Move lab2 to lab3
This commit is contained in:
+151
@@ -0,0 +1,151 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.authentication
|
||||
|
||||
import com.mtusi.messenger.main.extensions.ErrorBody
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.authentication.responses.SessionResponse
|
||||
import com.mtusi.messenger.main.support.TEST_PASSWORD
|
||||
import com.mtusi.messenger.main.support.auth
|
||||
import com.mtusi.messenger.main.support.createUser
|
||||
import com.mtusi.messenger.main.support.register
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.basicAuth
|
||||
import io.ktor.client.request.bearerAuth
|
||||
import io.ktor.client.request.delete
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotEquals
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
private const val BASIC_CHALLENGE = "Basic realm=\"messenger\", charset=\"UTF-8\""
|
||||
|
||||
class AuthenticationControllerTest {
|
||||
|
||||
@Test
|
||||
fun `valid Basic credentials open a session`() = runApp { client ->
|
||||
val user = client.createUser("alice")
|
||||
|
||||
val response = client.post("/api/v1/auth/sessions") {
|
||||
basicAuth(user.username, TEST_PASSWORD)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.Created, response.status)
|
||||
|
||||
val session = response.body<SessionResponse>()
|
||||
assertEquals("Bearer", session.tokenType)
|
||||
assertEquals(user, session.user)
|
||||
assertTrue(session.token.length >= 43, "token must carry at least 256 bits")
|
||||
assertTrue(session.expiresAt > Clock.System.now() + 59.minutes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `each login issues a different token`() = runApp { client ->
|
||||
val user = client.createUser("alice")
|
||||
|
||||
val first = client.post("/api/v1/auth/sessions") { basicAuth(user.username, TEST_PASSWORD) }
|
||||
val second = client.post("/api/v1/auth/sessions") { basicAuth(user.username, TEST_PASSWORD) }
|
||||
|
||||
assertNotEquals(first.body<SessionResponse>().token, second.body<SessionResponse>().token)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `password containing a colon and non-ASCII characters works`() = runApp { client ->
|
||||
val password = "пароль:с-двоеточием"
|
||||
val user = client.createUser("colon", password = password)
|
||||
|
||||
val response = client.post("/api/v1/auth/sessions") {
|
||||
basicAuth(user.username, password)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.Created, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wrong password and unknown user get the same 401`() = runApp { client ->
|
||||
val user = client.createUser("alice")
|
||||
|
||||
val wrongPassword = client.post("/api/v1/auth/sessions") {
|
||||
basicAuth(user.username, "wrong-password-123")
|
||||
}
|
||||
val unknownUser = client.post("/api/v1/auth/sessions") {
|
||||
basicAuth("nobody_${user.username}".take(32), TEST_PASSWORD)
|
||||
}
|
||||
|
||||
for (response in listOf(wrongPassword, unknownUser)) {
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
assertEquals(BASIC_CHALLENGE, response.headers[HttpHeaders.WWWAuthenticate])
|
||||
assertEquals("unauthorized", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing or malformed Basic header returns 401`() = runApp { client ->
|
||||
val missing = client.post("/api/v1/auth/sessions")
|
||||
val malformed = client.post("/api/v1/auth/sessions") {
|
||||
header(HttpHeaders.Authorization, "Basic !!!not-base64")
|
||||
}
|
||||
|
||||
for (response in listOf(missing, malformed)) {
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
assertEquals(BASIC_CHALLENGE, response.headers[HttpHeaders.WWWAuthenticate])
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Bearer token cannot open a session`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
|
||||
val response = client.post("/api/v1/auth/sessions") {
|
||||
auth(alice)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout revokes only the current token`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
val secondSession = client.post("/api/v1/auth/sessions") {
|
||||
basicAuth(alice.user.username, alice.password)
|
||||
}.body<SessionResponse>()
|
||||
|
||||
val logout = client.delete("/api/v1/auth/sessions/current") { auth(alice) }
|
||||
assertEquals(HttpStatusCode.NoContent, logout.status)
|
||||
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
|
||||
val other = client.get("/api/v1/users/me") { bearerAuth(secondSession.token) }
|
||||
assertEquals(HttpStatusCode.OK, other.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown token returns 401`() = runApp { client ->
|
||||
val response = client.get("/api/v1/users/me") {
|
||||
bearerAuth("this-token-was-never-issued-by-the-server-at-all")
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session expires after SESSION_TTL_SECONDS`() = runApp(sessionTtlSeconds = 2) { client ->
|
||||
val alice = client.register("alice")
|
||||
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
delay(2.5.seconds)
|
||||
|
||||
val expired = client.get("/api/v1/users/me") { auth(alice) }
|
||||
assertEquals(HttpStatusCode.Unauthorized, expired.status)
|
||||
assertEquals("Bearer realm=\"messenger\"", expired.headers[HttpHeaders.WWWAuthenticate])
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
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.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.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<String>): 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<Chat>())
|
||||
assertEquals(listOf(bob.id, alice.id), created.memberIds)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `foreign chat returns 404 for non-member`() = runApp { client ->
|
||||
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}") {
|
||||
auth(eve)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||
assertEquals("not_found", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `invalid member lists are rejected with 400`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
|
||||
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 `unknown member is rejected before anything is written`() = 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<Chat>()
|
||||
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<PageResponse<Chat>>()
|
||||
|
||||
collected += page.items
|
||||
cursor = page.nextCursor
|
||||
} while (cursor != null)
|
||||
|
||||
assertEquals(created, collected)
|
||||
|
||||
val evePage = client.get("/api/v1/chats") { auth(eve) }.body<PageResponse<Chat>>()
|
||||
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<PageResponse<Chat>>()
|
||||
.nextCursor!!
|
||||
|
||||
val response = client.get("/api/v1/chats") {
|
||||
auth(bob)
|
||||
url { parameters.append("cursor", cursor) }
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.health
|
||||
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class HealthControllerTest {
|
||||
|
||||
@Test
|
||||
fun `live returns 200`() = runApp { client ->
|
||||
val response = client.get("/health/live")
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ready returns 200 when database is reachable`() = runApp { client ->
|
||||
val response = client.get("/health/ready")
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.message
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
|
||||
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.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.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.http.ContentType
|
||||
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
|
||||
|
||||
class MessageConcurrencyTest {
|
||||
|
||||
@Test
|
||||
fun `parallel senders produce exactly N unique messages`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
val chat = client.createChat(alice, title = "load", memberIds = listOf(alice.id))
|
||||
|
||||
val workers = 10
|
||||
val perWorker = 10
|
||||
val total = workers * perWorker
|
||||
|
||||
coroutineScope {
|
||||
(0 until workers).map { w ->
|
||||
async {
|
||||
repeat(perWorker) { i ->
|
||||
val response = client.post("/api/v1/chats/${chat.id}/messages") {
|
||||
auth(alice)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "w$w-i$i"))
|
||||
}
|
||||
assertEquals(HttpStatusCode.Created, response.status)
|
||||
}
|
||||
}
|
||||
}.awaitAll()
|
||||
}
|
||||
|
||||
val collected = mutableListOf<String>()
|
||||
var cursor: String? = null
|
||||
|
||||
do {
|
||||
val response = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
auth(alice)
|
||||
url {
|
||||
parameters.append("limit", "100")
|
||||
if (cursor != null) parameters.append("cursor", cursor!!)
|
||||
}
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
|
||||
val page = response.body<PageResponse<Message>>()
|
||||
collected += page.items.map { it.text }
|
||||
cursor = page.nextCursor
|
||||
} while (cursor != null)
|
||||
|
||||
assertEquals(total, collected.size)
|
||||
assertEquals(total, collected.toSet().size)
|
||||
|
||||
val expected = buildSet {
|
||||
for (w in 0 until workers) for (i in 0 until perWorker) add("w$w-i$i")
|
||||
}
|
||||
assertEquals(expected, collected.toSet())
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
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.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.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.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.contentType
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
|
||||
class MessageControllerTest {
|
||||
|
||||
@Test
|
||||
fun `empty text returns 400 invalid_request`() = runApp { client ->
|
||||
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") {
|
||||
auth(alice)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = ""))
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
assertEquals("invalid_request", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `foreign chat returns 404 when sending`() = runApp { client ->
|
||||
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") {
|
||||
auth(bob)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "hi"))
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||
assertEquals("not_found", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `foreign chat returns 404 when listing`() = runApp { client ->
|
||||
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") {
|
||||
auth(bob)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `pagination walks all messages exactly once`() = runApp { client ->
|
||||
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") {
|
||||
auth(alice)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "m$i"))
|
||||
}
|
||||
assertEquals(HttpStatusCode.Created, r.status)
|
||||
}
|
||||
|
||||
val collected = mutableListOf<String>()
|
||||
var cursor: String? = null
|
||||
var pages = 0
|
||||
|
||||
do {
|
||||
val response = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
auth(alice)
|
||||
url {
|
||||
parameters.append("limit", "10")
|
||||
if (cursor != null) parameters.append("cursor", cursor!!)
|
||||
}
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
|
||||
val page = response.body<PageResponse<Message>>()
|
||||
collected += page.items.map { it.text }
|
||||
cursor = page.nextCursor
|
||||
pages++
|
||||
} while (cursor != null)
|
||||
|
||||
assertEquals(3, pages)
|
||||
assertEquals(total, collected.size)
|
||||
assertEquals(total, collected.toSet().size)
|
||||
assertEquals((0 until total).map { "m$it" }, collected)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `history that is an exact multiple of limit ends with null next_cursor`() = runApp { client ->
|
||||
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") {
|
||||
auth(alice)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "m$i"))
|
||||
}
|
||||
}
|
||||
|
||||
val first = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
auth(alice)
|
||||
url { parameters.append("limit", "10") }
|
||||
}.body<PageResponse<Message>>()
|
||||
|
||||
val cursor = first.nextCursor
|
||||
assertNotNull(cursor)
|
||||
|
||||
val second = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
auth(alice)
|
||||
url {
|
||||
parameters.append("limit", "10")
|
||||
parameters.append("cursor", cursor)
|
||||
}
|
||||
}.body<PageResponse<Message>>()
|
||||
|
||||
assertEquals((10 until 20).map { "m$it" }, second.items.map { it.text })
|
||||
assertNull(second.nextCursor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `last page has null next_cursor`() = runApp { client ->
|
||||
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") {
|
||||
auth(alice)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val page = response.body<PageResponse<Message>>()
|
||||
assertEquals(0, page.items.size)
|
||||
assertNull(page.nextCursor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `foreign cursor returns 400`() = runApp { client ->
|
||||
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") {
|
||||
auth(alice)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "a$i"))
|
||||
}
|
||||
}
|
||||
|
||||
val firstA = client.get("/api/v1/chats/${chatA.id}/messages") {
|
||||
auth(alice)
|
||||
url { parameters.append("limit", "1") }
|
||||
}.body<PageResponse<Message>>()
|
||||
|
||||
val cursor = firstA.nextCursor
|
||||
assertNotNull(cursor)
|
||||
|
||||
val response = client.get("/api/v1/chats/${chatB.id}/messages") {
|
||||
auth(alice)
|
||||
url {
|
||||
parameters.append("limit", "1")
|
||||
parameters.append("cursor", cursor)
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
assertEquals("invalid_request", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
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.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 without password`() = runApp { client ->
|
||||
val username = uniqueUsername("alice")
|
||||
|
||||
val response = client.post("/api/v1/users") {
|
||||
contentType(ContentType.Application.Json)
|
||||
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<User>().username)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `invalid JSON body returns 400 invalid_request`() = runApp { client ->
|
||||
val response = client.post("/api/v1/users") {
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("{not json")
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
|
||||
val body = response.body<ErrorBody>()
|
||||
assertEquals("invalid_request", body.error.code)
|
||||
assertNotNull(body.error.requestId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing password returns 400`() = runApp { client ->
|
||||
val response = client.post("/api/v1/users") {
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("""{"username":"${uniqueUsername("nopass")}","display_name":"x"}""")
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
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<ErrorBody>().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<User>())
|
||||
}
|
||||
|
||||
@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<ErrorBody>().error.code)
|
||||
assertEquals("Bearer realm=\"messenger\"", response.headers[HttpHeaders.WWWAuthenticate])
|
||||
}
|
||||
|
||||
@Test
|
||||
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", 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<User>().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])
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
|
||||
|
||||
import com.mtusi.messenger.main.config.redis.SerialRedisConfig
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.utils.nowMicros
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import java.util.UUID
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
|
||||
class RedisSessionCacheRepositoryTest {
|
||||
|
||||
private fun withRepository(block: suspend (RedisSessionCacheRepository) -> Unit) = runTest {
|
||||
val endpoint = TestRedis.endpoint()
|
||||
val connection = RedisConnection(
|
||||
SerialRedisConfig(
|
||||
host = endpoint.host,
|
||||
port = endpoint.port,
|
||||
password = TestRedis.PASSWORD,
|
||||
connectTimeoutMs = 2000,
|
||||
commandTimeoutMs = 2000
|
||||
)
|
||||
)
|
||||
connection.use { block(RedisSessionCacheRepository(it)) }
|
||||
}
|
||||
|
||||
private fun session(ttl: Duration = 10.minutes): Session {
|
||||
val now = Clock.System.nowMicros()
|
||||
return Session(
|
||||
id = UUID.randomUUID(),
|
||||
userId = UUID.randomUUID(),
|
||||
tokenHash = UUID.randomUUID().toString().replace("-", ""),
|
||||
createdAt = now,
|
||||
expiresAt = now + ttl
|
||||
)
|
||||
}
|
||||
|
||||
private fun ttlSeconds(session: Session): Long {
|
||||
return TestRedis.cli(TestRedis.container, "TTL", "session:${session.tokenHash}").toLong()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cached session round-trips and expires together with the session`() = withRepository { repository ->
|
||||
val session = session()
|
||||
|
||||
assertNull(repository.find(session.tokenHash))
|
||||
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
assertEquals(CachedSession.Active(session), repository.find(session.tokenHash))
|
||||
assertTrue(ttlSeconds(session) in 590..600, "key must expire at cachedUntil")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `revoke replaces a cached session with a tombstone`() = withRepository { repository ->
|
||||
val session = session()
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
repository.revoke(session.tokenHash, session.expiresAt)
|
||||
|
||||
assertEquals(CachedSession.Revoked, repository.find(session.tokenHash))
|
||||
assertTrue(ttlSeconds(session) in 590..600, "tombstone must live until the session would expire")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `late cache fill cannot overwrite a tombstone`() = withRepository { repository ->
|
||||
val session = session()
|
||||
|
||||
// A lookup read the session from PostgreSQL before logout and stores it after the logout finished.
|
||||
repository.revoke(session.tokenHash, session.expiresAt)
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
assertEquals(CachedSession.Revoked, repository.find(session.tokenHash))
|
||||
}
|
||||
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.chat
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
|
||||
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
|
||||
import com.mtusi.messenger.main.support.register
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import org.jetbrains.exposed.v1.core.eq
|
||||
import org.jetbrains.exposed.v1.exceptions.ExposedSQLException
|
||||
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.assertFailsWith
|
||||
|
||||
private const val FOREIGN_KEY_VIOLATION = "23503"
|
||||
|
||||
/**
|
||||
* The service validates members before writing, so the rollback is exercised here directly: the chat row is
|
||||
* inserted, the membership batch then fails on the foreign key, and the whole transaction must disappear.
|
||||
*/
|
||||
class ExposedChatRepositoryTest {
|
||||
|
||||
private val repository = ExposedChatRepository()
|
||||
|
||||
@Test
|
||||
fun `chat row is rolled back when inserting members fails`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
val title = "rollback-${UUID.randomUUID()}"
|
||||
|
||||
val error = assertFailsWith<ExposedSQLException> {
|
||||
transaction {
|
||||
repository.create(title = title, memberIds = listOf(alice.id, UUID.randomUUID()))
|
||||
}
|
||||
}
|
||||
assertEquals(FOREIGN_KEY_VIOLATION, error.sqlState)
|
||||
|
||||
val (chats, memberships) = transaction {
|
||||
val chats = ChatModel.selectAll().where(ChatModel.title eq title).count()
|
||||
val memberships = ChatMemberModel.selectAll().where(ChatMemberModel.userId eq alice.id).count()
|
||||
chats to memberships
|
||||
}
|
||||
assertEquals(0, chats)
|
||||
assertEquals(0, memberships)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `successful creation commits the chat and every member`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
|
||||
val chat = transaction {
|
||||
repository.create(title = "committed", memberIds = listOf(alice.id, bob.id))
|
||||
}
|
||||
|
||||
val memberships = transaction {
|
||||
ChatMemberModel.selectAll().where(ChatMemberModel.chatId eq chat.id).count()
|
||||
}
|
||||
assertEquals(2, memberships)
|
||||
}
|
||||
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package com.mtusi.messenger.main.infrastructure.services.authentication
|
||||
|
||||
import com.mtusi.messenger.main.config.authentication.SerialAuthenticationConfig
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.CachedSession
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.SessionCacheRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation.SessionRevocationRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.user.ExposedUserRepository
|
||||
import com.mtusi.messenger.main.infrastructure.services.hashing.DefaultHashingService
|
||||
import com.mtusi.messenger.main.support.TestDatabase
|
||||
import com.mtusi.messenger.main.utils.computeSha256
|
||||
import com.mtusi.messenger.main.utils.nowMicros
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.jetbrains.exposed.v1.jdbc.Database
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlin.test.BeforeTest
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.hours
|
||||
import kotlin.time.Instant
|
||||
|
||||
private const val CONCURRENT_REQUESTS = 50
|
||||
private const val SLOW_QUERY_MS = 200L
|
||||
|
||||
/**
|
||||
* Cold cache and a deliberately slow lookup, so every request is guaranteed to overlap with the first one.
|
||||
*/
|
||||
class SessionLookupSingleFlightTest {
|
||||
|
||||
private val token = "token-${UUID.randomUUID()}"
|
||||
private val tokenHash = token.toByteArray().computeSha256()
|
||||
|
||||
private val session = Clock.System.nowMicros().let {
|
||||
Session(
|
||||
id = UUID.randomUUID(),
|
||||
userId = UUID.randomUUID(),
|
||||
tokenHash = tokenHash,
|
||||
createdAt = it,
|
||||
expiresAt = it + 1.hours
|
||||
)
|
||||
}
|
||||
|
||||
private class CountingSessionRepository(private val session: Session) : SessionRepository {
|
||||
|
||||
val lookups = AtomicInteger()
|
||||
|
||||
override fun findActiveByTokenHash(tokenHash: String, now: Instant): Session? {
|
||||
lookups.incrementAndGet()
|
||||
Thread.sleep(SLOW_QUERY_MS)
|
||||
return session.takeIf { it.tokenHash == tokenHash }
|
||||
}
|
||||
|
||||
override fun create(userId: UUID, tokenHash: String, ttl: Duration) = error("not used")
|
||||
|
||||
override fun deleteById(id: UUID) = true
|
||||
|
||||
}
|
||||
|
||||
private class ColdCache : SessionCacheRepository {
|
||||
|
||||
val writes = AtomicInteger()
|
||||
|
||||
override suspend fun find(tokenHash: String): CachedSession? = null
|
||||
|
||||
override suspend fun putIfAbsent(session: Session, cachedUntil: Instant) {
|
||||
writes.incrementAndGet()
|
||||
}
|
||||
|
||||
override suspend fun revoke(tokenHash: String, expiresAt: Instant) = Unit
|
||||
|
||||
}
|
||||
|
||||
private object NoRevocations : SessionRevocationRepository {
|
||||
|
||||
override fun add(revocation: SessionRevocation) = Unit
|
||||
|
||||
override fun findPending(now: Instant) = emptyList<SessionRevocation>()
|
||||
|
||||
override fun delete(tokenHash: String) = Unit
|
||||
|
||||
override fun deleteExpired(now: Instant) = Unit
|
||||
|
||||
}
|
||||
|
||||
@BeforeTest
|
||||
fun connect() {
|
||||
// The fakes do not touch the database, but the service still opens a transaction around the lookup.
|
||||
TestDatabase.container.let { Database.connect(it.jdbcUrl, user = it.username, password = it.password) }
|
||||
}
|
||||
|
||||
private fun service(singleFlight: Boolean, repository: SessionRepository, cache: SessionCacheRepository) =
|
||||
DefaultAuthenticationService(
|
||||
userRepository = ExposedUserRepository(),
|
||||
sessionRepository = repository,
|
||||
sessionCacheRepository = cache,
|
||||
sessionRevocationRepository = NoRevocations,
|
||||
hashingService = DefaultHashingService(),
|
||||
config = SerialAuthenticationConfig(
|
||||
realm = "messenger",
|
||||
sessionTtlSeconds = 3600,
|
||||
sessionCacheTtlSeconds = 60,
|
||||
sessionCacheSingleFlight = singleFlight
|
||||
)
|
||||
)
|
||||
|
||||
private fun stampede(service: AuthenticationService): List<Session?> = runBlocking(Dispatchers.Default) {
|
||||
(0 until CONCURRENT_REQUESTS).map {
|
||||
async { service.findSessionByToken(token) }
|
||||
}.awaitAll()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without single-flight every concurrent miss queries the database`() {
|
||||
val repository = CountingSessionRepository(session)
|
||||
val cache = ColdCache()
|
||||
|
||||
val results = stampede(service(singleFlight = false, repository, cache))
|
||||
|
||||
assertTrue(results.all { it == session })
|
||||
assertEquals(CONCURRENT_REQUESTS, repository.lookups.get())
|
||||
assertEquals(CONCURRENT_REQUESTS, cache.writes.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `with single-flight concurrent misses share one database lookup`() {
|
||||
val repository = CountingSessionRepository(session)
|
||||
val cache = ColdCache()
|
||||
|
||||
val results = stampede(service(singleFlight = true, repository, cache))
|
||||
|
||||
assertTrue(results.all { it == session })
|
||||
assertEquals(1, repository.lookups.get())
|
||||
assertEquals(1, cache.writes.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `request arriving after logout does not join a lookup started before it`() = runBlocking(Dispatchers.Default) {
|
||||
val repository = CountingSessionRepository(session)
|
||||
val service = service(singleFlight = true, repository, ColdCache())
|
||||
|
||||
// The leader's query is still running (SLOW_QUERY_MS) when the logout completes.
|
||||
val leader = async { service.findSessionByToken(token) }
|
||||
delay(SLOW_QUERY_MS / 4)
|
||||
service.revokeSession(session)
|
||||
|
||||
val afterLogout = async { service.findSessionByToken(token) }
|
||||
leader.await()
|
||||
afterLogout.await()
|
||||
|
||||
assertEquals(2, repository.lookups.get(), "the request after logout must run its own lookup")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `lookup that finished before a request arrived is not reused`() = runBlocking {
|
||||
val repository = CountingSessionRepository(session)
|
||||
val service = service(singleFlight = true, repository, ColdCache())
|
||||
|
||||
service.findSessionByToken(token)
|
||||
service.findSessionByToken(token)
|
||||
|
||||
assertEquals(2, repository.lookups.get())
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -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"))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.extensions.ErrorBody
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Chat
|
||||
import com.mtusi.messenger.main.support.TestDatabase
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.support.TestUser
|
||||
import com.mtusi.messenger.main.support.auth
|
||||
import com.mtusi.messenger.main.support.createChat
|
||||
import com.mtusi.messenger.main.support.register
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import com.mtusi.messenger.main.utils.computeSha256
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.basicAuth
|
||||
import io.ktor.client.request.delete
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.client.statement.HttpResponse
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.contentType
|
||||
import org.testcontainers.containers.GenericContainer
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
class DependencyFailureTest {
|
||||
|
||||
/**
|
||||
* An unknown token can only be checked against PostgreSQL, so without it the answer is 503, never a success.
|
||||
*/
|
||||
private suspend fun HttpClient.assertAnonymousRejected(
|
||||
unknownTokenStatus: HttpStatusCode = HttpStatusCode.Unauthorized
|
||||
) {
|
||||
assertEquals(HttpStatusCode.Unauthorized, get("/api/v1/users/me").status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, get("/api/v1/users/me") { header("X-User-Id", "1") }.status)
|
||||
assertEquals(
|
||||
unknownTokenStatus,
|
||||
get("/api/v1/users/me") { header("Authorization", "Bearer never-issued-token") }.status
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun assertUnavailable(response: HttpResponse) {
|
||||
assertEquals(HttpStatusCode.ServiceUnavailable, response.status)
|
||||
assertEquals("unavailable", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without Redis requests bypass the cache`() = runApp(
|
||||
redis = TestRedis.unreachableEndpoint()
|
||||
) { client ->
|
||||
assertEquals(HttpStatusCode.OK, client.get("/health/ready").status)
|
||||
|
||||
val alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
client.createChat(alice, "no redis", listOf(alice.id, bob.id))
|
||||
|
||||
client.assertAnonymousRejected()
|
||||
|
||||
// PostgreSQL is the source of truth: logout still works and is visible immediately.
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hanging Redis costs one command timeout and recovers`() {
|
||||
val redis = TestRedis.create().also { it.start() }
|
||||
val docker = redis.dockerClient
|
||||
|
||||
try {
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
val alice = client.register("alice")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
docker.pauseContainerCmd(redis.containerId).exec()
|
||||
|
||||
val started = TimeSource.Monotonic.markNow()
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertTrue(started.elapsedNow() < 2.seconds, "cache lookup must be bounded by the command timeout")
|
||||
|
||||
client.assertAnonymousRejected()
|
||||
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
docker.unpauseContainerCmd(redis.containerId).exec()
|
||||
|
||||
// The copy cached before the pause is replaced by the delayed tombstone, not resurrected.
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
val bob = client.register("bob")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(bob) }.status)
|
||||
assertTrue(
|
||||
TestRedis.cli(redis, "EXISTS", "session:${bob.token.toByteArray().computeSha256()}") == "1",
|
||||
"cache is used again after recovery"
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
redis.stop()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tombstone written by a logout during an outage can be lost while the copy cached before it survives
|
||||
* (here: put back by hand). The revocation kept in PostgreSQL must still win once Redis is reachable again.
|
||||
*/
|
||||
private fun loseTombstone(redis: GenericContainer<*>, user: TestUser, cachedCopy: String) {
|
||||
TestRedis.cli(redis, "SET", "session:${user.token.toByteArray().computeSha256()}", cachedCopy, "PX", "60000")
|
||||
}
|
||||
|
||||
private fun cachedCopy(redis: GenericContainer<*>, user: TestUser): String {
|
||||
return TestRedis.cli(redis, "GET", "session:${user.token.toByteArray().computeSha256()}")
|
||||
.also { assertTrue(it.contains(user.id.toString()), "session must be cached before the outage") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout during a Redis outage is not undone by a stale cached copy`() {
|
||||
val redis = TestRedis.create().also { it.start() }
|
||||
val docker = redis.dockerClient
|
||||
|
||||
try {
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
val alice = client.register("alice")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
val copy = cachedCopy(redis, alice)
|
||||
|
||||
docker.pauseContainerCmd(redis.containerId).exec()
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
docker.unpauseContainerCmd(redis.containerId).exec()
|
||||
|
||||
loseTombstone(redis, alice, copy)
|
||||
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertEquals("revoked", TestRedis.cli(redis, "GET", "session:${alice.token.toByteArray().computeSha256()}"))
|
||||
}
|
||||
} finally {
|
||||
redis.stop()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout during a Redis outage survives an API restart`() {
|
||||
val redis = TestRedis.create().also { it.start() }
|
||||
val docker = redis.dockerClient
|
||||
|
||||
lateinit var alice: TestUser
|
||||
lateinit var chat: Chat
|
||||
lateinit var copy: String
|
||||
|
||||
try {
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
chat = client.createChat(alice, "restart", listOf(alice.id, bob.id))
|
||||
copy = cachedCopy(redis, alice)
|
||||
|
||||
docker.pauseContainerCmd(redis.containerId).exec()
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
}
|
||||
|
||||
docker.unpauseContainerCmd(redis.containerId).exec()
|
||||
loseTombstone(redis, alice, copy)
|
||||
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/chats/${chat.id}/messages") { auth(alice) }.status)
|
||||
assertEquals(
|
||||
HttpStatusCode.Unauthorized,
|
||||
client.post("/api/v1/chats/${chat.id}/messages") {
|
||||
auth(alice)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "after logout"))
|
||||
}.status
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
redis.stop()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without PostgreSQL requests fail with a bounded 503`() {
|
||||
val database = TestDatabase.create().also { it.start() }
|
||||
|
||||
try {
|
||||
runApp(database = database, databaseConnectionTimeoutMs = 2000) { client ->
|
||||
val alice = client.register("alice")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
database.dockerClient.stopContainerCmd(database.containerId).exec()
|
||||
|
||||
val started = TimeSource.Monotonic.markNow()
|
||||
|
||||
// The session itself is still served from Redis, the user lookup needs PostgreSQL.
|
||||
assertUnavailable(client.get("/api/v1/users/me") { auth(alice) })
|
||||
assertUnavailable(client.post("/api/v1/auth/sessions") { basicAuth(alice.user.username, alice.password) })
|
||||
assertEquals(HttpStatusCode.ServiceUnavailable, client.get("/health/ready").status)
|
||||
assertEquals(HttpStatusCode.OK, client.get("/health/live").status)
|
||||
|
||||
assertTrue(started.elapsedNow() < 15.seconds, "every request must fail within the pool timeout")
|
||||
|
||||
client.assertAnonymousRejected(unknownTokenStatus = HttpStatusCode.ServiceUnavailable)
|
||||
}
|
||||
} finally {
|
||||
database.stop()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.support.TestUser
|
||||
import com.mtusi.messenger.main.support.auth
|
||||
import com.mtusi.messenger.main.support.register
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import com.mtusi.messenger.main.utils.computeSha256
|
||||
import io.ktor.client.request.delete
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class SessionCacheTest {
|
||||
|
||||
private val redis = TestRedis.container
|
||||
|
||||
private fun cached(user: TestUser): String {
|
||||
return TestRedis.cli(redis, "GET", "session:${user.token.toByteArray().computeSha256()}")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `first authenticated request fills the cache`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
|
||||
assertEquals("", cached(alice), "login does not write to the cache")
|
||||
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
assertTrue(cached(alice).contains(alice.id.toString()))
|
||||
|
||||
// The session lives for an hour, its cached copy at most sessionCacheTtlSeconds.
|
||||
val ttl = TestRedis.cli(redis, "TTL", "session:${alice.token.toByteArray().computeSha256()}").toLong()
|
||||
assertTrue(ttl in 1..60, "cached copy TTL was $ttl")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout leaves a tombstone and the token is rejected`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
client.get("/api/v1/users/me") { auth(alice) }
|
||||
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
|
||||
assertEquals("revoked", cached(alice))
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `emptied cache falls back to PostgreSQL`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
client.get("/api/v1/users/me") { auth(alice) }
|
||||
client.delete("/api/v1/auth/sessions/current") { auth(bob) }
|
||||
|
||||
TestRedis.cli(redis, "FLUSHALL")
|
||||
|
||||
// PostgreSQL is the source of truth: the live session survives, the revoked one stays revoked.
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(bob) }.status)
|
||||
assertTrue(cached(alice).contains(alice.id.toString()), "cache is filled again")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.mtusi.messenger.main.support
|
||||
|
||||
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.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.http.ContentType
|
||||
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 org.testcontainers.containers.PostgreSQLContainer
|
||||
import java.util.UUID
|
||||
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
val testJson = Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
namingStrategy = JsonNamingStrategy.SnakeCase
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
data class RedisEndpoint(
|
||||
val host: String,
|
||||
val port: Int,
|
||||
)
|
||||
|
||||
private fun testConfig(
|
||||
sessionTtlSeconds: Long,
|
||||
database: PostgreSQLContainer<*>,
|
||||
databaseConnectionTimeoutMs: Long,
|
||||
redis: RedisEndpoint,
|
||||
) = HoconApplicationConfig(
|
||||
ConfigFactory.parseMap(
|
||||
mapOf(
|
||||
"database.host" to database.host,
|
||||
"database.port" to database.firstMappedPort,
|
||||
"database.name" to database.databaseName,
|
||||
"database.username" to database.username,
|
||||
"database.password" to database.password,
|
||||
"database.maxPoolSize" to 10,
|
||||
"database.connectionTimeoutMs" to databaseConnectionTimeoutMs,
|
||||
"database.statementTimeoutMs" to 5000,
|
||||
"redis.host" to redis.host,
|
||||
"redis.port" to redis.port,
|
||||
"redis.password" to TestRedis.PASSWORD,
|
||||
"redis.connectTimeoutMs" to 500,
|
||||
"redis.commandTimeoutMs" to 500,
|
||||
"authentication.realm" to "messenger",
|
||||
"authentication.sessionTtlSeconds" to sessionTtlSeconds,
|
||||
"authentication.sessionCacheTtlSeconds" to 60,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
/**
|
||||
* Docker Desktop can be slow to accept the first connection, hence the generous default database timeout.
|
||||
*/
|
||||
fun runApp(
|
||||
sessionTtlSeconds: Long = 3600,
|
||||
database: PostgreSQLContainer<*> = TestDatabase.container,
|
||||
databaseConnectionTimeoutMs: Long = 10000,
|
||||
redis: RedisEndpoint = TestRedis.endpoint(),
|
||||
block: suspend ApplicationTestBuilder.(HttpClient) -> Unit
|
||||
) = testApplication {
|
||||
environment {
|
||||
config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis)
|
||||
}
|
||||
application {
|
||||
module()
|
||||
}
|
||||
val client = createClient {
|
||||
install(ContentNegotiation) {
|
||||
json(testJson)
|
||||
}
|
||||
}
|
||||
block(client)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = 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: TestUser,
|
||||
title: String,
|
||||
memberIds: List<UUID>,
|
||||
): Chat {
|
||||
val response = post("/api/v1/chats") {
|
||||
auth(creator)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateChatRequest(title = title, memberIds = memberIds.map(UUID::toString)))
|
||||
}
|
||||
check(response.status == HttpStatusCode.Created) { "createChat failed: ${response.status}" }
|
||||
return response.body()
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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 {
|
||||
create().also { it.start() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A separate, not yet started container for tests that stop the database.
|
||||
*/
|
||||
fun create(): PostgreSQLContainer<*> {
|
||||
return PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres"))
|
||||
.withDatabaseName(NAME)
|
||||
.withUsername(USERNAME)
|
||||
.withPassword(PASSWORD)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.mtusi.messenger.main.support
|
||||
|
||||
import org.testcontainers.containers.GenericContainer
|
||||
import org.testcontainers.utility.DockerImageName
|
||||
import java.net.ServerSocket
|
||||
|
||||
/**
|
||||
* One Redis container per test JVM, same image and memory settings as compose.yaml.
|
||||
*/
|
||||
object TestRedis {
|
||||
|
||||
const val PASSWORD = "messenger"
|
||||
|
||||
private const val PORT = 6379
|
||||
|
||||
val container: GenericContainer<*> by lazy {
|
||||
create().also { it.start() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A separate, not yet started container for tests that pause or flush Redis.
|
||||
*/
|
||||
fun create(): GenericContainer<*> {
|
||||
return GenericContainer(DockerImageName.parse("redis:8.4.0-alpine"))
|
||||
.withExposedPorts(PORT)
|
||||
.withCommand(
|
||||
"redis-server",
|
||||
"--requirepass", PASSWORD,
|
||||
"--save", "",
|
||||
"--appendonly", "no",
|
||||
"--maxmemory-policy", "volatile-lru"
|
||||
)
|
||||
}
|
||||
|
||||
fun endpoint(container: GenericContainer<*> = this.container) = RedisEndpoint(
|
||||
host = container.host,
|
||||
port = container.getMappedPort(PORT)
|
||||
)
|
||||
|
||||
/**
|
||||
* An endpoint nobody listens on: connections are refused immediately.
|
||||
*/
|
||||
fun unreachableEndpoint(): RedisEndpoint {
|
||||
val port = ServerSocket(0).use { it.localPort }
|
||||
return RedisEndpoint(host = "127.0.0.1", port = port)
|
||||
}
|
||||
|
||||
fun cli(container: GenericContainer<*>, vararg command: String): String {
|
||||
val result = container.execInContainer("redis-cli", "--no-auth-warning", "-a", PASSWORD, *command)
|
||||
check(result.exitCode == 0) { "redis-cli failed: ${result.stderr}" }
|
||||
return result.stdout.trim()
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user