Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,7 @@ import java.nio.charset.StandardCharsets
import java.util.Collections
import kotlin.collections.HashSet

/**
* This class handles the connections to the given Destination.
*/
/** This class handles the connections to the given Destination. */
class DestinationHttpClient {

private val httpClient: CloseableHttpClient
Expand All @@ -58,30 +56,40 @@ class DestinationHttpClient {
companion object {
private val log by logger(DestinationHttpClient::class.java)

/**
* all valid response status
*/
private val VALID_RESPONSE_STATUS = Collections.unmodifiableSet(
HashSet(
listOf(
RestStatus.OK.status,
RestStatus.CREATED.status,
RestStatus.ACCEPTED.status,
RestStatus.NON_AUTHORITATIVE_INFORMATION.status,
RestStatus.NO_CONTENT.status,
RestStatus.RESET_CONTENT.status,
RestStatus.PARTIAL_CONTENT.status,
RestStatus.MULTI_STATUS.status
/** all valid response status */
private val VALID_RESPONSE_STATUS =
Collections.unmodifiableSet(
HashSet(
listOf(
RestStatus.OK.status,
RestStatus.CREATED.status,
RestStatus.ACCEPTED.status,
RestStatus.NON_AUTHORITATIVE_INFORMATION.status,
RestStatus.NO_CONTENT.status,
RestStatus.RESET_CONTENT.status,
RestStatus.PARTIAL_CONTENT.status,
RestStatus.MULTI_STATUS.status
)
)
)
)

private fun createHttpClient(): CloseableHttpClient {
val config: RequestConfig = RequestConfig.custom()
.setConnectTimeout(Timeout.ofMilliseconds(PluginSettings.connectionTimeout.toLong()))
.setConnectionRequestTimeout(Timeout.ofMilliseconds(PluginSettings.connectionTimeout.toLong()))
.setResponseTimeout(Timeout.ofMilliseconds(PluginSettings.socketTimeout.toLong()))
.build()
val config: RequestConfig =
RequestConfig.custom()
.setConnectTimeout(
Timeout.ofMilliseconds(
PluginSettings.connectionTimeout.toLong()
)
)
.setConnectionRequestTimeout(
Timeout.ofMilliseconds(
PluginSettings.connectionTimeout.toLong()
)
)
.setResponseTimeout(
Timeout.ofMilliseconds(PluginSettings.socketTimeout.toLong())
)
.build()
val connectionManager = PoolingHttpClientConnectionManager()
connectionManager.maxTotal = PluginSettings.maxConnections
connectionManager.defaultMaxPerRoute = PluginSettings.maxConnectionsPerRoute
Expand All @@ -97,7 +105,11 @@ class DestinationHttpClient {
}

@Throws(Exception::class)
fun execute(destination: WebhookDestination, message: MessageContent, referenceId: String): String {
fun execute(
destination: WebhookDestination,
message: MessageContent,
referenceId: String
): String {
var response: CloseableHttpResponse? = null
return try {
// validate webhook url against host_deny_list in plugin settings
Expand All @@ -115,17 +127,19 @@ class DestinationHttpClient {
}

@Throws(Exception::class)
private fun getHttpResponse(destination: WebhookDestination, message: MessageContent): CloseableHttpResponse {
private fun getHttpResponse(
destination: WebhookDestination,
message: MessageContent
): CloseableHttpResponse {
var httpRequest: HttpUriRequestBase = HttpPost(destination.url)

if (destination is CustomWebhookDestination) {
httpRequest = constructHttpRequest(destination.method, destination.url)
if (destination.headerParams.isEmpty()) {
// set default header
httpRequest.setHeader("Content-type", "application/json")
} else {
for ((key, value) in destination.headerParams.entries) httpRequest.setHeader(key, value)
}
for ((key, value) in destination.headerParams.entries) httpRequest.setHeader(key, value)
}

if (destination is MicrosoftTeamsDestination) {
httpRequest.setHeader("Content-Type", "application/json")
}

val entity = StringEntity(buildRequestBody(destination, message), StandardCharsets.UTF_8)
Expand All @@ -139,16 +153,21 @@ class DestinationHttpClient {
HttpPost.METHOD_NAME -> HttpPost(url)
HttpPut.METHOD_NAME -> HttpPut(url)
HttpPatch.METHOD_NAME -> HttpPatch(url)
else -> throw IllegalArgumentException(
"Invalid or empty method supplied. Only POST, PUT and PATCH are allowed"
)
else ->
throw IllegalArgumentException(
"Invalid or empty method supplied. Only POST, PUT and PATCH are allowed"
)
}
}

@Throws(IOException::class)
fun getResponseString(response: CloseableHttpResponse): String {
val entity: HttpEntity = response.entity ?: return "{}"
val responseString = EntityUtils.toString(entity, PluginSettings.maxHttpResponseSize / 2) // Java char is 2 bytes
val responseString =
EntityUtils.toString(
entity,
PluginSettings.maxHttpResponseSize / 2
) // Java char is 2 bytes
// DeliveryStatus need statusText must not be empty, convert empty response to {}
return if (responseString.isNullOrEmpty()) "{}" else responseString
}
Expand All @@ -162,24 +181,55 @@ class DestinationHttpClient {
}

fun buildRequestBody(destination: WebhookDestination, message: MessageContent): String {
val builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)
val keyName = when (destination) {
// Slack webhook request body has required "text" as key name https://api.slack.com/messaging/webhooks
// Chime webhook request body has required "Content" as key name
// Microsoft Teams webhook request body has required "text" as key name https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/what-are-webhooks-and-connectors
// Customer webhook allows input as json or plain text, so we just return the message as it is
is SlackDestination -> "text"
is ChimeDestination -> "Content"
is MicrosoftTeamsDestination -> "text"
is CustomWebhookDestination -> return message.textDescription
else -> throw IllegalArgumentException(
"Invalid destination type is provided, Only Slack, Chime, Microsoft Teams and CustomWebhook are allowed"
)
if (destination is MicrosoftTeamsDestination) {
val builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)
builder.startObject()
.startArray("attachments")
.startObject()
.field("contentType", "application/vnd.microsoft.card.adaptive")
.startObject("content")
.field("type", "AdaptiveCard")
.field("version", "1.2")
.startArray("body")
.startObject()
.field("type", "TextBlock")
.field("text", message.title)
.field("weight", "Bolder")
.field("color", "Attention")
.endObject()
.startObject()
.field("type", "TextBlock")
.field("text", message.textDescription)
.field("wrap", true)
.endObject()
.endArray()
.endObject()
.endObject()
.endArray()
.endObject()
return builder.string()
}

builder.startObject()
.field(keyName, message.buildMessageWithTitle())
.endObject()
val builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)
val keyName =
when (destination) {
// Slack webhook request body has required "text" as key name
// https://api.slack.com/messaging/webhooks
// Chime webhook request body has required "Content" as key name
// Microsoft Teams webhook request body has required "text" as key name
// https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/what-are-webhooks-and-connectors
// Customer webhook allows input as json or plain text, so we just return the
// message as it is
is SlackDestination -> "text"
is ChimeDestination -> "Content"
is CustomWebhookDestination -> return message.textDescription
else ->
throw IllegalArgumentException(
"Invalid destination type is provided, Only Slack, Chime, Microsoft Teams and CustomWebhook are allowed"
)
}

builder.startObject().field(keyName, message.buildMessageWithTitle()).endObject()
return builder.string()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,70 +50,83 @@ internal class MicrosoftTeamsDestinationTests {

@BeforeEach
fun setup() {
// Stubbing isHostInDenylist() so it doesn't attempt to resolve hosts that don't exist in the unit tests
// Stubbing isHostInDenylist() so it doesn't attempt to resolve hosts that don't exist in
// the unit tests
mockkStatic("org.opensearch.notifications.spi.utils.ValidationHelpersKt")
every { org.opensearch.notifications.spi.utils.isHostInDenylist(any(), any()) } returns false
every { org.opensearch.notifications.spi.utils.getResolvedIps(any()) } returns listOf(IPAddressString("174.0.0.0"))
every { org.opensearch.notifications.spi.utils.isHostInDenylist(any(), any()) } returns
false
every { org.opensearch.notifications.spi.utils.getResolvedIps(any()) } returns
listOf(IPAddressString("174.0.0.0"))
}

@Test
fun `test MicrosoftTeams message null entity response`() {
val mockHttpClient: CloseableHttpClient = EasyMock.createMock(CloseableHttpClient::class.java)
val mockHttpClient: CloseableHttpClient =
EasyMock.createMock(CloseableHttpClient::class.java)

// The DestinationHttpClient replaces a null entity with "{}".
val expectedWebhookResponse = DestinationMessageResponse(RestStatus.OK.status, "{}")

val httpResponse = mockk<CloseableHttpResponse>()
EasyMock.expect(mockHttpClient.execute(EasyMock.anyObject(HttpPost::class.java))).andReturn(httpResponse)
EasyMock.expect(mockHttpClient.execute(EasyMock.anyObject(HttpPost::class.java)))
.andReturn(httpResponse)

every { httpResponse.code } returns RestStatus.OK.status
every { httpResponse.entity } returns null
EasyMock.replay(mockHttpClient)

val httpClient = DestinationHttpClient(mockHttpClient)
val webhookDestinationTransport = WebhookDestinationTransport(httpClient)
DestinationTransportProvider.destinationTransportMap = mapOf(DestinationType.MICROSOFT_TEAMS to webhookDestinationTransport)
DestinationTransportProvider.destinationTransportMap =
mapOf(DestinationType.MICROSOFT_TEAMS to webhookDestinationTransport)

val title = "test MicrosoftTeams"
val messageText = "Message gughjhjlkh Body emoji test: :) :+1: " +
"link test: http://sample.com email test: marymajor@example.com All member callout: " +
"@All All Present member callout: @Present"
val messageText =
"Message gughjhjlkh Body emoji test: :) :+1: " +
"link test: http://sample.com email test: marymajor@example.com All member callout: " +
"@All All Present member callout: @Present"
val url = "https://abc/com"

val destination = MicrosoftTeamsDestination(url)
val message = MessageContent(title, messageText)

val actualMicrosoftTeamsResponse: DestinationMessageResponse = NotificationCoreImpl.sendMessage(destination, message, "ref")
val actualMicrosoftTeamsResponse: DestinationMessageResponse =
NotificationCoreImpl.sendMessage(destination, message, "ref")

assertEquals(expectedWebhookResponse.statusText, actualMicrosoftTeamsResponse.statusText)
assertEquals(expectedWebhookResponse.statusCode, actualMicrosoftTeamsResponse.statusCode)
}

@Test
fun `test MicrosoftTeams message empty entity response`() {
val mockHttpClient: CloseableHttpClient = EasyMock.createMock(CloseableHttpClient::class.java)
val mockHttpClient: CloseableHttpClient =
EasyMock.createMock(CloseableHttpClient::class.java)
val expectedWebhookResponse = DestinationMessageResponse(RestStatus.OK.status, "{}")

val httpResponse = mockk<CloseableHttpResponse>()
EasyMock.expect(mockHttpClient.execute(EasyMock.anyObject(HttpPost::class.java))).andReturn(httpResponse)
EasyMock.expect(mockHttpClient.execute(EasyMock.anyObject(HttpPost::class.java)))
.andReturn(httpResponse)
every { httpResponse.code } returns RestStatus.OK.status
every { httpResponse.entity } returns StringEntity("")
EasyMock.replay(mockHttpClient)

val httpClient = DestinationHttpClient(mockHttpClient)
val webhookDestinationTransport = WebhookDestinationTransport(httpClient)
DestinationTransportProvider.destinationTransportMap = mapOf(DestinationType.MICROSOFT_TEAMS to webhookDestinationTransport)
DestinationTransportProvider.destinationTransportMap =
mapOf(DestinationType.MICROSOFT_TEAMS to webhookDestinationTransport)

val title = "test MicrosoftTeams"
val messageText = "{\"Content\":\"Message gughjhjlkh Body emoji test: :) :+1: " +
"link test: http://sample.com email test: marymajor@example.com All member callout: " +
"@All All Present member callout: @Present\"}"
val messageText =
"{\"Content\":\"Message gughjhjlkh Body emoji test: :) :+1: " +
"link test: http://sample.com email test: marymajor@example.com All member callout: " +
"@All All Present member callout: @Present\"}"
val url = "https://abc/com"

val destination = MicrosoftTeamsDestination(url)
val message = MessageContent(title, messageText)

val actualMicrosoftTeamsResponse: DestinationMessageResponse = NotificationCoreImpl.sendMessage(destination, message, "ref")
val actualMicrosoftTeamsResponse: DestinationMessageResponse =
NotificationCoreImpl.sendMessage(destination, message, "ref")

assertEquals(expectedWebhookResponse.statusText, actualMicrosoftTeamsResponse.statusText)
assertEquals(expectedWebhookResponse.statusCode, actualMicrosoftTeamsResponse.statusCode)
Expand All @@ -122,47 +135,52 @@ internal class MicrosoftTeamsDestinationTests {
@Test
fun `test MicrosoftTeams message non-empty entity response`() {
val responseContent = "It worked!"
val mockHttpClient: CloseableHttpClient = EasyMock.createMock(CloseableHttpClient::class.java)
val expectedWebhookResponse = DestinationMessageResponse(RestStatus.OK.status, responseContent)
val mockHttpClient: CloseableHttpClient =
EasyMock.createMock(CloseableHttpClient::class.java)
val expectedWebhookResponse =
DestinationMessageResponse(RestStatus.OK.status, responseContent)

val httpResponse = mockk<CloseableHttpResponse>()
EasyMock.expect(mockHttpClient.execute(EasyMock.anyObject(HttpPost::class.java))).andReturn(httpResponse)
EasyMock.expect(mockHttpClient.execute(EasyMock.anyObject(HttpPost::class.java)))
.andReturn(httpResponse)
every { httpResponse.code } returns RestStatus.OK.status
every { httpResponse.entity } returns StringEntity(responseContent)
EasyMock.replay(mockHttpClient)

val httpClient = DestinationHttpClient(mockHttpClient)
val webhookDestinationTransport = WebhookDestinationTransport(httpClient)
DestinationTransportProvider.destinationTransportMap = mapOf(DestinationType.MICROSOFT_TEAMS to webhookDestinationTransport)
DestinationTransportProvider.destinationTransportMap =
mapOf(DestinationType.MICROSOFT_TEAMS to webhookDestinationTransport)

val title = "test MicrosoftTeams"
val messageText = "{\"Content\":\"Message gughjhjlkh Body emoji test: :) :+1: " +
"link test: http://sample.com email test: marymajor@example.com All member callout: " +
"@All All Present member callout: @Present\"}"
val messageText =
"{\"Content\":\"Message gughjhjlkh Body emoji test: :) :+1: " +
"link test: http://sample.com email test: marymajor@example.com All member callout: " +
"@All All Present member callout: @Present\"}"
val url = "https://abc/com"

val destination = MicrosoftTeamsDestination(url)
val message = MessageContent(title, messageText)

val actualMicrosoftTeamsResponse: DestinationMessageResponse = NotificationCoreImpl.sendMessage(destination, message, "ref")
val actualMicrosoftTeamsResponse: DestinationMessageResponse =
NotificationCoreImpl.sendMessage(destination, message, "ref")

assertEquals(expectedWebhookResponse.statusText, actualMicrosoftTeamsResponse.statusText)
assertEquals(expectedWebhookResponse.statusCode, actualMicrosoftTeamsResponse.statusCode)
}

@Test
fun `test url missing should throw IllegalArgumentException with message`() {
val exception = Assertions.assertThrows(IllegalArgumentException::class.java) {
MicrosoftTeamsDestination("")
}
val exception =
Assertions.assertThrows(IllegalArgumentException::class.java) {
MicrosoftTeamsDestination("")
}
assertEquals("url is null or empty", exception.message)
}

@Test
fun testUrlInvalidMessage() {
assertThrows<MalformedURLException> {
ChimeDestination("invalidUrl")
}
assertThrows<MalformedURLException> { ChimeDestination("invalidUrl") }
}

@ParameterizedTest
Expand All @@ -175,7 +193,8 @@ internal class MicrosoftTeamsDestinationTests {
val title = "test MicrosoftTeams"
val messageText = "line1${escapeSequence}line2"
val url = "https://abc/com"
val expectedRequestBody = """{"text":"$title\n\nline1${rawString}line2"}"""
val expectedRequestBody =
"""{"attachments":[{"contentType":"application/vnd.microsoft.card.adaptive","content":{"type":"AdaptiveCard","version":"1.2","body":[{"type":"TextBlock","text":"$title","weight":"Bolder","color":"Attention"},{"type":"TextBlock","text":"line1${rawString}line2","wrap":true}]}}]}"""
val destination = MicrosoftTeamsDestination(url)
val message = MessageContent(title, messageText)
val actualRequestBody = httpClient.buildRequestBody(destination, message)
Expand Down
Loading