From 9fd7421f011981541c2363315ffb5864fb073c46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franc=CC=A7ois=20Benaiteau?= Date: Wed, 2 Dec 2026 16:13:02 +0100 Subject: [PATCH 1/2] feat: mention mapped GitHub users in Wire --- README.md | 17 ++ .../kotlin/com/wire/github/AuthorMentions.kt | 75 +++++++ .../kotlin/com/wire/github/EventsHandler.kt | 3 +- .../com/wire/github/GitHubCommandHandler.kt | 45 ++++- .../kotlin/com/wire/github/RedisService.kt | 28 +++ src/main/kotlin/com/wire/github/Routing.kt | 12 +- .../github/response/model/GitHubResponse.kt | 2 + .../com/wire/github/util/TemplateHandler.kt | 44 +++++ .../en/pull_request.review_requested.template | 4 + .../kotlin/com/wire/github/ApplicationTest.kt | 64 ++++++ .../com/wire/github/AuthorMentionsTest.kt | 184 ++++++++++++++++++ .../wire/github/GitHubCommandHandlerTest.kt | 39 ++++ .../com/wire/github/RedisServiceTest.kt | 22 +++ 13 files changed, 534 insertions(+), 5 deletions(-) create mode 100644 src/main/kotlin/com/wire/github/AuthorMentions.kt create mode 100644 src/main/resources/templates/en/pull_request.review_requested.template create mode 100644 src/test/kotlin/com/wire/github/AuthorMentionsTest.kt diff --git a/README.md b/README.md index 921f37f..d89a80c 100644 --- a/README.md +++ b/README.md @@ -74,12 +74,29 @@ The action accepts these inputs: | Command | Description | |---------|-------------| +| `/github map @Wire user` | Register or replace an author mapping for this conversation; select the user with Wire’s mention picker. | | `/github help` | List available commands and notification approaches. | | `/github tokens` | Show or create the webhook secret and Actions token. | | `/github webhook help` | Show repository webhook setup instructions. | | `/github actions help` | Show the Actions endpoint, token usage, and reusable action example. | +Mappings are stored in Redis per conversation and preserve the registered login's capitalization. +Any conversation participant can register or replace a mapping. Use the same command again to update it. + +| Notification | Who receives a native Wire mention | +|--------------|-------------------------------------| +| PR review request | The mapped requested reviewer. | +| PR review, PR inline comment, issue/PR conversation comment | Explicit `@github-login` tags in the body, excluding the reviewer/comment author. | +| Issue opened, reopened, closed | Explicit tags in the rendered title/body, excluding the issue author. | +| Custom Actions message | Explicit tags in `text`. | +| Other repository notifications | Nobody. | + +Explicit tags require `@` and exact capitalization: mapping `octocat` matches `@octocat`, +but not `octocat` or `@Octocat`. Unmapped tags remain text. Email addresses and URL paths +are excluded. Team review requests do not create individual notifications. +Enable **Pull requests** in the repository webhook settings to receive review requests. + ## Building & Running To build or run the project, you can use the IDE Run configuration with environment variables. diff --git a/src/main/kotlin/com/wire/github/AuthorMentions.kt b/src/main/kotlin/com/wire/github/AuthorMentions.kt new file mode 100644 index 0000000..abffc53 --- /dev/null +++ b/src/main/kotlin/com/wire/github/AuthorMentions.kt @@ -0,0 +1,75 @@ +package com.wire.github + +import com.wire.github.response.model.GitHubResponse +import com.wire.github.util.TemplateHandler +import com.wire.sdk.model.QualifiedId +import com.wire.sdk.model.WireMessage + +internal fun reviewRequestMentions( + event: String, + response: GitHubResponse, + conversationId: QualifiedId, + redisService: RedisService +): List { + if (event != "pull_request" || response.action != "review_requested") return emptyList() + return response.requestedReviewer + ?.login + ?.let { login -> + redisService.getAuthorMapping(conversationId, login)?.let { userId -> + // The review-request template starts with the requested reviewer's @login. + listOf(WireMessage.Mention(userId = userId, offset = 0, length = login.length + 1)) + } + }.orEmpty() +} + +internal fun actionsMentions( + text: String, + conversationId: QualifiedId, + redisService: RedisService +): List { + val mappings = redisService.getAuthorMappings(conversationId) + return textMentions(text, mappings) +} + +private fun textMentions( + text: String, + mappings: Map +): List { + if (mappings.isEmpty()) return emptyList() + val logins = mappings.keys.joinToString("|", transform = Regex::escape) + val pattern = Regex("(? + WireMessage.Mention( + mappings.getValue(match.groupValues[1]), + match.range.first, + match.value.length + ) + }.toList() +} + +internal fun TemplateHandler.repositoryMentions( + event: String, + response: GitHubResponse, + text: String, + conversationId: QualifiedId, + redisService: RedisService +): List { + val author = when (event) { + "pull_request_review" -> response.review?.user?.login ?: response.sender.login + "pull_request_review_comment", "issue_comment" -> response.comment?.user?.login + "issues" -> response.issue?.user?.login + else -> return reviewRequestMentions(event, response, conversationId, redisService) + } + val mappings = redisService.getAuthorMappings(conversationId) + val authorIds = mappings.filterKeys { it.equals(author, ignoreCase = true) }.values.toSet() + val others = mappings.filter { (login, userId) -> + !login.equals(author, ignoreCase = true) && userId !in authorIds + } + return mentionRanges(event, response).flatMap { range -> + textMentions(text.substring(range), others).map { mention -> + mention.copy(offset = mention.offset + range.first) + } + } +} diff --git a/src/main/kotlin/com/wire/github/EventsHandler.kt b/src/main/kotlin/com/wire/github/EventsHandler.kt index 1eb5d00..c1dc127 100644 --- a/src/main/kotlin/com/wire/github/EventsHandler.kt +++ b/src/main/kotlin/com/wire/github/EventsHandler.kt @@ -20,7 +20,8 @@ class EventsHandler : WireEventsHandlerSuspending() { override suspend fun onTextMessageReceived(wireMessage: WireMessage.Text) { val response = commandHandler.response( command = wireMessage.text, - conversationId = wireMessage.conversationId + conversationId = wireMessage.conversationId, + mentions = wireMessage.mentions ) ?: return logger.info( diff --git a/src/main/kotlin/com/wire/github/GitHubCommandHandler.kt b/src/main/kotlin/com/wire/github/GitHubCommandHandler.kt index d4ced02..cc29363 100644 --- a/src/main/kotlin/com/wire/github/GitHubCommandHandler.kt +++ b/src/main/kotlin/com/wire/github/GitHubCommandHandler.kt @@ -5,6 +5,7 @@ import com.wire.github.util.ENV_VAR_HOST import com.wire.github.util.ActionsTokenGenerator import com.wire.github.util.SessionIdentifierGenerator import com.wire.sdk.model.QualifiedId +import com.wire.sdk.model.WireMessage internal class GitHubCommandHandler( private val redisService: RedisService, @@ -15,15 +16,47 @@ internal class GitHubCommandHandler( ) { fun response( command: String, - conversationId: QualifiedId + conversationId: QualifiedId, + mentions: List = emptyList() ): String? = when (command.lowercase()) { HELP_COMMAND -> trackedHelp(help()) WEBHOOK_HELP_COMMAND -> trackedHelp(webhookHelp(conversationId)) ACTIONS_HELP_COMMAND -> trackedHelp(actionsHelp(conversationId)) - else -> null + else -> registerMapping(command, conversationId, mentions) } + private fun registerMapping( + command: String, + conversationId: QualifiedId, + mentions: List + ): String? { + val parts = command.split(Regex("\\s+"), limit = 4) + if (!parts.first().equals("/github", ignoreCase = true) || + !parts.getOrNull(1).equals("map", ignoreCase = true) + ) { + return null + } + val match = MAPPING_COMMAND.matchEntire(command) + val mention = mentions.singleOrNull() + val login = match + ?.groupValues + ?.get(1) + .orEmpty() + .removePrefix("@") + val target = match?.groups?.get(2) + val selectedUser = mention?.takeIf { + it.offset == target?.range?.first && it.length == target.value.length + } + return if (!GITHUB_LOGIN.matches(login) || selectedUser == null) { + "Usage: `/github map @Wire user` " + + "(select one user from Wire's mention picker)." + } else { + redisService.setAuthorMapping(conversationId, login, selectedUser.userId) + "Mapped GitHub @$login to the selected Wire user in this conversation." + } + } + fun help(): String = "GitHub App supports repository webhooks and workflow-authored Actions notifications.\n\n" + HELP_COMMANDS @@ -76,11 +109,19 @@ internal class GitHubCommandHandler( get() = host.trimEnd('/') companion object { + private val MAPPING_COMMAND = Regex( + "/github\\s+map\\s+([^\\s]+)\\s+(.+)", + RegexOption.IGNORE_CASE + ) + private val GITHUB_LOGIN = Regex( + "[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?(?:\\[bot\\])?" + ) const val HELP_COMMAND = "/github help" const val WEBHOOK_HELP_COMMAND = "/github webhook help" const val ACTIONS_HELP_COMMAND = "/github actions help" const val HELP_COMMANDS = "Available commands:\n" + + "- `/github map @Wire user` - map a PR reviewer\n" + "- `$WEBHOOK_HELP_COMMAND` - configure GitHub repository webhooks\n" + "- `$ACTIONS_HELP_COMMAND` - send custom messages from GitHub Actions\n" + "- `$HELP_COMMAND` - Show this help message" diff --git a/src/main/kotlin/com/wire/github/RedisService.kt b/src/main/kotlin/com/wire/github/RedisService.kt index e259ee9..b20ad43 100644 --- a/src/main/kotlin/com/wire/github/RedisService.kt +++ b/src/main/kotlin/com/wire/github/RedisService.kt @@ -10,9 +10,37 @@ import java.util.UUID import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec +@Suppress("TooManyFunctions") class RedisService( private val storage: RedisCommands ) { + fun getAuthorMapping( + conversationId: QualifiedId, + login: String + ): QualifiedId? = + storage + .hget( + "${conversationId.toWebhookStorageKey()}:authors", + login + )?.let(QualifiedId::fromFullString) + + fun getAuthorMappings(conversationId: QualifiedId): Map = + storage + .hgetall("${conversationId.toWebhookStorageKey()}:authors") + .mapValues { (_, userId) -> QualifiedId.fromFullString(userId) } + + fun setAuthorMapping( + conversationId: QualifiedId, + login: String, + userId: QualifiedId + ) { + storage.hset( + "${conversationId.toWebhookStorageKey()}:authors", + login, + userId.toFullString() + ) + } + fun getWebhookSecret(conversationId: QualifiedId): String? = storage.get(conversationId.toWebhookStorageKey()) diff --git a/src/main/kotlin/com/wire/github/Routing.kt b/src/main/kotlin/com/wire/github/Routing.kt index 66293e1..54fe44f 100644 --- a/src/main/kotlin/com/wire/github/Routing.kt +++ b/src/main/kotlin/com/wire/github/Routing.kt @@ -143,7 +143,14 @@ fun Application.configureRouting() { id = UUID.fromString(conversationId), domain = conversationDomain ), - text = messageTemplate + text = messageTemplate, + mentions = templateHandler.repositoryMentions( + event, + response, + messageTemplate, + QualifiedId(UUID.fromString(conversationId), conversationDomain), + redisService + ) ) ) usageMetrics.onNotificationSent(event = event) @@ -212,7 +219,8 @@ private fun Route.configureActionsRoute( wireAppSdk.getApplicationManager().sendMessage( message = WireMessage.Text.create( conversationId = qualifiedConversationId, - text = request.text + text = request.text, + mentions = actionsMentions(request.text, qualifiedConversationId, redisService) ) ) call.response.status(HttpStatusCode.OK) diff --git a/src/main/kotlin/com/wire/github/response/model/GitHubResponse.kt b/src/main/kotlin/com/wire/github/response/model/GitHubResponse.kt index 6887bda..7d9bb70 100644 --- a/src/main/kotlin/com/wire/github/response/model/GitHubResponse.kt +++ b/src/main/kotlin/com/wire/github/response/model/GitHubResponse.kt @@ -8,6 +8,8 @@ data class GitHubResponse( val action: String? = null, @SerialName("pull_request") val pullRequest: PullRequest? = null, + @SerialName("requested_reviewer") + val requestedReviewer: User? = null, val comment: Comment? = null, val issue: Issue? = null, val commits: List = emptyList(), diff --git a/src/main/kotlin/com/wire/github/util/TemplateHandler.kt b/src/main/kotlin/com/wire/github/util/TemplateHandler.kt index e497ee5..f9f28d5 100644 --- a/src/main/kotlin/com/wire/github/util/TemplateHandler.kt +++ b/src/main/kotlin/com/wire/github/util/TemplateHandler.kt @@ -7,6 +7,7 @@ import com.wire.github.response.model.GitHubResponse import java.io.PrintWriter import java.io.StringWriter import java.util.Locale +import java.util.UUID import org.slf4j.LoggerFactory class TemplateHandler { @@ -33,6 +34,49 @@ class TemplateHandler { null } + fun mentionRanges( + event: String, + response: GitHubResponse + ): List { + val content = mutableMapOf() + + fun mark(value: String?): String? = + value?.let { + val marker = UUID.randomUUID().toString() + content[marker] = it + marker + } + val marked = when (event) { + "pull_request_review" -> response.copy( + review = response.review?.let { it.copy(body = mark(it.body)) } + ) + "pull_request_review_comment", "issue_comment" -> response.copy( + comment = response.comment?.let { it.copy(body = mark(it.body)) } + ) + "issues" -> response.copy( + issue = response.issue?.let { + it.copy( + title = mark(it.title)!!, + body = mark(it.body) + ) + } + ) + else -> return emptyList() + } + val rendered = handleEvent(event, marked).orEmpty() + // Placeholders distinguish user-authored fields from identical text in headers. + var adjustment = 0 + return content.entries + .mapNotNull { (marker, value) -> + rendered.indexOf(marker).takeIf { it >= 0 }?.let { Triple(it, marker, value) } + }.sortedBy { it.first } + .map { (offset, marker, value) -> + val start = offset + adjustment + adjustment += value.length - marker.length + start until start + value.length + } + } + private fun compileTemplate( event: String, action: String? diff --git a/src/main/resources/templates/en/pull_request.review_requested.template b/src/main/resources/templates/en/pull_request.review_requested.template new file mode 100644 index 0000000..ded05b4 --- /dev/null +++ b/src/main/resources/templates/en/pull_request.review_requested.template @@ -0,0 +1,4 @@ +{{#requestedReviewer}}@{{requestedReviewer.login}}, your review was requested by **{{sender.login}}**. +**[{{repository.fullName}}]** PR #{{pullRequest.number}}: **{{{pullRequest.title}}}** +{{pullRequest.htmlUrl}} +{{/requestedReviewer}} \ No newline at end of file diff --git a/src/test/kotlin/com/wire/github/ApplicationTest.kt b/src/test/kotlin/com/wire/github/ApplicationTest.kt index 0283193..2c8872a 100644 --- a/src/test/kotlin/com/wire/github/ApplicationTest.kt +++ b/src/test/kotlin/com/wire/github/ApplicationTest.kt @@ -36,6 +36,7 @@ class ApplicationTest { @BeforeTest fun setupKoin() { val redisService = mockk() + every { redisService.getAuthorMappings(any()) } returns emptyMap() val mockWireAppSdk = mockk(relaxed = true) startKoin { @@ -104,6 +105,7 @@ class ApplicationTest { @Test fun `given a delivery is rendered, when GET metrics, then funnel counters are set`() { val redisService = mockk() + every { redisService.getAuthorMappings(any()) } returns emptyMap() every { redisService.isWebhookSignatureValid(any(), any(), any(), any()) } returns true val wireAppSdk = mockk() @@ -157,6 +159,7 @@ class ApplicationTest { @Test fun `given no template for the event, when GET metrics, then unsupported counter is exposed`() { val redisService = mockk() + every { redisService.getAuthorMappings(any()) } returns emptyMap() every { redisService.isWebhookSignatureValid(any(), any(), any(), any()) } returns true val wireAppSdk = mockk(relaxed = true) @@ -210,6 +213,7 @@ class ApplicationTest { @Test fun `given received event, when pull_request is created, then validations are passing`() { val redisService = mockk() + every { redisService.getAuthorMappings(any()) } returns emptyMap() every { redisService.isWebhookSignatureValid( conversationId = CONVERSATION_ID.id.toString(), @@ -270,6 +274,7 @@ class ApplicationTest { @Test fun `given invalid signature, when webhook is posted, then forbidden without sending`() { val redisService = mockk() + every { redisService.getAuthorMappings(any()) } returns emptyMap() every { redisService.isWebhookSignatureValid(any(), any(), any(), any()) } returns false val wireAppSdk = mockk(relaxed = true) loadKoinModules( @@ -299,6 +304,7 @@ class ApplicationTest { @Test fun `given malformed payload, when webhook is posted, then bad request without sending`() { val redisService = mockk() + every { redisService.getAuthorMappings(any()) } returns emptyMap() every { redisService.isWebhookSignatureValid(any(), any(), any(), any()) } returns true val wireAppSdk = mockk(relaxed = true) loadKoinModules( @@ -328,6 +334,7 @@ class ApplicationTest { @Test fun `given completed GitHub Actions events, when received, then messages are sent`() { val redisService = mockk() + every { redisService.getAuthorMappings(any()) } returns emptyMap() every { redisService.isWebhookSignatureValid(any(), any(), any(), any()) } returns true val wireAppSdk = mockk() @@ -365,6 +372,39 @@ class ApplicationTest { } } + @Test + fun `review request webhook mentions its mapped reviewer`() { + val redisService = GlobalContext.get().get() + val wireAppSdk = GlobalContext.get().get() + val userId = QualifiedId(UUID.randomUUID(), "user.example.com") + every { redisService.isWebhookSignatureValid(any(), any(), any(), any()) } returns true + every { redisService.getAuthorMapping(CONVERSATION_ID, "Octocat") } returns userId + val sentMessage = slot() + every { + wireAppSdk.getApplicationManager().sendMessage(message = capture(sentMessage)) + } returns UUID.randomUUID() + val payload = TestFixtures.event("pull_request.opened").replaceFirst( + "\"action\": \"opened\"", + "\"action\": \"review_requested\", " + + "\"requested_reviewer\": {\"login\": \"Octocat\", \"avatar_url\": \"\"}" + ) + + testApplication { + application { configureRouting() } + val response = client.post("/${CONVERSATION_ID.id}/${CONVERSATION_ID.domain}") { + contentType(ContentType.Application.Json) + header("X-GitHub-Event", "pull_request") + header("X-Hub-Signature", "sha1=$DUMMY_SIGNATURE") + header("X-GitHub-Delivery", "review-request") + setBody(payload) + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals(listOf(WireMessage.Mention(userId, 0, 8)), sentMessage.captured.mentions) + assertTrue(sentMessage.captured.text.startsWith("@Octocat,")) + } + } + @Test fun `given valid bearer token, when Actions message is posted, then message is sent`() { val (redisService, wireAppSdk) = loadActionsDependencies(tokenValid = true) @@ -385,6 +425,7 @@ class ApplicationTest { assertEquals("", response.bodyAsText()) assertEquals(CONVERSATION_ID, sentMessage.captured.conversationId) assertEquals("CI failed", sentMessage.captured.text) + assertTrue(sentMessage.captured.mentions.isEmpty()) verify(exactly = 1) { redisService.isActionsTokenValid(CONVERSATION_ID, ACTIONS_TOKEN) } @@ -392,6 +433,28 @@ class ApplicationTest { } } + @Test + fun `Actions message mentions an exact tagged name`() { + val (redisService, wireAppSdk) = loadActionsDependencies(tokenValid = true) + val userId = QualifiedId(UUID.randomUUID(), "user.example.com") + every { redisService.getAuthorMappings(CONVERSATION_ID) } returns mapOf("octocat" to userId) + val sentMessage = slot() + every { + wireAppSdk.getApplicationManager().sendMessage(message = capture(sentMessage)) + } returns UUID.randomUUID() + + testApplication { + application { configureRouting() } + val response = client.postActionsMessage( + payload = """{"text":"πŸš€ @octocat: CI failed"}""" + ) + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals(listOf(WireMessage.Mention(userId, 3, 8)), sentMessage.captured.mentions) + assertEquals("πŸš€ @octocat: CI failed", sentMessage.captured.text) + } + } + @Test fun `Actions message without bearer authorization is unauthorized`() { listOf( @@ -514,6 +577,7 @@ class ApplicationTest { private fun loadActionsDependencies(tokenValid: Boolean): Pair { val redisService = mockk() + every { redisService.getAuthorMappings(any()) } returns emptyMap() every { redisService.isActionsTokenValid(any(), any()) } returns tokenValid val wireAppSdk = mockk(relaxed = true) loadKoinModules( diff --git a/src/test/kotlin/com/wire/github/AuthorMentionsTest.kt b/src/test/kotlin/com/wire/github/AuthorMentionsTest.kt new file mode 100644 index 0000000..aa3ee4f --- /dev/null +++ b/src/test/kotlin/com/wire/github/AuthorMentionsTest.kt @@ -0,0 +1,184 @@ +package com.wire.github + +import com.wire.github.response.model.GitHubResponse +import com.wire.github.response.model.User +import com.wire.github.util.KtxSerializer +import com.wire.github.util.TemplateHandler +import com.wire.sdk.model.QualifiedId +import io.mockk.every +import io.mockk.mockk +import java.util.UUID +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.test.assertNull + +class AuthorMentionsTest { + private val conversationId = QualifiedId(UUID.randomUUID(), "conversation.example.com") + private val userId = QualifiedId(UUID.randomUUID(), "user.example.com") + private val redisService = mockk() + private val response = KtxSerializer.json + .decodeFromString( + TestFixtures.event("pull_request.opened") + ).copy(action = "review_requested", requestedReviewer = User("", "Octocat")) + + @Test + fun `Actions require exact tagged names and preserve emoji offsets`() { + every { redisService.getAuthorMappings(conversationId) } returns mapOf("octocat" to userId) + val text = "πŸš€ @octocat please check Octocat octocat @Octocat @unknown and @octocat" + + val mentions = actionsMentions(text, conversationId, redisService) + + assertEquals(listOf(3, text.lastIndexOf('@')), mentions.map { it.offset }) + assertEquals(listOf(userId, userId), mentions.map { it.userId }) + assertEquals(listOf(8, 8), mentions.map { it.length }) + } + + @Test + fun `Actions do not mention partial names email addresses or URL paths`() { + every { redisService.getAuthorMappings(conversationId) } returns mapOf("octocat" to userId) + val text = "@octocat2 @octocat-bot @octocat[bot] octocat@example.com person@octocat.com " + + "https://example.com/@octocat https://example.com/octocat" + assertTrue(actionsMentions(text, conversationId, redisService).isEmpty()) + } + + @Test + fun `review and comment bodies mention other users only with exact tags`() { + val handler = TemplateHandler() + every { redisService.getAuthorMappings(conversationId) } returns mapOf( + "target" to userId, + "author" to QualifiedId(UUID.randomUUID(), "user.example.com") + ) + for (event in listOf( + "pull_request_review", + "pull_request_review_comment", + "issue_comment" + )) { + val action = if (event == "pull_request_review") "submitted" else "created" + val original = KtxSerializer.json.decodeFromString( + TestFixtures.event("$event.$action") + ) + val body = "πŸš€ @target please check; @author @Target target" + val author = User("", "author") + val model = original.copy( + review = original.review?.copy(body = body, user = author), + comment = original.comment?.copy(body = body, user = author), + pullRequest = original.pullRequest?.copy(title = "@target in title"), + issue = original.issue?.copy(title = "@target in title") + ) + val text = handler.handleEvent(event, model).orEmpty() + val mentions = handler.repositoryMentions( + event, + model, + text, + conversationId, + redisService + ) + + assertEquals(1, mentions.size, event) + assertEquals(text.indexOf(body) + 3, mentions.single().offset, event) + assertEquals(userId, mentions.single().userId, event) + } + } + + @Test + fun `issues mention tags in rendered title and body but exclude original author`() { + val handler = TemplateHandler() + every { redisService.getAuthorMappings(conversationId) } returns mapOf( + "target" to userId, + "author" to QualifiedId(UUID.randomUUID(), "user.example.com") + ) + val original = KtxSerializer.json.decodeFromString( + TestFixtures.event("issues.opened") + ) + for (action in listOf("opened", "reopened", "closed")) { + val model = original.copy( + action = action, + issue = original.issue!!.copy( + title = "πŸš€ @target & @author", + body = "Please ask @target and @author, not @Target", + user = User("", "author") + ) + ) + val text = handler.handleEvent("issues", model).orEmpty() + val mentions = handler.repositoryMentions( + "issues", + model, + text, + conversationId, + redisService + ) + + assertEquals(if (action == "closed") 1 else 2, mentions.size, action) + assertTrue(mentions.all { it.userId == userId }) + assertTrue( + mentions.all { text.substring(it.offset, it.offset + it.length) == "@target" } + ) + } + } + + @Test + fun `only the requested reviewer receives a mention at the rendered position`() { + every { redisService.getAuthorMapping(conversationId, "Octocat") } returns userId + val text = TemplateHandler().handleEvent("pull_request", response).orEmpty() + + val mention = reviewRequestMentions( + "pull_request", + response, + conversationId, + redisService + ).single() + + assertEquals(userId, mention.userId) + assertEquals("@Octocat", text.substring(mention.offset, mention.offset + mention.length)) + } + + @Test + fun `other notifications never mention users even when a reviewer is present`() { + assertTrue( + reviewRequestMentions("issues", response, conversationId, redisService).isEmpty() + ) + for (action in listOf("opened", "closed", "review_request_removed")) { + assertTrue( + reviewRequestMentions( + "pull_request", + response.copy(action = action), + conversationId, + redisService + ).isEmpty() + ) + } + } + + @Test + fun `unmapped reviewers and team requests have no mentions`() { + every { redisService.getAuthorMapping(conversationId, "Octocat") } returns null + assertTrue( + reviewRequestMentions("pull_request", response, conversationId, redisService).isEmpty() + ) + val teamRequest = response.copy(requestedReviewer = null) + assertTrue( + reviewRequestMentions( + "pull_request", + teamRequest, + conversationId, + redisService + ).isEmpty() + ) + assertNull(TemplateHandler().handleEvent("pull_request", teamRequest)) + } + + @Test + fun `mappings from another conversation domain are not used`() { + val otherConversation = QualifiedId(conversationId.id, "another.example.com") + every { redisService.getAuthorMapping(otherConversation, "Octocat") } returns null + assertTrue( + reviewRequestMentions( + "pull_request", + response, + otherConversation, + redisService + ).isEmpty() + ) + } +} diff --git a/src/test/kotlin/com/wire/github/GitHubCommandHandlerTest.kt b/src/test/kotlin/com/wire/github/GitHubCommandHandlerTest.kt index ab81b34..8cf1b6b 100644 --- a/src/test/kotlin/com/wire/github/GitHubCommandHandlerTest.kt +++ b/src/test/kotlin/com/wire/github/GitHubCommandHandlerTest.kt @@ -2,6 +2,7 @@ package com.wire.github import com.wire.github.metrics.UsageMetrics import com.wire.sdk.model.QualifiedId +import com.wire.sdk.model.WireMessage import io.mockk.every import io.mockk.mockk import io.mockk.verify @@ -115,6 +116,44 @@ class GitHubCommandHandlerTest { verify(exactly = 0) { usageMetrics.onHelpCommand() } } + @Test + fun `map registers the selected user with its domain`() { + val user = QualifiedId(UUID.randomUUID(), "other.example.com") + val command = "/github map Octocat @Wire User" + every { redisService.setAuthorMapping(CONVERSATION_ID, "Octocat", user) } returns Unit + + val response = handler.response( + command, + CONVERSATION_ID, + listOf(WireMessage.Mention(user, command.indexOf("@Wire"), "@Wire User".length)) + ) + + assertContains(response.orEmpty(), "Mapped GitHub @Octocat") + verify(exactly = 1) { redisService.setAuthorMapping(CONVERSATION_ID, "Octocat", user) } + } + + @Test + fun `map rejects plain text users invalid logins and misplaced mentions`() { + val user = QualifiedId(UUID.randomUUID(), "example.com") + for (command in listOf( + "/github map octocat @User", + "/github map bad/name @User", + "/github map" + )) { + assertContains(handler.response(command, CONVERSATION_ID).orEmpty(), "Usage:") + assertContains( + handler + .response( + command, + CONVERSATION_ID, + listOf(WireMessage.Mention(user, 0, 5)) + ).orEmpty(), + "Usage:" + ) + } + verify(exactly = 0) { redisService.setAuthorMapping(any(), any(), any()) } + } + private companion object { val CONVERSATION_ID = QualifiedId(UUID.randomUUID(), "conversation.example.com") const val EXISTING_SECRET = "existing-secret" diff --git a/src/test/kotlin/com/wire/github/RedisServiceTest.kt b/src/test/kotlin/com/wire/github/RedisServiceTest.kt index 9608805..9730634 100644 --- a/src/test/kotlin/com/wire/github/RedisServiceTest.kt +++ b/src/test/kotlin/com/wire/github/RedisServiceTest.kt @@ -17,6 +17,28 @@ class RedisServiceTest { private val storage = mockk>() private val service = RedisService(storage) + @Test + fun `author mappings are loaded only for the qualified conversation`() { + val user = QualifiedId(UUID.randomUUID(), "other.example.com") + every { storage.hgetall("$WEBHOOK_STORAGE_KEY:authors") } returns + mapOf("octocat" to user.toFullString()) + + assertEquals(mapOf("octocat" to user), service.getAuthorMappings(CONVERSATION_ID)) + } + + @Test + fun `author mapping preserves domain and login capitalization`() { + val user = QualifiedId(UUID.randomUUID(), "other.example.com") + val key = "$WEBHOOK_STORAGE_KEY:authors" + every { storage.hset(key, "OctoCat", user.toFullString()) } returns true + every { storage.hget(key, "OctoCat") } returns user.toFullString() + + service.setAuthorMapping(CONVERSATION_ID, "OctoCat", user) + + assertEquals(user, service.getAuthorMapping(CONVERSATION_ID, "OctoCat")) + verify { storage.hset(key, "OctoCat", user.toFullString()) } + } + @Test fun `get webhook secret reads the conversation storage key`() { every { storage.get(WEBHOOK_STORAGE_KEY) } returns WEBHOOK_SECRET From 0fbd9347b128a64479389a513f628237eebc69af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franc=CC=A7ois=20Benaiteau?= Date: Wed, 2 Dec 2026 23:58:49 +0100 Subject: [PATCH 2/2] fix: resolve plugin dependencies from Maven Central --- settings.gradle.kts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/settings.gradle.kts b/settings.gradle.kts index 19087c5..ad832b3 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1 +1,8 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } +} + rootProject.name = "github"