From b38a33308d0394d212eb5d96e978955aa42c2fe6 Mon Sep 17 00:00:00 2001 From: Mraksimus Date: Thu, 8 Oct 2026 20:26:09 +0300 Subject: [PATCH] Completed for a grade of three --- .gitignore | 1 + build.gradle.kts | 39 ++++- compose.yaml | 48 +++++- gradle/libs.versions.toml | 43 ++++- .../_template/config}/application.conf | 4 +- run/_template/config/authentication.conf | 4 + run/_template/config/database.conf | 9 ++ scripts/init-secrets.sh | 16 ++ scripts/restart.sh | 7 + .../kotlin/com/mtusi/messenger/main/App.kt | 29 ++-- .../main/compat/serializers/UUIDSerializer.kt | 31 ++++ .../messenger/main/config/ConfigModule.kt | 8 + .../authentication/AuthenticationConfig.kt | 8 + .../DefaultAuthenticationConfig.kt | 11 ++ .../SerialAuthenticationConfig.kt | 9 ++ .../main/config/database/DatabaseConfig.kt | 19 +++ .../config/database/DefaultDatabaseConfig.kt | 11 ++ .../config/database/SerialDatabaseConfig.kt | 15 ++ .../main/extensions/ApplicationCall.kt | 31 ++-- .../_common/parameters/PageParameters.kt | 31 ++++ .../AuthenticationController.kt | 55 +++++++ .../responses/SessionResponse.kt | 13 ++ .../controllers/chat/ChatController.kt | 131 ++++++++++----- .../chat/responses/ChatPageResponse.kt | 10 -- .../controllers/health/HealthController.kt | 21 +++ .../controllers/message/MessageController.kt | 103 +++++++----- .../message/responses/MessagePageResponse.kt | 10 -- .../controllers/user/UserController.kt | 62 +++++-- .../user/requests/CreateUserRequest.kt | 1 + .../messenger/main/infrastructure/dto/Chat.kt | 8 +- .../main/infrastructure/dto/Message.kt | 10 +- .../main/infrastructure/dto/PageResponse.kt | 9 ++ .../messenger/main/infrastructure/dto/User.kt | 6 +- .../dto/authentication/IssuedSession.kt | 6 + .../dto/authentication/Session.kt | 11 ++ .../dto/authentication/UserCredentials.kt | 8 + .../models/authentication/SessionModel.kt | 13 ++ .../models/chat/ChatMemberModel.kt | 13 ++ .../infrastructure/models/chat/ChatModel.kt | 12 ++ .../models/message/MessageModel.kt | 16 ++ .../infrastructure/models/user/UserModel.kt | 14 ++ .../repositories/RepositoriesModule.kt | 8 + .../session/ExposedSessionRepository.kt | 67 ++++++++ .../session/SessionRepository.kt | 25 +++ .../repositories/chat/ChatRepository.kt | 29 +++- .../chat/ExposedChatRepository.kt | 134 ++++++++++++++++ .../chat/InMemoryChatRepository.kt | 24 --- .../message/ExposedMessageRepository.kt | 81 ++++++++++ .../message/InMemoryMessageRepository.kt | 45 ------ .../repositories/message/MessageRepository.kt | 19 ++- .../user/ExposedUserRepository.kt | 82 ++++++++++ .../user/InMemoryUserRepository.kt | 18 --- .../repositories/user/UserRepository.kt | 24 ++- .../infrastructure/services/ServicesModule.kt | 8 + .../authentication/AuthenticationService.kt | 27 ++++ .../DefaultAuthenticationService.kt | 91 +++++++++++ .../services/chat/ChatService.kt | 26 +-- .../services/chat/DefaultChatService.kt | 95 +++++------ .../chat/results/ChatCreationResult.kt | 17 ++ .../services/chat/results/ChatPageResult.kt | 16 ++ .../services/hashing/DefaultHashingService.kt | 123 ++++++++++++++ .../services/hashing/HashingService.kt | 18 +++ .../hashing/types/HashingAlgorithm.kt | 5 + .../services/message/DefaultMessageService.kt | 92 +++++------ .../services/message/MessageService.kt | 25 +-- .../message/results/MessageCreationResult.kt | 15 ++ .../message/results/MessagePageResult.kt | 17 ++ .../services/user/DefaultUserService.kt | 42 +++-- .../services/user/UserService.kt | 15 +- .../user/results/UserCreationResult.kt | 15 ++ .../infrastructure/types/AuthChallenge.kt | 6 + .../mtusi/messenger/main/plugins/Database.kt | 70 ++++++++ .../messenger/main/plugins/Dependencies.kt | 11 -- .../com/mtusi/messenger/main/plugins/Koin.kt | 27 ++++ .../mtusi/messenger/main/plugins/Routing.kt | 10 +- .../messenger/main/plugins/StatusPages.kt | 24 ++- .../plugins/authentication/Authentication.kt | 48 ++++++ .../authentication/CredentialsPrincipal.kt | 7 + .../plugins/authentication/UserPrincipal.kt | 8 + .../providers/BasicCredentialsProvider.kt | 66 ++++++++ .../providers/BearerSessionProvider.kt | 71 ++++++++ .../com/mtusi/messenger/main/utils/Hashing.kt | 10 ++ .../com/mtusi/messenger/main/utils/Page.kt | 6 - .../mtusi/messenger/main/utils/Pagination.kt | 66 +++++--- .../com/mtusi/messenger/main/utils/Time.kt | 21 ++- .../mtusi/messenger/main/utils/Validation.kt | 11 +- .../utils/exposed/operations/RowGreater.kt | 32 ++++ src/main/resources/application.conf | 22 +++ src/main/resources/migrations/V1__init.sql | 50 ++++++ .../AuthenticationControllerTest.kt | 151 ++++++++++++++++++ .../controllers/chat/ChatControllerTest.kt | 133 +++++++++++++-- .../health/HealthControllerTest.kt | 2 +- .../message/MessageConcurrencyTest.kt | 15 +- .../message/MessageControllerTest.kt | 59 +++---- .../controllers/user/UserControllerTest.kt | 132 +++++++++++++-- .../message/InMemoryMessageRepositoryTest.kt | 58 ------- .../hashing/DefaultHashingServiceTest.kt | 45 ++++++ .../main/plugins/DatabaseMigrationTest.kt | 49 ++++++ .../mtusi/messenger/main/support/TestApp.kt | 91 +++++++++-- .../messenger/main/support/TestDatabase.kt | 24 +++ 100 files changed, 2832 insertions(+), 602 deletions(-) rename {src/test/resources => run/_template/config}/application.conf (87%) create mode 100644 run/_template/config/authentication.conf create mode 100644 run/_template/config/database.conf create mode 100755 scripts/init-secrets.sh create mode 100755 scripts/restart.sh create mode 100644 src/main/kotlin/com/mtusi/messenger/main/compat/serializers/UUIDSerializer.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/ConfigModule.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/authentication/DefaultAuthenticationConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/database/DefaultDatabaseConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/_common/parameters/PageParameters.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/responses/SessionResponse.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/PageResponse.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/IssuedSession.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/UserCredentials.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/user/UserModel.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/RepositoriesModule.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepository.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/ExposedUserRepository.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/ServicesModule.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatCreationResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatPageResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/HashingService.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/types/HashingAlgorithm.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessageCreationResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessagePageResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/results/UserCreationResult.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/AuthChallenge.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/Koin.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/CredentialsPrincipal.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BasicCredentialsProvider.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BearerSessionProvider.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Hashing.kt delete mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt create mode 100644 src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/RowGreater.kt create mode 100644 src/main/resources/migrations/V1__init.sql create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationControllerTest.kt delete mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingServiceTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/plugins/DatabaseMigrationTest.kt create mode 100644 src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt diff --git a/.gitignore b/.gitignore index 0fe411f8..6137e904 100644 --- a/.gitignore +++ b/.gitignore @@ -31,5 +31,6 @@ coverage/ .gradle/ .kotlin/ !gradle/wrapper/ +/run/development/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. diff --git a/build.gradle.kts b/build.gradle.kts index d7d24c0e..cfb31b6c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,12 +1,13 @@ plugins { alias(libs.plugins.kotlin) alias(libs.plugins.kotlin.serialization) + alias(libs.plugins.ksp) alias(libs.plugins.shadow) id("application") } group = "com.mtusi.messenger" -version = "1.0.0" +version = "2.0.0" repositories { mavenCentral() @@ -14,10 +15,12 @@ repositories { dependencies { implementation(libs.kotlinx.serialization.json) + implementation(libs.kotlinx.serialization.hocon) implementation(libs.logback.classic) implementation(ktorLibs.server.core) implementation(ktorLibs.server.netty) + implementation(ktorLibs.server.auth) implementation(ktorLibs.server.contentNegotiation) implementation(ktorLibs.server.statusPages) implementation(ktorLibs.server.callLogging) @@ -25,16 +28,40 @@ dependencies { implementation(ktorLibs.server.swagger) implementation(ktorLibs.serialization.kotlinx.json) + implementation(libs.koin.core) + implementation(libs.koin.ktor) + implementation(libs.koin.annotations) + ksp(libs.koin.compiler) + + implementation(libs.exposed.core) + implementation(libs.exposed.jdbc) + implementation(libs.exposed.kotlin.datetime) + + implementation(libs.postgres) + implementation(libs.hikaricp) + implementation(libs.flyway) + implementation(libs.flyway.postgresql) + + implementation(libs.bouncycastle) + testImplementation(kotlin("test")) testImplementation(ktorLibs.server.testHost) testImplementation(ktorLibs.client.contentNegotiation) testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.koin.test) + testImplementation(libs.testContainers) + testImplementation(libs.testContainers.postgresql) } kotlin { jvmToolchain(21) } +ksp { + arg("KOIN_CONFIG_CHECK", "true") + arg("KOIN_DEFAULT_MODULE", "false") +} + application { mainClass = "io.ktor.server.netty.EngineMain" applicationDefaultJvmArgs = listOf("-Dio.ktor.development=false") @@ -61,6 +88,16 @@ tasks { } getByName("run") { + + val configArgs = File("run/development/config") + .listFiles() + ?.filter { it.extension == "conf" } + ?.map { + "-config=config/${it.name}" + } + ?: emptyList() + + args = configArgs workingDir = file("run/development") } } diff --git a/compose.yaml b/compose.yaml index 31417a30..5e562850 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,11 +1,51 @@ +name: mtusi-messenger-lab2 + services: - messenger: + + postgres: + image: postgres:17.6-alpine3.22 + container_name: mtusi-lab2-postgres + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: + - db_password + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 10s + restart: unless-stopped + + api: build: . image: mtusi-messenger:lab2 - container_name: mtusi-messenger-lab2 - ports: - - "127.0.0.1:8080:8080" + container_name: mtusi-lab2-api + depends_on: + postgres: + condition: service_healthy environment: APP_HOST: "0.0.0.0" APP_PORT: "8080" + DB_HOST: postgres + DB_PORT: "5432" + DB_NAME: messenger + DB_USER: messenger + DB_PASSWORD_FILE: /run/secrets/db_password + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + secrets: + - db_password + ports: + - "127.0.0.1:8080:8080" restart: unless-stopped + +secrets: + db_password: + file: ./secrets/db_password + +volumes: + postgres-data: diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5e51593a..ad76a4c8 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,16 +1,49 @@ [versions] -kotlin = "2.1.21" -kotlinx-serialization = "1.8.0" -logback = "1.5.12" -shadow = "8.3.5" +kotlin = "2.3.20" +ksp = "2.3.0" +kotlinx-serialization = "1.10.0" kotlinx-coroutines = "1.9.0" +logback = "1.5.13" +shadow = "8.3.5" +koin = "4.1.0-RC1" +koin-ktor = "4.1.0-Beta8" +koin-compiler = "2.0.0" +exposed = "1.0.0" +postgres = "42.7.3" +hikaricp = "6.3.0" +flyway = "11.9.0" +bouncycastle = "1.81" +test-containers = "1.21.0" [plugins] kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } [libraries] kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } -logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } +kotlinx-serialization-hocon = { module = "org.jetbrains.kotlinx:kotlinx-serialization-hocon", version.ref = "kotlinx-serialization" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" } + +logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } + +koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" } +koin-ktor = { module = "io.insert-koin:koin-ktor3", version.ref = "koin-ktor" } +koin-annotations = { module = "io.insert-koin:koin-annotations", version.ref = "koin-compiler" } +koin-compiler = { module = "io.insert-koin:koin-ksp-compiler", version.ref = "koin-compiler" } +koin-test = { module = "io.insert-koin:koin-test", version.ref = "koin" } + +exposed-core = { module = "org.jetbrains.exposed:exposed-core", version.ref = "exposed" } +exposed-jdbc = { module = "org.jetbrains.exposed:exposed-jdbc", version.ref = "exposed" } +exposed-kotlin-datetime = { module = "org.jetbrains.exposed:exposed-kotlin-datetime", version.ref = "exposed" } + +postgres = { module = "org.postgresql:postgresql", version.ref = "postgres" } +hikaricp = { module = "com.zaxxer:HikariCP", version.ref = "hikaricp" } +flyway = { module = "org.flywaydb:flyway-core", version.ref = "flyway" } +flyway-postgresql = { module = "org.flywaydb:flyway-database-postgresql", version.ref = "flyway" } + +bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" } + +testContainers = { module = "org.testcontainers:testcontainers", version.ref = "test-containers" } +testContainers-postgresql = { module = "org.testcontainers:postgresql", version.ref = "test-containers" } diff --git a/src/test/resources/application.conf b/run/_template/config/application.conf similarity index 87% rename from src/test/resources/application.conf rename to run/_template/config/application.conf index cbc3abad..d9373003 100644 --- a/src/test/resources/application.conf +++ b/run/_template/config/application.conf @@ -1,10 +1,12 @@ ktor { + application { modules = [com.mtusi.messenger.main.AppKt.module] } deployment { host = "127.0.0.1" - port = 0 + port = 8080 } + } diff --git a/run/_template/config/authentication.conf b/run/_template/config/authentication.conf new file mode 100644 index 00000000..8debebf3 --- /dev/null +++ b/run/_template/config/authentication.conf @@ -0,0 +1,4 @@ +authentication { + realm = "messenger" + sessionTtlSeconds = 3600 +} diff --git a/run/_template/config/database.conf b/run/_template/config/database.conf new file mode 100644 index 00000000..6de16a67 --- /dev/null +++ b/run/_template/config/database.conf @@ -0,0 +1,9 @@ +database { + host = "localhost" + port = 5432 + name = "messenger" + username = "username" + password = "password" + maxPoolSize = 10 + connectionTimeoutMs = 2000 +} diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 00000000..1700f205 --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Creates local secrets for the Compose stack. Never overwrites an existing secret: +# the PostgreSQL volume is initialised with the first password and keeps it. +set -eu +cd "$(dirname "$0")/.." + +mkdir -p secrets + +if [ ! -s secrets/db_password ]; then + # Readable by the non-root users inside the api/postgres containers (bind-mounted as is). + umask 022 + openssl rand -hex 24 > secrets/db_password + echo "created secrets/db_password" +else + echo "secrets/db_password already exists, keeping it" +fi diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..6fd26f11 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Restarts the API and PostgreSQL, keeping the named volume (no `down -v`, no re-seed). +set -eu +cd "$(dirname "$0")/.." + +docker compose stop api postgres +docker compose up -d --wait postgres api diff --git a/src/main/kotlin/com/mtusi/messenger/main/App.kt b/src/main/kotlin/com/mtusi/messenger/main/App.kt index 366cb856..31e47039 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/App.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/App.kt @@ -1,15 +1,11 @@ package com.mtusi.messenger.main -import com.mtusi.messenger.main.infrastructure.repositories.chat.InMemoryChatRepository -import com.mtusi.messenger.main.infrastructure.repositories.message.InMemoryMessageRepository -import com.mtusi.messenger.main.infrastructure.repositories.user.InMemoryUserRepository -import com.mtusi.messenger.main.infrastructure.services.chat.DefaultChatService -import com.mtusi.messenger.main.infrastructure.services.message.DefaultMessageService -import com.mtusi.messenger.main.infrastructure.services.user.DefaultUserService -import com.mtusi.messenger.main.plugins.Dependencies +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.configureRequestId import com.mtusi.messenger.main.plugins.configureRouting import com.mtusi.messenger.main.plugins.configureStatusPages @@ -19,24 +15,17 @@ import io.ktor.server.netty.EngineMain fun main(args: Array): Unit = EngineMain.main(args) fun Application.module() { - val userRepository = InMemoryUserRepository() - val chatRepository = InMemoryChatRepository() - val messageRepository = InMemoryMessageRepository() - val userService = DefaultUserService(userRepository) - val chatService = DefaultChatService(chatRepository, userRepository) - val messageService = DefaultMessageService(chatRepository, messageRepository) - - val dependencies = Dependencies( - userService = userService, - chatService = chatService, - messageService = messageService, - ) + configureKoin() + configureDatabase() configureContentNegotiation() configureDefaultHeaders() configureRequestId() configureCallLogging() configureStatusPages() - configureRouting(dependencies) + + configureAuthentication() + configureRouting() + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/compat/serializers/UUIDSerializer.kt b/src/main/kotlin/com/mtusi/messenger/main/compat/serializers/UUIDSerializer.kt new file mode 100644 index 00000000..5a1ccff8 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/compat/serializers/UUIDSerializer.kt @@ -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 { + + 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()) + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/ConfigModule.kt b/src/main/kotlin/com/mtusi/messenger/main/config/ConfigModule.kt new file mode 100644 index 00000000..e4763008 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/ConfigModule.kt @@ -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 diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt new file mode 100644 index 00000000..bef24b8f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/AuthenticationConfig.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.config.authentication + +interface AuthenticationConfig { + + val realm: String + val sessionTtlSeconds: Long + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/DefaultAuthenticationConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/DefaultAuthenticationConfig.kt new file mode 100644 index 00000000..7be2ab3f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/DefaultAuthenticationConfig.kt @@ -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() diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt new file mode 100644 index 00000000..aa2f51cf --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/authentication/SerialAuthenticationConfig.kt @@ -0,0 +1,9 @@ +package com.mtusi.messenger.main.config.authentication + +import kotlinx.serialization.Serializable + +@Serializable +data class SerialAuthenticationConfig( + override val realm: String, + override val sessionTtlSeconds: Long +) : AuthenticationConfig diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt new file mode 100644 index 00000000..e679f562 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/database/DatabaseConfig.kt @@ -0,0 +1,19 @@ +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 jdbcConnectionUrl: String + get() = "jdbc:postgresql://$host:$port/$name" + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/database/DefaultDatabaseConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/database/DefaultDatabaseConfig.kt new file mode 100644 index 00000000..72a6c044 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/database/DefaultDatabaseConfig.kt @@ -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() diff --git a/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt b/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt new file mode 100644 index 00000000..c4f11b84 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/config/database/SerialDatabaseConfig.kt @@ -0,0 +1,15 @@ +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 +) : DatabaseConfig diff --git a/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt b/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt index c6b1bb5b..0fc40818 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/extensions/ApplicationCall.kt @@ -1,11 +1,12 @@ package com.mtusi.messenger.main.extensions -import com.mtusi.messenger.main.infrastructure.dto.User -import com.mtusi.messenger.main.infrastructure.services.user.UserService -import com.mtusi.messenger.main.infrastructure.types.ApiException +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 @@ -20,25 +21,17 @@ data class ErrorDetails( val requestId: String, ) -suspend fun ApplicationCall.respondError(code: ErrorCode, message: String) { +suspend fun ApplicationCall.respondError( + code: ErrorCode, + message: String, + challenge: String = AuthChallenge.BEARER, +) { val requestId = attributes[RequestIdKey] if (code == ErrorCode.UNAUTHORIZED) { - response.header("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"") + response.header(HttpHeaders.WWWAuthenticate, challenge) } respond(code.status, ErrorBody(ErrorDetails(code.wire, message, requestId))) } -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 isValidUuid(value: String): Boolean = UUID_REGEX.matches(value) - -fun ApplicationCall.requireCurrentUser(userService: UserService): User { - val header = request.headers["X-User-Id"]?.trim() - if (header.isNullOrEmpty() || !isValidUuid(header)) { - throw ApiException(ErrorCode.UNAUTHORIZED, "missing or invalid X-User-Id") - } - return userService.findById(header) - ?: throw ApiException(ErrorCode.UNAUTHORIZED, "unknown user") -} +val ApplicationCall.currentUser: UserPrincipal + get() = principal()!! diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/_common/parameters/PageParameters.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/_common/parameters/PageParameters.kt new file mode 100644 index 00000000..043b686e --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/_common/parameters/PageParameters.kt @@ -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) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt new file mode 100644 index 00000000..90f6e012 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationController.kt @@ -0,0 +1,55 @@ +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() + + authenticate(CREDENTIALS_AUTH) { + post { + + val (user) = call.principal()!! + + 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") { + + suspendedTransaction { + authenticationService.revokeSession(call.currentUser.sessionId) + } + + call.respond(HttpStatusCode.NoContent) + } + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/responses/SessionResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/responses/SessionResponse.kt new file mode 100644 index 00000000..f9c4e343 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/responses/SessionResponse.kt @@ -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, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt index 8f252d8e..e2fd839a 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatController.kt @@ -1,67 +1,112 @@ package com.mtusi.messenger.main.infrastructure.controllers.chat -import com.mtusi.messenger.main.extensions.requireCurrentUser +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.controllers.chat.responses.ChatPageResponse +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.user.UserService +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 -private const val TITLE_MAX = 100 +fun Routing.configureChatRouting() = route("/api/v1/chats") { -fun Routing.configureChatRouting( - chatService: ChatService, - userService: UserService, -) = route("/api/v1/chats") { + val chatService by inject() - post { + authenticate(SESSION_AUTH) { - val actor = call.requireCurrentUser(userService) - val body = call.receive() + post { - requireNonBlankBounded( - body.title, - min = 1, - max = TITLE_MAX, - field = "title" - ) + val actor = call.currentUser + val body = call.receive() + + 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) + } - val chat = chatService.create(actor.id, body.title, body.memberIds) - call.respond(HttpStatusCode.Created, chat) } - get { - - val actor = call.requireCurrentUser(userService) - - val page = chatService.findPageAccessible( - userId = actor.id, - rawLimit = call.request.queryParameters["limit"], - rawCursor = call.request.queryParameters["cursor"], - ) - - call.respond(HttpStatusCode.OK, ChatPageResponse(page.items, page.nextCursor)) - } - - get("{chat_id}") { - - val actor = call.requireCurrentUser(userService) - val chatId = call.parameters["chat_id"] - ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") - - requireUuid(chatId, "chat_id") - - val chat = chatService.findAccessible(actor.id, chatId) - call.respond(HttpStatusCode.OK, chat) - } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt deleted file mode 100644 index 49a29440..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/responses/ChatPageResponse.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.controllers.chat.responses - -import com.mtusi.messenger.main.infrastructure.dto.Chat -import kotlinx.serialization.Serializable - -@Serializable -data class ChatPageResponse( - val items: List, - val nextCursor: String?, -) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt index 7f9b836c..51465719 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthController.kt @@ -1,7 +1,11 @@ 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 @@ -13,7 +17,24 @@ fun Routing.configureHealthRouting() = route("/health") { 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()) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt index f956039e..d1b02be5 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageController.kt @@ -1,65 +1,88 @@ package com.mtusi.messenger.main.infrastructure.controllers.message -import com.mtusi.messenger.main.extensions.requireCurrentUser +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.controllers.message.responses.MessagePageResponse +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.user.UserService -import com.mtusi.messenger.main.infrastructure.types.ApiException +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 -private const val TEXT_MAX = 4000 +fun Routing.configureMessageRouting() = route("/api/v1/chats/{chat_id}/messages") { -fun Routing.configureMessageRouting( - messageService: MessageService, - userService: UserService, -) = route("/api/v1/chats/{chat_id}/messages") { + val messageService by inject() - post { + authenticate(SESSION_AUTH) { - val actor = call.requireCurrentUser(userService) - val chatId = call.parameters["chat_id"] - ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") + post { - requireUuid(chatId, "chat_id") + val actor = call.currentUser + val chatId = requireUuid(call.parameters["chat_id"], "chat_id") + val body = call.receive() - val body = call.receive() + requireNonBlankBounded( + body.text, + min = 1, + max = MAX_MESSAGE_TEXT_LENGTH, + field = "text" + ) - requireNonBlankBounded( - body.text, - min = 1, - max = TEXT_MAX, - 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) + } + } - val message = messageService.send(chatId, actor.id, body.text) - call.respond(HttpStatusCode.Created, message) } - get { - - val actor = call.requireCurrentUser(userService) - val chatId = call.parameters["chat_id"] - ?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id") - - requireUuid(chatId, "chat_id") - - val page = messageService.findPageByChatId( - chatId = chatId, - actorId = actor.id, - rawLimit = call.request.queryParameters["limit"], - rawCursor = call.request.queryParameters["cursor"], - ) - - call.respond(HttpStatusCode.OK, MessagePageResponse(page.items, page.nextCursor)) - } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt deleted file mode 100644 index e2bd1fc4..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/responses/MessagePageResponse.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.controllers.message.responses - -import com.mtusi.messenger.main.infrastructure.dto.Message -import kotlinx.serialization.Serializable - -@Serializable -data class MessagePageResponse( - val items: List, - val nextCursor: String?, -) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt index a398b623..d49bc9a9 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserController.kt @@ -1,23 +1,35 @@ package com.mtusi.messenger.main.infrastructure.controllers.user -import com.mtusi.messenger.main.extensions.requireCurrentUser +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 DISPLAY_NAME_MAX = 100 +private const val PASSWORD_MIN = 12 +private const val PASSWORD_MAX = 128 -fun Routing.configureUserRouting(userService: UserService) = route("/api/v1/users") { +fun Routing.configureUserRouting() = route("/api/v1/users") { + + val userService by inject() post { + val body = call.receive() requireUsername(body.username) @@ -25,17 +37,47 @@ fun Routing.configureUserRouting(userService: UserService) = route("/api/v1/user requireNonBlankBounded( body.displayName, min = 1, - max = DISPLAY_NAME_MAX, - field = "displayName" + max = MAX_DISPLAY_NAME_LENGTH, + field = "display_name" ) - val user = userService.create(body.username, body.displayName) - call.respond(HttpStatusCode.Created, user) + 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) + } } - get("me") { - val user = call.requireCurrentUser(userService) - call.respond(HttpStatusCode.OK, 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) + } } } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt index d7a9dbf1..0e7bb113 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/requests/CreateUserRequest.kt @@ -6,4 +6,5 @@ import kotlinx.serialization.Serializable data class CreateUserRequest( val username: String, val displayName: String, + val password: String, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt index 84a57b85..846d6c82 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Chat.kt @@ -1,11 +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: String, + val id: SerialUUID, val title: String, - val memberIds: List, - val createdAt: String, + val memberIds: List, + val createdAt: Instant, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt index 979b8d32..15e30304 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/Message.kt @@ -1,12 +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: String, - val chatId: String, - val senderId: String, + val id: SerialUUID, + val chatId: SerialUUID, + val senderId: SerialUUID, val text: String, - val createdAt: String, + val createdAt: Instant, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/PageResponse.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/PageResponse.kt new file mode 100644 index 00000000..28fa6dce --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/PageResponse.kt @@ -0,0 +1,9 @@ +package com.mtusi.messenger.main.infrastructure.dto + +import kotlinx.serialization.Serializable + +@Serializable +data class PageResponse( + val items: List, + val nextCursor: String?, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt index b6ed9b92..4f768822 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/User.kt @@ -1,11 +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: String, + val id: SerialUUID, val username: String, val displayName: String, - val createdAt: String, + val createdAt: Instant, ) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/IssuedSession.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/IssuedSession.kt new file mode 100644 index 00000000..480607bf --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/IssuedSession.kt @@ -0,0 +1,6 @@ +package com.mtusi.messenger.main.infrastructure.dto.authentication + +data class IssuedSession( + val session: Session, + val token: String, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt new file mode 100644 index 00000000..4734da86 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/Session.kt @@ -0,0 +1,11 @@ +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 createdAt: Instant, + val expiresAt: Instant, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/UserCredentials.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/UserCredentials.kt new file mode 100644 index 00000000..2533ff71 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/dto/authentication/UserCredentials.kt @@ -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, +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt new file mode 100644 index 00000000..cfc1d7e3 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/authentication/SessionModel.kt @@ -0,0 +1,13 @@ +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) + val tokenHash = varchar("token_hash", 64).uniqueIndex("sessions_token_hash_key") + val createdAt = timestamp("created_at") + val expiresAt = timestamp("expires_at") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt new file mode 100644 index 00000000..acbcb0fb --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatMemberModel.kt @@ -0,0 +1,13 @@ +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) + val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE) + val position = integer("position") + + override val primaryKey = PrimaryKey(chatId, userId) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatModel.kt new file mode 100644 index 00000000..984fbfd8 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/chat/ChatModel.kt @@ -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") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt new file mode 100644 index 00000000..9d90d600 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/message/MessageModel.kt @@ -0,0 +1,16 @@ +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) + val senderId = reference("sender_id", UserModel, onDelete = ReferenceOption.CASCADE) + val text = varchar("text", MAX_MESSAGE_TEXT_LENGTH) + val createdAt = timestamp("created_at") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/user/UserModel.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/user/UserModel.kt new file mode 100644 index 00000000..8dfa1664 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/models/user/UserModel.kt @@ -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") +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/RepositoriesModule.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/RepositoriesModule.kt new file mode 100644 index 00000000..b5d76471 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/RepositoriesModule.kt @@ -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 diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt new file mode 100644 index 00000000..41f87e76 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/ExposedSessionRepository.kt @@ -0,0 +1,67 @@ +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.Instant + +@Single +class ExposedSessionRepository : SessionRepository { + + override fun create( + userId: UUID, + tokenHash: String, + expiresAt: Instant + ): Session { + + val insertedRow = SessionModel.insert { + it[this.userId] = userId + it[this.tokenHash] = tokenHash + it[this.createdAt] = Clock.System.nowMicros() + it[this.expiresAt] = expiresAt + } + + return Session( + id = insertedRow[SessionModel.id].value, + userId = userId, + createdAt = insertedRow[SessionModel.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, + createdAt = this[SessionModel.createdAt], + expiresAt = this[SessionModel.expiresAt] + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt new file mode 100644 index 00000000..d5bb2256 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/authentication/session/SessionRepository.kt @@ -0,0 +1,25 @@ +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.Instant + +interface SessionRepository : Repository { + + fun create( + userId: UUID, + tokenHash: String, + expiresAt: Instant + ): Session + + fun findActiveByTokenHash( + tokenHash: String, + now: Instant + ): Session? + + fun deleteById( + id: UUID + ): Boolean + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt index de0bc6ae..956e9dfc 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ChatRepository.kt @@ -2,11 +2,32 @@ 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 { - fun findById(id: String): Chat? +interface ChatRepository : Repository { - fun insert(chat: Chat) + fun create( + title: String, + memberIds: List + ): 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 - fun findAllAccessible(userId: String): List } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepository.kt new file mode 100644 index 00000000..2afe352d --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/ExposedChatRepository.kt @@ -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 + ): 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 { + + 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 + ): Map> { + + 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) = Chat( + id = this[ChatModel.id].value, + title = this[ChatModel.title], + memberIds = memberIds, + createdAt = this[ChatModel.createdAt] + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt deleted file mode 100644 index b84d6e57..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/chat/InMemoryChatRepository.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.repositories.chat - -import com.mtusi.messenger.main.infrastructure.dto.Chat -import java.util.concurrent.ConcurrentHashMap - -class InMemoryChatRepository : ChatRepository { - private val byId = ConcurrentHashMap() - - override fun findById(id: String): Chat? = byId[id] - - override fun insert(chat: Chat) { - byId[chat.id] = chat - } - - override fun findAllAccessible(userId: String): List = - byId.values - .filter { userId in it.memberIds } - .sortedWith( - compareBy( - { it.createdAt }, - { it.id } - ) - ) -} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt new file mode 100644 index 00000000..19dc19c4 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/ExposedMessageRepository.kt @@ -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 { + + 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] + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt deleted file mode 100644 index 371c0609..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepository.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.repositories.message - -import com.mtusi.messenger.main.infrastructure.dto.Message -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.CopyOnWriteArrayList - -class InMemoryMessageRepository : MessageRepository { - private val byChat = ConcurrentHashMap>() - private val locks = ConcurrentHashMap() - - override fun append( - chatId: String, - message: Message - ) { - - val lock = locks.computeIfAbsent(chatId) { - Any() - } - - synchronized(lock) { - byChat.computeIfAbsent(chatId) { - CopyOnWriteArrayList() - }.add(message) - } - } - - override fun findRangeByChatId( - chatId: String, - offset: Int, - count: Int, - ): List { - - val messages = byChat[chatId] - ?: return emptyList() - - // Append-only: indices below an observed size never change, so no snapshot copy is needed. - val end = minOf(messages.size, offset + count) - - if (offset >= end) { - return emptyList() - } - - return List(end - offset) { messages[offset + it] } - } -} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt index a0279d91..80a130d2 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/MessageRepository.kt @@ -2,8 +2,21 @@ 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 { + + fun create( + chatId: UUID, + senderId: UUID, + text: String + ): Message + + fun findPageByChatId( + chatId: UUID, + after: PageKey?, + limit: Int + ): List -interface MessageRepository : Repository { - fun append(chatId: String, message: Message) - fun findRangeByChatId(chatId: String, offset: Int, count: Int): List } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/ExposedUserRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/ExposedUserRepository.kt new file mode 100644 index 00000000..404a333f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/ExposedUserRepository.kt @@ -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 + ): 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] + ) + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt deleted file mode 100644 index 125bae78..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/InMemoryUserRepository.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.repositories.user - -import com.mtusi.messenger.main.infrastructure.dto.User -import java.util.concurrent.ConcurrentHashMap - -class InMemoryUserRepository : UserRepository { - private val byId = ConcurrentHashMap() - - override fun insert(user: User) { - byId[user.id] = user - } - - override fun findById(id: String): User? = byId[id] - - override fun findByUsername(username: String): User? { - return byId.values.find { it.username == username } - } -} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt index 62da5146..0773d071 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/repositories/user/UserRepository.kt @@ -1,12 +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 { - fun insert(user: User) +interface UserRepository : Repository { - fun findById(id: String): User? + fun create( + username: String, + displayName: String, + passwordHash: String + ): User? + + fun findById( + id: UUID + ): User? + + fun findCredentialsByUsername( + username: String + ): UserCredentials? + + fun countByIds( + ids: Collection + ): Long - fun findByUsername(username: String): User? } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/ServicesModule.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/ServicesModule.kt new file mode 100644 index 00000000..d7d75fc9 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/ServicesModule.kt @@ -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 diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt new file mode 100644 index 00000000..6ef710d0 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/AuthenticationService.kt @@ -0,0 +1,27 @@ +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 + + fun findSessionByToken( + token: String + ): Session? + + fun revokeSession( + sessionId: UUID + ): Boolean + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt new file mode 100644 index 00000000..960be0ad --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/authentication/DefaultAuthenticationService.kt @@ -0,0 +1,91 @@ +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.repositories.authentication.session.SessionRepository +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.utils.computeSha256 +import com.mtusi.messenger.main.utils.nowMicros +import org.koin.core.annotation.Single +import java.security.SecureRandom +import java.util.Base64 +import java.util.UUID +import kotlin.time.Clock +import kotlin.time.Duration.Companion.seconds + +private const val TOKEN_BYTES = 32 + +@Single +class DefaultAuthenticationService( + private val userRepository: UserRepository, + private val sessionRepository: SessionRepository, + private val hashingService: HashingService, + private val config: AuthenticationConfig +) : AuthenticationService { + + private val random = SecureRandom() + + 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(), + expiresAt = Clock.System.nowMicros() + config.sessionTtlSeconds.seconds + ) + + return IssuedSession( + session = session, + token = token + ) + } + + override fun findSessionByToken( + token: String + ): Session? { + return sessionRepository.findActiveByTokenHash( + tokenHash = token.toByteArray().computeSha256(), + now = Clock.System.now() + ) + } + + override fun revokeSession( + sessionId: UUID + ): Boolean { + return sessionRepository.deleteById(sessionId) + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt index b21197e7..603abc9f 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/ChatService.kt @@ -1,23 +1,27 @@ package com.mtusi.messenger.main.infrastructure.services.chat import com.mtusi.messenger.main.infrastructure.dto.Chat -import com.mtusi.messenger.main.utils.Page +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: String, + creatorId: UUID, title: String, - memberIds: List, - ): Chat + memberIds: List + ): ChatCreationResult fun findAccessible( - userId: String, - chatId: String, - ): Chat + userId: UUID, + chatId: UUID + ): Chat? fun findPageAccessible( - userId: String, - rawLimit: String?, - rawCursor: String?, - ): Page + userId: UUID, + limit: Int, + cursor: String? + ): ChatPageResult + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt index 9678d267..b38620c5 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/DefaultChatService.kt @@ -1,92 +1,79 @@ package com.mtusi.messenger.main.infrastructure.services.chat -import com.mtusi.messenger.main.extensions.isValidUuid 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.types.ApiException -import com.mtusi.messenger.main.infrastructure.types.ErrorCode -import com.mtusi.messenger.main.utils.Page +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.encodeCursor -import com.mtusi.messenger.main.utils.nowIsoUtc -import com.mtusi.messenger.main.utils.parseLimit +import com.mtusi.messenger.main.utils.toPage +import org.koin.core.annotation.Single import java.util.UUID -private const val MAX_MEMBERS = 100 - +@Single class DefaultChatService( private val chatRepository: ChatRepository, - private val userRepository: UserRepository, + private val userRepository: UserRepository ) : ChatService { override fun create( - creatorId: String, + creatorId: UUID, title: String, - memberIds: List, - ): Chat { - - if (memberIds.isEmpty() || memberIds.size > MAX_MEMBERS) { - throw ApiException(ErrorCode.INVALID_REQUEST, "size out of range") - } + memberIds: List + ): ChatCreationResult { if (memberIds.toSet().size != memberIds.size) { - throw ApiException(ErrorCode.INVALID_REQUEST, "memberIds must be unique") + return ChatCreationResult.DuplicateMembers } if (creatorId !in memberIds) { - throw ApiException(ErrorCode.INVALID_REQUEST, "creator must be in members") + return ChatCreationResult.CreatorNotMember } - for (id in memberIds) { - if (!isValidUuid(id)) - throw ApiException(ErrorCode.INVALID_REQUEST, "invalid member id") - - if (userRepository.findById(id) == null) - throw ApiException(ErrorCode.INVALID_REQUEST, "unknown member") + if (userRepository.countByIds(memberIds) != memberIds.size.toLong()) { + return ChatCreationResult.UnknownMembers } - val chat = Chat( - id = UUID.randomUUID().toString(), + val chat = chatRepository.create( title = title, - memberIds = memberIds, - createdAt = nowIsoUtc(), + memberIds = memberIds ) - chatRepository.insert(chat) - return chat + return ChatCreationResult.Success(chat) } override fun findAccessible( - userId: String, - chatId: String, - ): Chat { - - val chat = chatRepository.findById(chatId) - ?: throw ApiException(ErrorCode.NOT_FOUND, "chat not found") - - if (userId !in chat.memberIds) { - throw ApiException(ErrorCode.NOT_FOUND, "chat not found") - } - - return chat + userId: UUID, + chatId: UUID + ): Chat? { + return chatRepository.findById(chatId) + ?.takeIf { userId in it.memberIds } } override fun findPageAccessible( - userId: String, - rawLimit: String?, - rawCursor: String?, - ): Page { + userId: UUID, + limit: Int, + cursor: String? + ): ChatPageResult { - val limit = parseLimit(rawLimit) val scope = "chats:$userId" - val start = rawCursor?.let { decodeCursor(it, scope) } ?: 0 - val all = chatRepository.findAllAccessible(userId) - val slice = all.drop(start).take(limit) - val nextIndex = start + slice.size - val nextCursor = if (nextIndex < all.size) encodeCursor(scope, nextIndex) else null + val after = cursor?.let { + decodeCursor(it, scope) ?: return ChatPageResult.InvalidCursor + } - return Page(slice, nextCursor) + val page = chatRepository + .findPageByMemberId( + userId = userId, + after = after, + limit = limit + 1 + ) + .toPage(limit, scope) { + PageKey(it.createdAt, it.id) + } + + return ChatPageResult.Success(page) } + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatCreationResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatCreationResult.kt new file mode 100644 index 00000000..61c35511 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatCreationResult.kt @@ -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() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatPageResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatPageResult.kt new file mode 100644 index 00000000..d347bad6 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/chat/results/ChatPageResult.kt @@ -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 + ) : ChatPageResult() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingService.kt new file mode 100644 index 00000000..d18110ac --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingService.kt @@ -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) + } + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/HashingService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/HashingService.kt new file mode 100644 index 00000000..0de59beb --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/HashingService.kt @@ -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 + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/types/HashingAlgorithm.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/types/HashingAlgorithm.kt new file mode 100644 index 00000000..8f39402b --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/types/HashingAlgorithm.kt @@ -0,0 +1,5 @@ +package com.mtusi.messenger.main.infrastructure.services.hashing.types + +sealed class HashingAlgorithm { + data object Argon2id : HashingAlgorithm() +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt index 52afe12c..800af6fe 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/DefaultMessageService.kt @@ -1,74 +1,68 @@ package com.mtusi.messenger.main.infrastructure.services.message -import com.mtusi.messenger.main.infrastructure.dto.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.types.ApiException -import com.mtusi.messenger.main.infrastructure.types.ErrorCode -import com.mtusi.messenger.main.utils.Page +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.encodeCursor -import com.mtusi.messenger.main.utils.nowIsoUtc -import com.mtusi.messenger.main.utils.parseLimit +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, + private val messageRepository: MessageRepository ) : MessageService { override fun send( - chatId: String, - senderId: String, - text: String, - ): Message { + chatId: UUID, + senderId: UUID, + text: String + ): MessageCreationResult { - requireChatMembership(chatId, senderId) + if (!chatRepository.isMember(chatId, senderId)) { + return MessageCreationResult.ChatNotFound + } - val message = Message( - id = UUID.randomUUID().toString(), + val message = messageRepository.create( chatId = chatId, senderId = senderId, - text = text, - createdAt = nowIsoUtc(), + text = text ) - messageRepository.append(chatId, message) - - return message + return MessageCreationResult.Success(message) } override fun findPageByChatId( - chatId: String, - actorId: String, - rawLimit: String?, - rawCursor: String?, - ): Page { + chatId: UUID, + actorId: UUID, + limit: Int, + cursor: String? + ): MessagePageResult { - requireChatMembership(chatId, actorId) - - val limit = parseLimit(rawLimit) - val scope = "messages:$chatId" - val start = rawCursor?.let { decodeCursor(it, scope) } ?: 0 - - val window = messageRepository.findRangeByChatId( - chatId = chatId, - offset = start, - count = limit + 1, - ) - - val items = window.take(limit) - val nextCursor = if (window.size > limit) encodeCursor(scope, start + limit) else null - - return Page(items, nextCursor) - } - - private fun requireChatMembership(chatId: String, userId: String) { - val chat = chatRepository.findById(chatId) - ?: throw ApiException(ErrorCode.NOT_FOUND, "chat not found") - - if (userId !in chat.memberIds) { - throw ApiException(ErrorCode.NOT_FOUND, "chat not found") + 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) } + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt index 24f54eb2..075c35d7 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/MessageService.kt @@ -1,19 +1,22 @@ package com.mtusi.messenger.main.infrastructure.services.message -import com.mtusi.messenger.main.infrastructure.dto.Message -import com.mtusi.messenger.main.utils.Page +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: String, - senderId: String, - text: String, - ): Message + chatId: UUID, + senderId: UUID, + text: String + ): MessageCreationResult fun findPageByChatId( - chatId: String, - actorId: String, - rawLimit: String?, - rawCursor: String?, - ): Page + chatId: UUID, + actorId: UUID, + limit: Int, + cursor: String? + ): MessagePageResult + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessageCreationResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessageCreationResult.kt new file mode 100644 index 00000000..d5ac9756 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessageCreationResult.kt @@ -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() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessagePageResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessagePageResult.kt new file mode 100644 index 00000000..254b1d52 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/message/results/MessagePageResult.kt @@ -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 + ) : MessagePageResult() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt index 7dd8f22b..618ca129 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/DefaultUserService.kt @@ -2,32 +2,42 @@ 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.types.ApiException -import com.mtusi.messenger.main.infrastructure.types.ErrorCode -import com.mtusi.messenger.main.utils.nowIsoUtc +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): User { + override fun create( + username: String, + displayName: String, + password: String + ): UserCreationResult { - if (userRepository.findByUsername(username) != null) { - throw ApiException(ErrorCode.CONFLICT, "username already taken") - } - - val user = User( - id = UUID.randomUUID().toString(), - username = username, - displayName = displayName, - createdAt = nowIsoUtc(), + val passwordHash = hashingService.computeHash( + algorithm = HashingAlgorithm.Argon2id, + input = password ) - userRepository.insert(user) + val user = userRepository.create( + username = username, + displayName = displayName, + passwordHash = passwordHash + ) ?: return UserCreationResult.UsernameTaken - return user + return UserCreationResult.Success(user) + } + + override fun findById( + id: UUID + ): User? { + return userRepository.findById(id) } - override fun findById(id: String): User? = userRepository.findById(id) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt index ad976c1c..da9528ed 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/UserService.kt @@ -1,8 +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): User - fun findById(id: String): User? + + fun create( + username: String, + displayName: String, + password: String + ): UserCreationResult + + fun findById( + id: UUID + ): User? + } diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/results/UserCreationResult.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/results/UserCreationResult.kt new file mode 100644 index 00000000..ae51bf5d --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/services/user/results/UserCreationResult.kt @@ -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() + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/AuthChallenge.kt b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/AuthChallenge.kt new file mode 100644 index 00000000..d8f23b56 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/infrastructure/types/AuthChallenge.kt @@ -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\"" +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt new file mode 100644 index 00000000..74b55b5f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Database.kt @@ -0,0 +1,70 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.config.database.DatabaseConfig +import com.zaxxer.hikari.HikariConfig +import com.zaxxer.hikari.HikariDataSource +import io.ktor.server.application.Application +import io.ktor.server.application.ApplicationStopped +import kotlinx.coroutines.Dispatchers +import org.flywaydb.core.Flyway +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.koin.ktor.ext.inject +import java.io.File +import javax.sql.DataSource + +fun Application.configureDatabase() { + + val config by inject() + + val dataSource = HikariDataSource( + HikariConfig().apply { + poolName = "messenger" + jdbcUrl = config.jdbcConnectionUrl + username = config.username + password = config.resolvePassword() + maximumPoolSize = config.maxPoolSize + connectionTimeout = config.connectionTimeoutMs + } + ) + + Database.connect( + datasource = dataSource, + databaseConfig = ExposedDatabaseConfig { + defaultMaxAttempts = 1 + } + ) + applyDatabaseMigrations(dataSource) + + monitor.subscribe(ApplicationStopped) { + dataSource.close() + } + +} + +private fun DatabaseConfig.resolvePassword(): String { + return password + ?: passwordFile?.let { File(it).readText().trim() } + ?: "" +} + +fun applyDatabaseMigrations( + dataSource: DataSource +) { + + val flyway = Flyway.configure() + .dataSource(dataSource) + .locations("classpath:migrations") + .load() + + flyway.migrate() + flyway.validate() + +} + +suspend fun suspendedTransaction(statement: JdbcTransaction.() -> R) = newSuspendedTransaction( + context = Dispatchers.IO, + statement = statement +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt deleted file mode 100644 index 46f4d02e..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/Dependencies.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.mtusi.messenger.main.plugins - -import com.mtusi.messenger.main.infrastructure.services.chat.ChatService -import com.mtusi.messenger.main.infrastructure.services.message.MessageService -import com.mtusi.messenger.main.infrastructure.services.user.UserService - -data class Dependencies( - val userService: UserService, - val chatService: ChatService, - val messageService: MessageService, -) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Koin.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Koin.kt new file mode 100644 index 00000000..6702609f --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Koin.kt @@ -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 + ) + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt index 8ce80a6d..5329f729 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/Routing.kt @@ -1,5 +1,6 @@ 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 @@ -7,10 +8,11 @@ import com.mtusi.messenger.main.infrastructure.controllers.user.configureUserRou import io.ktor.server.application.Application import io.ktor.server.routing.routing -fun Application.configureRouting(dependencies: Dependencies) = routing { +fun Application.configureRouting() = routing { configureSwaggerRouting() configureHealthRouting() - configureUserRouting(dependencies.userService) - configureChatRouting(dependencies.chatService, dependencies.userService) - configureMessageRouting(dependencies.messageService, dependencies.userService) + configureUserRouting() + configureAuthenticationRouting() + configureChatRouting() + configureMessageRouting() } diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt index b777ee92..41d58395 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/StatusPages.kt @@ -7,11 +7,16 @@ 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 kotlinx.serialization.SerializationException +import java.sql.SQLException +import java.sql.SQLTransientConnectionException + +private const val CONNECTION_ERROR_SQL_STATE_CLASS = "08" fun Application.configureStatusPages() = install(StatusPages) { exception { call, cause -> @@ -32,7 +37,17 @@ fun Application.configureStatusPages() = install(StatusPages) { exception { call, _ -> call.respondError(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "unsupported media type") } - exception { call, _ -> + exception { 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 { call, cause -> + call.application.log.error("Unhandled error", cause) call.respondError(ErrorCode.INTERNAL_ERROR, "internal error") } status(HttpStatusCode.NotFound) { call, _ -> @@ -42,3 +57,10 @@ fun Application.configureStatusPages() = install(StatusPages) { call.respondError(ErrorCode.NOT_FOUND, "not found") } } + +private fun SQLException.isConnectionFailure(): Boolean { + return generateSequence(this) { it.cause }.any { + it is SQLTransientConnectionException || + (it is SQLException && it.sqlState?.startsWith(CONNECTION_ERROR_SQL_STATE_CLASS) == true) + } +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt new file mode 100644 index 00000000..e0d7b8e3 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/Authentication.kt @@ -0,0 +1,48 @@ +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() + + 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 = suspendedTransaction { + authenticationService.findSessionByToken(token) + } ?: return@authenticate null + + return@authenticate UserPrincipal( + id = session.userId, + sessionId = session.id + ) + } + } + + } + +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/CredentialsPrincipal.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/CredentialsPrincipal.kt new file mode 100644 index 00000000..9a5684a3 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/CredentialsPrincipal.kt @@ -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 +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt new file mode 100644 index 00000000..b8870e9c --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/UserPrincipal.kt @@ -0,0 +1,8 @@ +package com.mtusi.messenger.main.plugins.authentication + +import java.util.UUID + +data class UserPrincipal( + val id: UUID, + val sessionId: UUID +) diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BasicCredentialsProvider.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BasicCredentialsProvider.kt new file mode 100644 index 00000000..f8ab4179 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BasicCredentialsProvider.kt @@ -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))) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BearerSessionProvider.kt b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BearerSessionProvider.kt new file mode 100644 index 00000000..9d3ad728 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/plugins/authentication/providers/BearerSessionProvider.kt @@ -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))) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Hashing.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Hashing.kt new file mode 100644 index 00000000..824b9059 --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Hashing.kt @@ -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() +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt deleted file mode 100644 index e4e8ce6e..00000000 --- a/src/main/kotlin/com/mtusi/messenger/main/utils/Page.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.mtusi.messenger.main.utils - -data class Page( - val items: List, - val nextCursor: String?, -) diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt index 415bca63..cd84ad28 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Pagination.kt @@ -1,40 +1,64 @@ 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.Base64 +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 const val DEFAULT_LIMIT = 50 -private const val MAX_LIMIT = 100 +private val json = Json { ignoreUnknownKeys = false } -private val json = Json { ignoreUnknownKeys = true } +/** + * 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 index: Int) +private data class Cursor( + val scope: String, + val createdAt: Instant, + val id: SerialUUID, +) -fun encodeCursor(scope: String, index: Int): String { - val raw = json.encodeToString(Cursor.serializer(), Cursor(scope, index)) +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)) } -fun decodeCursor(raw: String, expectedScope: String): Int { - val decoded = try { +/** + * @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 (_: Throwable) { - throw ApiException(ErrorCode.INVALID_REQUEST, "invalid cursor") + } catch (_: Exception) { + return null } - if (decoded.scope != expectedScope || decoded.index < 0) { - throw ApiException(ErrorCode.INVALID_REQUEST, "cursor does not belong to this resource") + + if (cursor.scope != expectedScope) { + return null } - return decoded.index + + return PageKey(cursor.createdAt, cursor.id) } -fun parseLimit(raw: String?): Int { - if (raw == null) return DEFAULT_LIMIT - val v = raw.toIntOrNull() ?: throw ApiException(ErrorCode.INVALID_REQUEST, "invalid limit") - if (v !in 1..MAX_LIMIT) throw ApiException(ErrorCode.INVALID_REQUEST, "limit out of range") - return v +/** + * Builds a page from `limit + 1` rows fetched after the cursor: the extra row only signals that more data exists. + */ +fun List.toPage( + limit: Int, + scope: String, + key: (T) -> PageKey, +): PageResponse { + + val items = take(limit) + val nextCursor = if (size > limit) encodeCursor(scope, key(items.last())) else null + + return PageResponse(items, nextCursor) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt index e8f7d1e4..7c8c8d43 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Time.kt @@ -1,11 +1,18 @@ package com.mtusi.messenger.main.utils -import java.time.Instant -import java.time.ZoneOffset -import java.time.format.DateTimeFormatter +import kotlin.time.Clock +import kotlin.time.Instant -private val RFC3339: DateTimeFormatter = DateTimeFormatter - .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - .withZone(ZoneOffset.UTC) +private const val NANOS_PER_MICRO = 1_000 -fun nowIsoUtc(): String = RFC3339.format(Instant.now()) +/** + * 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 + ) +} diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt index 19ab2b57..395e8fb6 100644 --- a/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/Validation.kt @@ -1,11 +1,15 @@ package com.mtusi.messenger.main.utils -import com.mtusi.messenger.main.extensions.isValidUuid 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) { @@ -24,8 +28,9 @@ fun requireNonBlankBounded(value: String, min: Int, max: Int, field: String) { } } -fun requireUuid(value: String, field: String) { - if (!isValidUuid(value)) { +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) } diff --git a/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/RowGreater.kt b/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/RowGreater.kt new file mode 100644 index 00000000..190d93fa --- /dev/null +++ b/src/main/kotlin/com/mtusi/messenger/main/utils/exposed/operations/RowGreater.kt @@ -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>, + private val right: List> +) : Op() { + + 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>) { + append("(") + expressions.forEachIndexed { index, expression -> + if (index > 0) { + append(", ") + } + append(expression) + } + append(")") + } +} diff --git a/src/main/resources/application.conf b/src/main/resources/application.conf index ce1c5691..dc393054 100644 --- a/src/main/resources/application.conf +++ b/src/main/resources/application.conf @@ -12,3 +12,25 @@ ktor { 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 +} + +authentication { + realm = "messenger" + sessionTtlSeconds = 3600 + sessionTtlSeconds = ${?SESSION_TTL_SECONDS} +} diff --git a/src/main/resources/migrations/V1__init.sql b/src/main/resources/migrations/V1__init.sql new file mode 100644 index 00000000..b580eefd --- /dev/null +++ b/src/main/resources/migrations/V1__init.sql @@ -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); diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationControllerTest.kt new file mode 100644 index 00000000..67734ad9 --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/authentication/AuthenticationControllerTest.kt @@ -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() + 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().token, second.body().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().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() + + 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]) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt index 5b310c46..ea0b63e4 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/chat/ChatControllerTest.kt @@ -1,27 +1,64 @@ package com.mtusi.messenger.main.infrastructure.controllers.chat import com.mtusi.messenger.main.extensions.ErrorBody +import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.dto.PageResponse +import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel +import com.mtusi.messenger.main.support.TestUser +import com.mtusi.messenger.main.support.auth import com.mtusi.messenger.main.support.createChat -import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.register import com.mtusi.messenger.main.support.runApp +import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.get -import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import org.jetbrains.exposed.v1.core.eq +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.jetbrains.exposed.v1.jdbc.transactions.transaction +import java.util.UUID import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNull class ChatControllerTest { + private suspend fun HttpClient.postChat(actor: TestUser, title: String, memberIds: List): HttpResponse = + post("/api/v1/chats") { + auth(actor) + contentType(ContentType.Application.Json) + setBody(CreateChatRequest(title = title, memberIds = memberIds)) + } + + @Test + fun `member can read own chat and members keep their order`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") + val created = client.createChat(alice, title = "notes", memberIds = listOf(bob.id, alice.id)) + + val response = client.get("/api/v1/chats/${created.id}") { + auth(bob) + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals(created, response.body()) + assertEquals(listOf(bob.id, alice.id), created.memberIds) + } + @Test fun `foreign chat returns 404 for non-member`() = runApp { client -> - val alice = client.createUser("alice") - val bob = client.createUser("bob") + val alice = client.register("alice") + val eve = client.register("eve") val chat = client.createChat(alice, title = "secret", memberIds = listOf(alice.id)) val response = client.get("/api/v1/chats/${chat.id}") { - header("X-User-Id", bob.id) + auth(eve) } assertEquals(HttpStatusCode.NotFound, response.status) @@ -29,15 +66,87 @@ class ChatControllerTest { } @Test - fun `member can read own chat`() = runApp { client -> - val alice = client.createUser("alice") - val created = client.createChat(alice, title = "notes", memberIds = listOf(alice.id)) + fun `invalid member lists are rejected with 400`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") - val response = client.get("/api/v1/chats/${created.id}") { - header("X-User-Id", alice.id) + val cases = listOf( + listOf(bob.id.toString()), // creator is not a member + listOf(alice.id.toString(), alice.id.toString()), // duplicates + listOf(alice.id.toString(), "not-a-uuid"), // malformed id + listOf(alice.id.toString(), UUID.randomUUID().toString()), // unknown user + emptyList(), + ) + + for (memberIds in cases) { + val response = client.postChat(alice, "bad", memberIds) + assertEquals(HttpStatusCode.BadRequest, response.status, "member_ids=$memberIds") + } + } + + @Test + fun `failed chat creation leaves no partial rows`() = runApp { client -> + val alice = client.register("alice") + val title = "atomic-${UUID.randomUUID()}" + + val response = client.postChat(alice, title, listOf(alice.id.toString(), UUID.randomUUID().toString())) + assertEquals(HttpStatusCode.BadRequest, response.status) + + val chats = transaction { + ChatModel.selectAll().where(ChatModel.title eq title).count() + } + assertEquals(0, chats) + } + + @Test + fun `chat list contains only own chats and is paginated`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") + val eve = client.register("eve") + + val created = (0 until 5).map { + client.createChat(alice, title = "c$it", memberIds = listOf(alice.id, bob.id)) + } + client.createChat(eve, title = "eve only", memberIds = listOf(eve.id)) + + val collected = mutableListOf() + var cursor: String? = null + + do { + val page = client.get("/api/v1/chats") { + auth(bob) + url { + parameters.append("limit", "2") + cursor?.let { parameters.append("cursor", it) } + } + }.body>() + + collected += page.items + cursor = page.nextCursor + } while (cursor != null) + + assertEquals(created, collected) + + val evePage = client.get("/api/v1/chats") { auth(eve) }.body>() + assertEquals(listOf("eve only"), evePage.items.map { it.title }) + assertNull(evePage.nextCursor) + } + + @Test + fun `cursor issued to another user is rejected`() = runApp { client -> + val alice = client.register("alice") + val bob = client.register("bob") + repeat(2) { client.createChat(alice, title = "c$it", memberIds = listOf(alice.id)) } + + val cursor = client.get("/api/v1/chats?limit=1") { auth(alice) } + .body>() + .nextCursor!! + + val response = client.get("/api/v1/chats") { + auth(bob) + url { parameters.append("cursor", cursor) } } - assertEquals(HttpStatusCode.OK, response.status) - assertEquals(created.id, response.body().id) + assertEquals(HttpStatusCode.BadRequest, response.status) } } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt index fbe943fd..66a36f3f 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/health/HealthControllerTest.kt @@ -15,7 +15,7 @@ class HealthControllerTest { } @Test - fun `ready returns 200`() = runApp { client -> + fun `ready returns 200 when database is reachable`() = runApp { client -> val response = client.get("/health/ready") assertEquals(HttpStatusCode.OK, response.status) } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt index ea3cf062..a91cb3d8 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageConcurrencyTest.kt @@ -1,13 +1,14 @@ package com.mtusi.messenger.main.infrastructure.controllers.message import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest -import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.infrastructure.dto.PageResponse +import com.mtusi.messenger.main.support.auth import com.mtusi.messenger.main.support.createChat -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.get -import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.http.ContentType @@ -23,7 +24,7 @@ class MessageConcurrencyTest { @Test fun `parallel senders produce exactly N unique messages`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "load", memberIds = listOf(alice.id)) val workers = 10 @@ -35,7 +36,7 @@ class MessageConcurrencyTest { async { repeat(perWorker) { i -> val response = client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "w$w-i$i")) } @@ -50,7 +51,7 @@ class MessageConcurrencyTest { do { val response = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "100") if (cursor != null) parameters.append("cursor", cursor!!) @@ -58,7 +59,7 @@ class MessageConcurrencyTest { } assertEquals(HttpStatusCode.OK, response.status) - val page = response.body() + val page = response.body>() collected += page.items.map { it.text } cursor = page.nextCursor } while (cursor != null) diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt index d689ece9..ac72e82c 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/message/MessageControllerTest.kt @@ -2,13 +2,14 @@ package com.mtusi.messenger.main.infrastructure.controllers.message import com.mtusi.messenger.main.extensions.ErrorBody import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest -import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse +import com.mtusi.messenger.main.infrastructure.dto.Message +import com.mtusi.messenger.main.infrastructure.dto.PageResponse +import com.mtusi.messenger.main.support.auth import com.mtusi.messenger.main.support.createChat -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.get -import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.http.ContentType @@ -23,11 +24,11 @@ class MessageControllerTest { @Test fun `empty text returns 400 invalid_request`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val response = client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "")) } @@ -38,12 +39,12 @@ class MessageControllerTest { @Test fun `foreign chat returns 404 when sending`() = runApp { client -> - val alice = client.createUser("alice") - val bob = client.createUser("bob") + val alice = client.register("alice") + val bob = client.register("bob") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val response = client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", bob.id) + auth(bob) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "hi")) } @@ -54,12 +55,12 @@ class MessageControllerTest { @Test fun `foreign chat returns 404 when listing`() = runApp { client -> - val alice = client.createUser("alice") - val bob = client.createUser("bob") + val alice = client.register("alice") + val bob = client.register("bob") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val response = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", bob.id) + auth(bob) } assertEquals(HttpStatusCode.NotFound, response.status) @@ -67,13 +68,13 @@ class MessageControllerTest { @Test fun `pagination walks all messages exactly once`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val total = 25 repeat(total) { i -> val r = client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "m$i")) } @@ -86,7 +87,7 @@ class MessageControllerTest { do { val response = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "10") if (cursor != null) parameters.append("cursor", cursor!!) @@ -94,7 +95,7 @@ class MessageControllerTest { } assertEquals(HttpStatusCode.OK, response.status) - val page = response.body() + val page = response.body>() collected += page.items.map { it.text } cursor = page.nextCursor pages++ @@ -108,32 +109,32 @@ class MessageControllerTest { @Test fun `history that is an exact multiple of limit ends with null next_cursor`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) repeat(20) { i -> client.post("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "m$i")) } } val first = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "10") } - }.body() + }.body>() val cursor = first.nextCursor assertNotNull(cursor) val second = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "10") parameters.append("cursor", cursor) } - }.body() + }.body>() assertEquals((10 until 20).map { "m$it" }, second.items.map { it.text }) assertNull(second.nextCursor) @@ -141,43 +142,43 @@ class MessageControllerTest { @Test fun `last page has null next_cursor`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id)) val response = client.get("/api/v1/chats/${chat.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) } assertEquals(HttpStatusCode.OK, response.status) - val page = response.body() + val page = response.body>() assertEquals(0, page.items.size) assertNull(page.nextCursor) } @Test fun `foreign cursor returns 400`() = runApp { client -> - val alice = client.createUser("alice") + val alice = client.register("alice") val chatA = client.createChat(alice, title = "a", memberIds = listOf(alice.id)) val chatB = client.createChat(alice, title = "b", memberIds = listOf(alice.id)) repeat(2) { i -> client.post("/api/v1/chats/${chatA.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "a$i")) } } val firstA = client.get("/api/v1/chats/${chatA.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "1") } - }.body() + }.body>() val cursor = firstA.nextCursor assertNotNull(cursor) val response = client.get("/api/v1/chats/${chatB.id}/messages") { - header("X-User-Id", alice.id) + auth(alice) url { parameters.append("limit", "1") parameters.append("cursor", cursor) diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt index f2f689a5..b2d7dfea 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/controllers/user/UserControllerTest.kt @@ -2,30 +2,48 @@ package com.mtusi.messenger.main.infrastructure.controllers.user import com.mtusi.messenger.main.extensions.ErrorBody import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest -import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.support.TEST_PASSWORD +import com.mtusi.messenger.main.support.auth +import com.mtusi.messenger.main.support.register import com.mtusi.messenger.main.support.runApp +import com.mtusi.messenger.main.support.uniqueUsername import io.ktor.client.call.body +import io.ktor.client.request.basicAuth import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.contentType +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNotNull class UserControllerTest { @Test - fun `create user returns 201 and echoes fields`() = runApp { client -> + fun `create user returns 201 without password`() = runApp { client -> + val username = uniqueUsername("alice") + val response = client.post("/api/v1/users") { contentType(ContentType.Application.Json) - setBody(CreateUserRequest(username = "alice", displayName = "Alice")) + setBody(CreateUserRequest(username = username, displayName = "Alice", password = TEST_PASSWORD)) } assertEquals(HttpStatusCode.Created, response.status) + + val body = response.bodyAsText() + assertFalse("password" in body) + assertFalse(TEST_PASSWORD in body) + assertEquals(username, response.body().username) } @Test @@ -43,30 +61,120 @@ class UserControllerTest { } @Test - fun `duplicate username returns 409 conflict`() = runApp { client -> - client.createUser(username = "bob") - + fun `missing password returns 400`() = runApp { client -> val response = client.post("/api/v1/users") { contentType(ContentType.Application.Json) - setBody(CreateUserRequest(username = "bob", displayName = "Bob 2")) + setBody("""{"username":"${uniqueUsername("nopass")}","display_name":"x"}""") } - assertEquals(HttpStatusCode.Conflict, response.status) - assertEquals("conflict", response.body().error.code) + assertEquals(HttpStatusCode.BadRequest, response.status) } @Test - fun `missing X-User-Id on protected endpoint returns 401`() = runApp { client -> + fun `password shorter than 12 code points returns 400`() = runApp { client -> + val response = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(CreateUserRequest(username = uniqueUsername("short"), displayName = "x", password = "elevenchars")) + } + + assertEquals(HttpStatusCode.BadRequest, response.status) + } + + @Test + fun `duplicate username returns 409 conflict`() = runApp { client -> + val username = uniqueUsername("bob") + + val request = CreateUserRequest(username = username, displayName = "Bob", password = TEST_PASSWORD) + + val first = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(request) + } + assertEquals(HttpStatusCode.Created, first.status) + + val second = client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(request.copy(displayName = "Bob 2")) + } + + assertEquals(HttpStatusCode.Conflict, second.status) + assertEquals("conflict", second.body().error.code) + } + + @Test + fun `concurrent registrations of one username create exactly one user`() = runApp { client -> + val username = uniqueUsername("race") + val attempts = 10 + + val statuses = coroutineScope { + (0 until attempts).map { + async { + client.post("/api/v1/users") { + contentType(ContentType.Application.Json) + setBody(CreateUserRequest(username = username, displayName = "r$it", password = TEST_PASSWORD)) + }.status + } + }.awaitAll() + } + + assertEquals(1, statuses.count { it == HttpStatusCode.Created }) + assertEquals(attempts - 1, statuses.count { it == HttpStatusCode.Conflict }) + } + + @Test + fun `me returns the session owner`() = runApp { client -> + val alice = client.register("alice") + + val response = client.get("/api/v1/users/me") { + auth(alice) + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals(alice.user, response.body()) + } + + @Test + fun `missing token returns 401 with Bearer challenge`() = runApp { client -> val response = client.get("/api/v1/users/me") + assertEquals(HttpStatusCode.Unauthorized, response.status) assertEquals("unauthorized", response.body().error.code) + assertEquals("Bearer realm=\"messenger\"", response.headers[HttpHeaders.WWWAuthenticate]) } @Test - fun `unknown X-User-Id returns 401`() = runApp { client -> + fun `X-User-Id alone gives no access`() = runApp { client -> + val alice = client.register("alice") + val response = client.get("/api/v1/users/me") { - header("X-User-Id", "00000000-0000-0000-0000-000000000000") + header("X-User-Id", alice.id.toString()) } + assertEquals(HttpStatusCode.Unauthorized, response.status) } + + @Test + fun `X-User-Id does not override bearer identity`() = runApp { client -> + val alice = client.register("alice") + val eve = client.register("eve") + + val response = client.get("/api/v1/users/me") { + auth(alice) + header("X-User-Id", eve.id.toString()) + } + + assertEquals(alice.id, response.body().id) + } + + @Test + fun `Basic credentials are rejected on business endpoints`() = runApp { client -> + val alice = client.register("alice") + + val response = client.get("/api/v1/users/me") { + basicAuth(alice.user.username, alice.password) + } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertEquals("Bearer realm=\"messenger\"", response.headers[HttpHeaders.WWWAuthenticate]) + } } diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt deleted file mode 100644 index 23e36884..00000000 --- a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/repositories/message/InMemoryMessageRepositoryTest.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.mtusi.messenger.main.infrastructure.repositories.message - -import com.mtusi.messenger.main.infrastructure.dto.Message -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -private const val CHAT_ID = "chat" - -class InMemoryMessageRepositoryTest { - - private fun repositoryWith(size: Int): InMemoryMessageRepository { - - val repository = InMemoryMessageRepository() - - repeat(size) { i -> - repository.append( - CHAT_ID, - Message( - id = "m$i", - chatId = CHAT_ID, - senderId = "u", - text = "t$i", - createdAt = "2026-01-01T00:00:00.000Z", - ), - ) - } - - return repository - } - - @Test - fun `returns requested window in append order`() { - val range = repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 3, count = 4) - assertEquals(listOf("m3", "m4", "m5", "m6"), range.map { it.id }) - } - - @Test - fun `window is clipped at the end of history`() { - val range = repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 8, count = 5) - assertEquals(listOf("m8", "m9"), range.map { it.id }) - } - - @Test - fun `offset past the end returns empty`() { - assertTrue(repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 10, count = 5).isEmpty()) - } - - @Test - fun `huge offset does not overflow`() { - assertTrue(repositoryWith(10).findRangeByChatId(CHAT_ID, offset = Int.MAX_VALUE - 1, count = 51).isEmpty()) - } - - @Test - fun `unknown chat returns empty`() { - assertTrue(InMemoryMessageRepository().findRangeByChatId("missing", offset = 0, count = 50).isEmpty()) - } -} diff --git a/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingServiceTest.kt b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingServiceTest.kt new file mode 100644 index 00000000..384e053c --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/infrastructure/services/hashing/DefaultHashingServiceTest.kt @@ -0,0 +1,45 @@ +package com.mtusi.messenger.main.infrastructure.services.hashing + +import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +class DefaultHashingServiceTest { + + private val service = DefaultHashingService() + + @Test + fun `hash is a salted Argon2id PHC string`() { + val first = service.computeHash(HashingAlgorithm.Argon2id, "correct-horse-battery") + val second = service.computeHash(HashingAlgorithm.Argon2id, "correct-horse-battery") + + assertTrue(first.startsWith("\$argon2id\$v=19\$m=19456,t=2,p=1\$")) + assertFalse("correct-horse-battery" in first) + assertNotEquals(first, second, "same password must produce different hashes (random salt)") + } + + @Test + fun `validates the right password and rejects a wrong one`() { + val hash = service.computeHash(HashingAlgorithm.Argon2id, "correct-horse-battery") + + assertTrue(service.validateHash(HashingAlgorithm.Argon2id, "correct-horse-battery", hash)) + assertFalse(service.validateHash(HashingAlgorithm.Argon2id, "correct-horse-batterY", hash)) + } + + @Test + fun `passwords differing only after 72 bytes are distinguished`() { + // bcrypt silently truncates input to 72 bytes; Argon2id must not. + val prefix = "ж".repeat(40) // 80 bytes in UTF-8 + val hash = service.computeHash(HashingAlgorithm.Argon2id, prefix + "a") + + assertFalse(service.validateHash(HashingAlgorithm.Argon2id, prefix + "b", hash)) + } + + @Test + fun `malformed hash is rejected instead of throwing`() { + assertFalse(service.validateHash(HashingAlgorithm.Argon2id, "whatever", "not-a-hash")) + assertFalse(service.validateHash(HashingAlgorithm.Argon2id, "whatever", "\$argon2id\$v=19\$m=x\$a\$b")) + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/plugins/DatabaseMigrationTest.kt b/src/test/kotlin/com/mtusi/messenger/main/plugins/DatabaseMigrationTest.kt new file mode 100644 index 00000000..93ccd43f --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/plugins/DatabaseMigrationTest.kt @@ -0,0 +1,49 @@ +package com.mtusi.messenger.main.plugins + +import com.mtusi.messenger.main.support.TestDatabase +import com.mtusi.messenger.main.support.createUser +import com.mtusi.messenger.main.support.runApp +import com.zaxxer.hikari.HikariDataSource +import org.flywaydb.core.Flyway +import kotlin.test.Test +import kotlin.test.assertEquals + +class DatabaseMigrationTest { + + @Test + fun `re-running migrations applies nothing and keeps data`() = runApp { client -> + client.createUser("keep") + + HikariDataSource().apply { + jdbcUrl = TestDatabase.container.jdbcUrl + username = TestDatabase.USERNAME + password = TestDatabase.PASSWORD + }.use { dataSource -> + + val usersBefore = countUsers(dataSource) + + applyDatabaseMigrations(dataSource) + applyDatabaseMigrations(dataSource) + + val flyway = Flyway.configure() + .dataSource(dataSource) + .locations("classpath:migrations") + .load() + + assertEquals(0, flyway.info().pending().size) + assertEquals(flyway.info().applied().size, flyway.info().all().size) + assertEquals(usersBefore, countUsers(dataSource)) + } + } + + private fun countUsers(dataSource: HikariDataSource): Long { + return dataSource.connection.use { connection -> + connection.createStatement().use { statement -> + statement.executeQuery("SELECT count(*) FROM users").use { + it.next() + it.getLong(1) + } + } + } + } +} diff --git a/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt b/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt index 6ce1f537..4917d5f5 100644 --- a/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt +++ b/src/test/kotlin/com/mtusi/messenger/main/support/TestApp.kt @@ -1,27 +1,31 @@ package com.mtusi.messenger.main.support -import com.mtusi.messenger.main.infrastructure.dto.Chat -import com.mtusi.messenger.main.infrastructure.dto.User +import com.mtusi.messenger.main.infrastructure.controllers.authentication.responses.SessionResponse import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest +import com.mtusi.messenger.main.infrastructure.dto.Chat +import com.mtusi.messenger.main.infrastructure.dto.User import com.mtusi.messenger.main.module +import com.typesafe.config.ConfigFactory import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.contentnegotiation.ContentNegotiation -import io.ktor.client.request.header +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.basicAuth +import io.ktor.client.request.bearerAuth import io.ktor.client.request.post import io.ktor.client.request.setBody -import io.ktor.client.statement.HttpResponse import io.ktor.http.ContentType -import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json +import io.ktor.server.config.HoconApplicationConfig import io.ktor.server.testing.ApplicationTestBuilder import io.ktor.server.testing.testApplication import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonNamingStrategy +import java.util.UUID @OptIn(ExperimentalSerializationApi::class) val testJson = Json { @@ -30,7 +34,40 @@ val testJson = Json { namingStrategy = JsonNamingStrategy.SnakeCase } -fun runApp(block: suspend ApplicationTestBuilder.(HttpClient) -> Unit) = testApplication { +const val TEST_PASSWORD = "correct-horse-battery" + +data class TestUser( + val user: User, + val password: String, + val token: String, +) { + val id: UUID + get() = user.id +} + +private fun testConfig(sessionTtlSeconds: Long) = HoconApplicationConfig( + ConfigFactory.parseMap( + mapOf( + "database.host" to TestDatabase.container.host, + "database.port" to TestDatabase.container.firstMappedPort, + "database.name" to TestDatabase.NAME, + "database.username" to TestDatabase.USERNAME, + "database.password" to TestDatabase.PASSWORD, + "database.maxPoolSize" to 10, + "database.connectionTimeoutMs" to 10000, + "authentication.realm" to "messenger", + "authentication.sessionTtlSeconds" to sessionTtlSeconds, + ) + ) +) + +fun runApp( + sessionTtlSeconds: Long = 3600, + block: suspend ApplicationTestBuilder.(HttpClient) -> Unit +) = testApplication { + environment { + config = testConfig(sessionTtlSeconds) + } application { module() } @@ -42,30 +79,50 @@ fun runApp(block: suspend ApplicationTestBuilder.(HttpClient) -> Unit) = testApp block(client) } -suspend fun HttpClient.createUser(username: String, displayName: String = username): User { +/** + * Usernames are unique per call: all tests share one database. + */ +fun uniqueUsername(prefix: String): String = "${prefix}_${UUID.randomUUID().toString().replace("-", "").take(12)}" + +suspend fun HttpClient.createUser(prefix: String, password: String = TEST_PASSWORD): User { + val username = uniqueUsername(prefix) val response = post("/api/v1/users") { contentType(ContentType.Application.Json) - setBody(CreateUserRequest(username = username, displayName = displayName)) + setBody(CreateUserRequest(username = username, displayName = prefix, password = password)) } check(response.status == HttpStatusCode.Created) { "createUser failed: ${response.status}" } return response.body() } +suspend fun HttpClient.login(username: String, password: String): SessionResponse { + val response = post("/api/v1/auth/sessions") { + basicAuth(username, password) + } + check(response.status == HttpStatusCode.Created) { "login failed: ${response.status}" } + return response.body() +} + +/** + * Registers a user and opens a session for it. + */ +suspend fun HttpClient.register(prefix: String): TestUser { + val user = createUser(prefix) + val session = login(user.username, TEST_PASSWORD) + return TestUser(user, TEST_PASSWORD, session.token) +} + +fun HttpRequestBuilder.auth(user: TestUser) = bearerAuth(user.token) + suspend fun HttpClient.createChat( - creator: User, + creator: TestUser, title: String, - memberIds: List, + memberIds: List, ): Chat { val response = post("/api/v1/chats") { - header("X-User-Id", creator.id) + auth(creator) contentType(ContentType.Application.Json) - setBody(CreateChatRequest(title = title, memberIds = memberIds)) + setBody(CreateChatRequest(title = title, memberIds = memberIds.map(UUID::toString))) } check(response.status == HttpStatusCode.Created) { "createChat failed: ${response.status}" } return response.body() } - -fun HttpResponse.header(name: String): String? = headers[name] - -val HttpResponse.requestId: String? - get() = headers[HttpHeaders.XRequestId] diff --git a/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt b/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt new file mode 100644 index 00000000..c4897e8a --- /dev/null +++ b/src/test/kotlin/com/mtusi/messenger/main/support/TestDatabase.kt @@ -0,0 +1,24 @@ +package com.mtusi.messenger.main.support + +import org.testcontainers.containers.PostgreSQLContainer +import org.testcontainers.utility.DockerImageName + +/** + * One PostgreSQL container per test JVM, same image as compose.yaml. + * Tests share it and stay independent by using unique usernames. + */ +object TestDatabase { + + const val NAME = "messenger" + const val USERNAME = "messenger" + const val PASSWORD = "messenger" + + val container: PostgreSQLContainer<*> by lazy { + PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres")) + .withDatabaseName(NAME) + .withUsername(USERNAME) + .withPassword(PASSWORD) + .also { it.start() } + } + +}