-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathToolsKtTest.kt
More file actions
1108 lines (919 loc) · 43.8 KB
/
Copy pathToolsKtTest.kt
File metadata and controls
1108 lines (919 loc) · 43.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package net.portswigger.mcp.tools
import burp.api.montoya.MontoyaApi
import burp.api.montoya.burpsuite.TaskExecutionEngine
import burp.api.montoya.collaborator.*
import burp.api.montoya.core.BurpSuiteEdition
import burp.api.montoya.core.ByteArray
import burp.api.montoya.http.Http
import burp.api.montoya.http.HttpMode
import burp.api.montoya.http.HttpProtocol
import burp.api.montoya.http.message.HttpHeader
import burp.api.montoya.http.message.requests.HttpRequest
import burp.api.montoya.logging.Logging
import burp.api.montoya.persistence.PersistedObject
import burp.api.montoya.proxy.Proxy
import burp.api.montoya.proxy.ProxyHttpRequestResponse
import burp.api.montoya.utilities.Base64Utils
import burp.api.montoya.utilities.RandomUtils
import burp.api.montoya.utilities.URLUtils
import burp.api.montoya.utilities.Utilities
import io.mockk.*
import java.net.InetAddress
import java.time.ZonedDateTime
import java.util.Optional
import io.modelcontextprotocol.kotlin.sdk.CallToolResultBase
import io.modelcontextprotocol.kotlin.sdk.TextContent
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToJsonElement
import net.portswigger.mcp.KtorServerManager
import net.portswigger.mcp.ServerState
import net.portswigger.mcp.TestSseMcpClient
import net.portswigger.mcp.config.McpConfig
import net.portswigger.mcp.schema.HttpRequestResponse
import net.portswigger.mcp.schema.toSerializableForm
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.net.ServerSocket
import javax.swing.JTextArea
class ToolsKtTest {
private val client = TestSseMcpClient()
private val api = mockk<MontoyaApi>(relaxed = true)
private val serverManager = KtorServerManager(api)
private val testPort = findAvailablePort()
private var serverStarted = false
private val config: McpConfig
private val mockHeaders = mutableListOf<HttpHeader>()
private val capturedRequest = slot<HttpRequest>()
init {
val persistedObject = mockk<PersistedObject>().apply {
every { getBoolean("enabled") } returns true
every { getBoolean("configEditingTooling") } returns true
every { getBoolean("requireHttpRequestApproval") } returns false
every { getBoolean("requireHistoryAccessApproval") } returns false
every { getBoolean("_alwaysAllowHttpHistory") } returns false
every { getBoolean("_alwaysAllowWebSocketHistory") } returns false
every { getString("host") } returns "127.0.0.1"
every { getString("_autoApproveTargets") } returns ""
every { getInteger("port") } returns testPort
every { setBoolean(any(), any()) } returns Unit
every { setString(any(), any()) } returns Unit
every { setInteger(any(), any()) } returns Unit
}
val mockLogging = mockk<Logging>().apply {
every { logToError(any<String>()) } returns Unit
every { logToOutput(any<String>()) } returns Unit
}
config = McpConfig(persistedObject, mockLogging)
mockkStatic(HttpHeader::class)
mockkStatic(burp.api.montoya.http.HttpService::class)
mockkStatic(HttpRequest::class)
}
private fun CallToolResultBase?.expectTextContent(
expected: String? = null,
): String {
assertNotNull(this, "Tool result cannot be null")
val result = this!!
val content = result.content
assertNotNull(content, "Tool result content cannot be null")
val nonNullContent = content
assertEquals(1, nonNullContent.size, "Expected exactly one content element")
val textContent = nonNullContent.firstOrNull() as? TextContent
assertNotNull(textContent, "Expected content to be TextContent")
val text = textContent!!.text
assertNotNull(text, "Text content cannot be null")
if (expected != null) {
assertEquals(expected, text, "Text content doesn't match expected value")
}
return text!!
}
private fun setupHttpHeaderMocks() {
every { HttpHeader.httpHeader(any<String>(), any<String>()) } answers {
val name = firstArg<String>()
val value = secondArg<String>()
mockk<HttpHeader>().also {
every { it.name() } returns name
every { it.value() } returns value
mockHeaders.add(it)
}
}
every { burp.api.montoya.http.HttpService.httpService(any(), any(), any()) } answers {
val host = firstArg<String>()
val port = secondArg<Int>()
val secure = thirdArg<Boolean>()
mockk<burp.api.montoya.http.HttpService>().also {
every { it.host() } returns host
every { it.port() } returns port
every { it.secure() } returns secure
}
}
}
@BeforeEach
fun setup() {
setupHttpHeaderMocks()
serverManager.start(config) { state ->
if (state is ServerState.Running) serverStarted = true
}
runBlocking {
var attempts = 0
while (!serverStarted && attempts < 30) {
delay(100)
attempts++
}
if (!serverStarted) throw IllegalStateException("Server failed to start after timeout")
client.connectToServer("http://127.0.0.1:${testPort}")
assertNotNull(client.ping(), "Ping should return a result")
}
}
private fun findAvailablePort() = ServerSocket(0).use { it.localPort }
@AfterEach
fun tearDown() {
runBlocking { if (client.isConnected()) client.close() }
serverManager.stop {}
}
@Nested
inner class HttpToolsTests {
@Test
fun `http1 line endings should be normalized`() {
val httpService = mockk<Http>()
val httpResponse = mockk<burp.api.montoya.http.message.HttpRequestResponse>()
val contentSlot = slot<String>()
every { HttpRequest.httpRequest(any(), capture(contentSlot)) } answers {
val content = secondArg<String>()
mockk<HttpRequest>().also {
every { it.toString() } returns content
}
}
every { api.http() } returns httpService
every { httpResponse.toString() } returns "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nResponse body"
every { httpResponse.hasResponse() } returns true
every { httpService.sendRequest(capture(capturedRequest)) } returns httpResponse
runBlocking {
val result = client.callTool(
"send_http1_request", mapOf(
"content" to "GET /foo HTTP/1.1\nHost: example.com\n\n",
"targetHostname" to "example.com",
"targetPort" to 80,
"usesHttps" to false
)
)
delay(100)
val text = result.expectTextContent()
assertFalse(text.contains("Error"),
"Expected success response but got error: $text")
}
verify(exactly = 1) { httpService.sendRequest(any<HttpRequest>()) }
verify(exactly = 1) { api.siteMap().add(httpResponse) }
assertEquals("GET /foo HTTP/1.1\r\nHost: example.com\r\n\r\n", capturedRequest.captured.toString(), "Request body should match")
}
@Test
fun `http1 request should handle no response`() {
val httpService = mockk<Http>()
val contentSlot = slot<String>()
every { HttpRequest.httpRequest(any(), capture(contentSlot)) } answers {
val content = secondArg<String>()
mockk<HttpRequest>().also {
every { it.toString() } returns content
}
}
every { api.http() } returns httpService
every { httpService.sendRequest(any()) } returns null
runBlocking {
val result = client.callTool(
"send_http1_request", mapOf(
"content" to "GET /foo HTTP/1.1\r\nHost: example.com\r\n\r\n",
"targetHostname" to "example.com",
"targetPort" to 80,
"usesHttps" to false
)
)
delay(100)
result.expectTextContent("<no response>")
}
verify(exactly = 0) { api.siteMap().add(any<burp.api.montoya.http.message.HttpRequestResponse>()) }
}
@Test
fun `http2 request should be formatted properly`() {
val httpService = mockk<Http>()
val httpResponse = mockk<burp.api.montoya.http.message.HttpRequestResponse>()
val httpRequest = mockk<HttpRequest>()
val requestSlot = slot<HttpRequest>()
val headersSlot = slot<List<HttpHeader>>()
val bodySlot = slot<String>()
every { HttpRequest.http2Request(any(), capture(headersSlot), capture(bodySlot)) } returns httpRequest
every { httpResponse.toString() } returns "HTTP/2 200 OK\r\nContent-Type: text/plain\r\n\r\nResponse body"
every { httpResponse.hasResponse() } returns true
every { api.http() } returns httpService
every { httpService.sendRequest(capture(requestSlot), HttpMode.HTTP_2) } returns httpResponse
val pseudoHeaders = mapOf(
"authority" to "example.com", "scheme" to "https", "method" to "GET", ":path" to "/test"
)
val headers = mapOf(
"User-Agent" to "Test Agent", "Accept" to "*/*"
)
val requestBody = "Test body"
runBlocking {
val result = client.callTool(
"send_http2_request", mapOf(
"pseudoHeaders" to Json.encodeToJsonElement(pseudoHeaders),
"headers" to Json.encodeToJsonElement(headers),
"requestBody" to requestBody,
"targetHostname" to "example.com",
"targetPort" to 443,
"usesHttps" to true
)
)
delay(100)
val text = result.expectTextContent()
assertFalse(text.contains("Error"),
"Expected success response but got error: $text")
}
verify(exactly = 1) { HttpRequest.http2Request(any(), any(), any<String>()) }
verify(exactly = 1) { api.siteMap().add(httpResponse) }
assertEquals("Test body", bodySlot.captured, "Request body should match")
val pseudoHeaderList = headersSlot.captured.filter { it.name().startsWith(":") }
val normalHeaderList = headersSlot.captured.filter { !it.name().startsWith(":") }
assertTrue(pseudoHeaderList.any { it.name() == ":scheme" && it.value() == "https" })
assertTrue(pseudoHeaderList.any { it.name() == ":method" && it.value() == "GET" })
assertTrue(pseudoHeaderList.any { it.name() == ":path" && it.value() == "/test" })
assertTrue(pseudoHeaderList.any { it.name() == ":authority" && it.value() == "example.com" })
assertTrue(normalHeaderList.any { it.name() == "user-agent" && it.value() == "Test Agent" })
assertTrue(normalHeaderList.any { it.name() == "accept" && it.value() == "*/*" })
}
@Test
fun `http2 request should handle null response`() {
val httpService = mockk<Http>()
val httpRequest = mockk<HttpRequest>()
every { HttpRequest.http2Request(any(), any(), any<String>()) } returns httpRequest
every { api.http() } returns httpService
every { httpService.sendRequest(any(), HttpMode.HTTP_2) } returns null
val pseudoHeaders = mapOf("method" to "GET", "path" to "/test")
val headers = mapOf("User-Agent" to "Test Agent")
runBlocking {
val result = client.callTool(
"send_http2_request", mapOf(
"pseudoHeaders" to Json.encodeToJsonElement(pseudoHeaders),
"headers" to Json.encodeToJsonElement(headers),
"requestBody" to "",
"targetHostname" to "example.com",
"targetPort" to 443,
"usesHttps" to true
)
)
delay(100)
result.expectTextContent("<no response>")
}
verify(exactly = 0) { api.siteMap().add(any<burp.api.montoya.http.message.HttpRequestResponse>()) }
}
@Test
fun `http2 should not add to site map when response is missing`() {
val httpService = mockk<Http>()
val httpRequest = mockk<HttpRequest>()
val httpResponse = mockk<burp.api.montoya.http.message.HttpRequestResponse>()
every { HttpRequest.http2Request(any(), any(), any<String>()) } returns httpRequest
every { api.http() } returns httpService
every { httpService.sendRequest(any(), HttpMode.HTTP_2) } returns httpResponse
every { httpResponse.hasResponse() } returns false
every { httpResponse.toString() } returns "HttpRequestResponse{httpRequest=..., httpResponse=null}"
val pseudoHeaders = mapOf("method" to "GET", "path" to "/test", "authority" to "example.com", "scheme" to "https")
val headers = mapOf("User-Agent" to "Test Agent")
runBlocking {
val result = client.callTool(
"send_http2_request", mapOf(
"pseudoHeaders" to Json.encodeToJsonElement(pseudoHeaders),
"headers" to Json.encodeToJsonElement(headers),
"requestBody" to "",
"targetHostname" to "example.com",
"targetPort" to 443,
"usesHttps" to true
)
)
delay(100)
assertNotNull(result)
}
verify(exactly = 0) { api.siteMap().add(any<burp.api.montoya.http.message.HttpRequestResponse>()) }
}
@Test
fun `create repeater tab should normalize line endings`() {
val repeater = mockk<burp.api.montoya.repeater.Repeater>(relaxed = true)
val contentSlot = slot<String>()
every { HttpRequest.httpRequest(any(), capture(contentSlot)) } answers {
val captured = secondArg<String>()
mockk<HttpRequest>().also {
every { it.toString() } returns captured
}
}
every { api.repeater() } returns repeater
runBlocking {
val result = client.callTool(
"create_repeater_tab", mapOf(
"tabName" to "lf-only",
"content" to "GET /foo HTTP/1.1\nHost: example.com\n\n",
"targetHostname" to "example.com",
"targetPort" to 80,
"usesHttps" to false
)
)
delay(100)
assertNotNull(result)
}
verify(exactly = 1) { repeater.sendToRepeater(any<HttpRequest>(), "lf-only") }
assertEquals("GET /foo HTTP/1.1\r\nHost: example.com\r\n\r\n", contentSlot.captured, "LF should be normalized to CRLF before sending to Repeater")
}
@Test
fun `http2 pseudo headers should be ordered correctly`() {
val httpService = mockk<Http>()
val httpResponse = mockk<burp.api.montoya.http.message.HttpRequestResponse>()
val httpRequest = mockk<HttpRequest>()
val headersSlot = slot<List<HttpHeader>>()
every { HttpRequest.http2Request(any(), capture(headersSlot), any<String>()) } returns httpRequest
every { httpResponse.toString() } returns "HTTP/2 200 OK"
every { api.http() } returns httpService
every { httpService.sendRequest(any(), HttpMode.HTTP_2) } returns httpResponse
val pseudoHeaders = mapOf(
"path" to "/test",
":authority" to "example.com",
"method" to "GET",
"scheme" to "https"
)
runBlocking {
val result = client.callTool(
"send_http2_request", mapOf(
"pseudoHeaders" to Json.encodeToJsonElement(pseudoHeaders),
"headers" to Json.encodeToJsonElement(emptyMap<String, String>()),
"requestBody" to "",
"targetHostname" to "example.com",
"targetPort" to 443,
"usesHttps" to true
)
)
delay(100)
assertNotNull(result)
}
val pseudoHeaderNames = headersSlot.captured
.filter { it.name().startsWith(":") }
.map { it.name() }
val expectedOrder = listOf(":scheme", ":method", ":path", ":authority")
for (i in 0 until minOf(expectedOrder.size, pseudoHeaderNames.size)) {
assertEquals(expectedOrder[i], pseudoHeaderNames[i],
"Pseudo headers should follow the order: scheme, method, path, authority")
}
}
}
@Nested
inner class UtilityToolsTests {
@Test
fun `url encode should work properly`() {
val urlUtils = mockk<URLUtils>()
val utilities = mockk<Utilities>()
every { api.utilities() } returns utilities
every { utilities.urlUtils() } returns urlUtils
every { urlUtils.encode(any<String>()) } returns "test+string+with+spaces"
runBlocking {
val result = client.callTool(
"url_encode", mapOf(
"content" to "test string with spaces"
)
)
delay(100)
result.expectTextContent("test+string+with+spaces")
}
verify(exactly = 1) { urlUtils.encode(any<String>()) }
}
@Test
fun `url decode should work properly`() {
val urlUtils = mockk<URLUtils>()
val utilities = mockk<Utilities>()
every { api.utilities() } returns utilities
every { utilities.urlUtils() } returns urlUtils
every { urlUtils.decode(any<String>()) } returns "test string with spaces"
runBlocking {
val result = client.callTool(
"url_decode", mapOf(
"content" to "test+string+with+spaces"
)
)
delay(100)
result.expectTextContent("test string with spaces")
}
verify(exactly = 1) { urlUtils.decode(any<String>()) }
}
@Test
fun `base64 encode should work properly`() {
val base64Utils = mockk<Base64Utils>()
val utilities = mockk<Utilities>()
every { api.utilities() } returns utilities
every { utilities.base64Utils() } returns base64Utils
every { base64Utils.encodeToString(any<String>()) } returns "dGVzdCBzdHJpbmc="
runBlocking {
val result = client.callTool(
"base64_encode", mapOf(
"content" to "test string"
)
)
delay(100)
result.expectTextContent("dGVzdCBzdHJpbmc=")
}
verify(exactly = 1) { base64Utils.encodeToString(any<String>()) }
}
@Test
fun `base64 decode should work properly`() {
val base64Utils = mockk<Base64Utils>()
val utilities = mockk<Utilities>()
val burpByteArray = mockk<ByteArray>()
every { api.utilities() } returns utilities
every { utilities.base64Utils() } returns base64Utils
every { base64Utils.decode(any<String>()) } returns burpByteArray
every { burpByteArray.toString() } returns "test string"
runBlocking {
val result = client.callTool(
"base64_decode", mapOf(
"content" to "dGVzdCBzdHJpbmc="
)
)
delay(100)
result.expectTextContent("test string")
}
verify(exactly = 1) { base64Utils.decode(any<String>()) }
}
@Test
fun `generate random string should work properly`() {
val randomUtils = mockk<RandomUtils>()
val utilities = mockk<Utilities>()
every { api.utilities() } returns utilities
every { utilities.randomUtils() } returns randomUtils
every { randomUtils.randomString(any<Int>(), any<String>()) } returns "1a2b3c1a2b"
runBlocking {
val result = client.callTool(
"generate_random_string", mapOf(
"length" to 10,
"characterSet" to "abc123"
)
)
delay(100)
result.expectTextContent("1a2b3c1a2b")
}
verify(exactly = 1) { randomUtils.randomString(any<Int>(), any<String>()) }
}
}
@Nested
inner class ConfigurationToolsTests {
@Test
fun `set task execution engine state should work properly`() {
val taskExecutionEngine = mockk<TaskExecutionEngine>()
val burpSuite = mockk<burp.api.montoya.burpsuite.BurpSuite>()
every { api.burpSuite() } returns burpSuite
every { burpSuite.taskExecutionEngine() } returns taskExecutionEngine
every { taskExecutionEngine.state = any() } just runs
runBlocking {
val result = client.callTool(
"set_task_execution_engine_state", mapOf(
"running" to true
)
)
delay(100)
result.expectTextContent("Task execution engine is now running")
}
verify(exactly = 1) { taskExecutionEngine.state = TaskExecutionEngine.TaskExecutionEngineState.RUNNING }
clearMocks(taskExecutionEngine, answers = false)
runBlocking {
val result = client.callTool(
"set_task_execution_engine_state", mapOf(
"running" to false
)
)
delay(100)
result.expectTextContent("Task execution engine is now paused")
}
verify(exactly = 1) { taskExecutionEngine.state = TaskExecutionEngine.TaskExecutionEngineState.PAUSED }
}
@Test
fun `set proxy intercept state should work properly`() {
val proxy = mockk<Proxy>()
every { api.proxy() } returns proxy
every { proxy.enableIntercept() } just runs
every { proxy.disableIntercept() } just runs
runBlocking {
val result = client.callTool(
"set_proxy_intercept_state", mapOf(
"intercepting" to true
)
)
delay(100)
result.expectTextContent("Intercept has been enabled")
}
verify(exactly = 1) { proxy.enableIntercept() }
clearMocks(proxy, answers = false)
runBlocking {
val result = client.callTool(
"set_proxy_intercept_state", mapOf(
"intercepting" to false
)
)
delay(100)
result.expectTextContent("Intercept has been disabled")
}
verify(exactly = 1) { proxy.disableIntercept() }
}
@Test
fun `config editing tools should respect config settings`() {
val burpSuite = mockk<burp.api.montoya.burpsuite.BurpSuite>()
every { api.burpSuite() } returns burpSuite
every { burpSuite.importProjectOptionsFromJson(any()) } just runs
every { api.logging().logToOutput(any()) } just runs
runBlocking {
val result = client.callTool(
"set_project_options", mapOf(
"json" to "{\"test\": true}"
)
)
delay(100)
result.expectTextContent("Project configuration has been applied")
}
verify(exactly = 1) { burpSuite.importProjectOptionsFromJson(any()) }
clearMocks(burpSuite, answers = false)
every { config.configEditingTooling } returns false
runBlocking {
val result = client.callTool(
"set_project_options", mapOf(
"json" to "{\"test\": true}"
)
)
delay(100)
result.expectTextContent("User has disabled configuration editing. They can enable it in the MCP tab in Burp by selecting 'Enable tools that can edit your config'")
}
verify(exactly = 0) { burpSuite.importProjectOptionsFromJson(any()) }
}
}
@Nested
inner class EditorTests {
@Test
fun `get active editor contents should handle no editor`() {
mockkStatic("net.portswigger.mcp.tools.ToolsKt")
every { getActiveEditor(api) } returns null
runBlocking {
val result = client.callTool("get_active_editor_contents", emptyMap())
delay(100)
result.expectTextContent("<No active editor>")
}
}
@Test
fun `get active editor contents should return text`() {
mockkStatic("net.portswigger.mcp.tools.ToolsKt")
val textArea = mockk<JTextArea>()
every { getActiveEditor(api) } returns textArea
every { textArea.text } returns "Editor content"
runBlocking {
val result = client.callTool("get_active_editor_contents", emptyMap())
delay(100)
result.expectTextContent("Editor content")
}
}
@Test
fun `set active editor contents should handle no editor`() {
mockkStatic("net.portswigger.mcp.tools.ToolsKt")
every { getActiveEditor(api) } returns null
runBlocking {
val result = client.callTool(
"set_active_editor_contents", mapOf(
"text" to "New content"
)
)
delay(100)
result.expectTextContent("<No active editor>")
}
}
@Test
fun `set active editor contents should handle non-editable editor`() {
mockkStatic("net.portswigger.mcp.tools.ToolsKt")
val textArea = mockk<JTextArea>()
every { getActiveEditor(api) } returns textArea
every { textArea.isEditable } returns false
runBlocking {
val result = client.callTool(
"set_active_editor_contents", mapOf(
"text" to "New content"
)
)
delay(100)
result.expectTextContent("<Current editor is not editable>")
}
}
@Test
fun `set active editor contents should update text`() {
mockkStatic("net.portswigger.mcp.tools.ToolsKt")
val textArea = mockk<JTextArea>()
every { getActiveEditor(api) } returns textArea
every { textArea.isEditable } returns true
every { textArea.text = any() } just runs
runBlocking {
val result = client.callTool(
"set_active_editor_contents", mapOf(
"text" to "New content"
)
)
delay(100)
result.expectTextContent("Editor text has been set")
}
verify(exactly = 1) { textArea.text = "New content" }
}
}
@Nested
inner class PaginatedToolsTests {
@Test
fun `get proxy history should paginate properly`() {
val proxy = mockk<Proxy>()
val proxyHistory = listOf(
mockk<ProxyHttpRequestResponse>(),
mockk<ProxyHttpRequestResponse>(),
mockk<ProxyHttpRequestResponse>()
)
every { api.proxy() } returns proxy
every { proxy.history() } returns proxyHistory
mockkStatic("net.portswigger.mcp.schema.SerializationKt")
every { proxyHistory[0].toSerializableForm() } returns HttpRequestResponse(
request = "GET /item1 HTTP/1.1",
response = "HTTP/1.1 200 OK",
notes = "Item 1 notes"
)
every { proxyHistory[1].toSerializableForm() } returns HttpRequestResponse(
request = "GET /item2 HTTP/1.1",
response = "HTTP/1.1 200 OK",
notes = "Item 2 notes"
)
every { proxyHistory[2].toSerializableForm() } returns HttpRequestResponse(
request = "GET /item3 HTTP/1.1",
response = "HTTP/1.1 200 OK",
notes = "Item 3 notes"
)
runBlocking {
val result1 = client.callTool(
"get_proxy_http_history", mapOf(
"count" to 2,
"offset" to 0
)
)
delay(100)
val text1 = result1.expectTextContent()
assertTrue(text1.contains("GET /item1"))
assertTrue(text1.contains("GET /item2"))
assertFalse(text1.contains("GET /item3"))
val result2 = client.callTool(
"get_proxy_http_history", mapOf(
"count" to 2,
"offset" to 2
)
)
delay(100)
val text2 = result2.expectTextContent()
assertTrue(text2.contains("GET /item3"))
val result3 = client.callTool(
"get_proxy_http_history", mapOf(
"count" to 2,
"offset" to 3
)
)
delay(100)
assertEquals("Reached end of items", result3.expectTextContent())
}
}
}
@Nested
inner class CollaboratorToolsTests {
private val collaborator = mockk<Collaborator>()
private val collaboratorClient = mockk<CollaboratorClient>()
private val collaboratorServer = mockk<CollaboratorServer>()
@BeforeEach
fun setupCollaborator() {
mockkStatic(InteractionFilter::class)
val burpSuite = mockk<burp.api.montoya.burpsuite.BurpSuite>()
val version = mockk<burp.api.montoya.core.Version>()
every { api.burpSuite() } returns burpSuite
every { burpSuite.version() } returns version
every { version.edition() } returns BurpSuiteEdition.PROFESSIONAL
every { burpSuite.taskExecutionEngine() } returns mockk(relaxed = true)
every { burpSuite.exportProjectOptionsAsJson() } returns "{}"
every { burpSuite.exportUserOptionsAsJson() } returns "{}"
every { burpSuite.importProjectOptionsFromJson(any()) } just runs
every { burpSuite.importUserOptionsFromJson(any()) } just runs
every { api.collaborator() } returns collaborator
every { collaborator.createClient() } returns collaboratorClient
every { collaboratorClient.server() } returns collaboratorServer
every { collaboratorServer.address() } returns "burpcollaborator.net"
serverManager.stop {}
serverStarted = false
serverManager.start(config) { state ->
if (state is ServerState.Running) serverStarted = true
}
runBlocking {
var attempts = 0
while (!serverStarted && attempts < 30) {
delay(100)
attempts++
}
if (!serverStarted) throw IllegalStateException("Server failed to start after timeout")
client.connectToServer("http://127.0.0.1:${testPort}")
}
}
@AfterEach
fun cleanupCollaborator() {
unmockkStatic(InteractionFilter::class)
}
private fun mockInteraction(
id: String,
type: InteractionType,
clientIp: String = "10.0.0.1",
clientPort: Int = 54321,
customData: String? = null,
dnsDetails: DnsDetails? = null,
httpDetails: HttpDetails? = null,
smtpDetails: SmtpDetails? = null
): Interaction {
val interactionId = mockk<InteractionId>()
every { interactionId.toString() } returns id
return mockk<Interaction>().also {
every { it.id() } returns interactionId
every { it.type() } returns type
every { it.timeStamp() } returns ZonedDateTime.parse("2025-01-01T12:00:00Z")
every { it.clientIp() } returns InetAddress.getByName(clientIp)
every { it.clientPort() } returns clientPort
every { it.customData() } returns Optional.ofNullable(customData)
every { it.dnsDetails() } returns Optional.ofNullable(dnsDetails)
every { it.httpDetails() } returns Optional.ofNullable(httpDetails)
every { it.smtpDetails() } returns Optional.ofNullable(smtpDetails)
}
}
@Test
fun `generate payload should return payload and server info`() {
val payload = mockk<CollaboratorPayload>()
val payloadId = mockk<InteractionId>()
every { payload.toString() } returns "abc123.burpcollaborator.net"
every { payload.id() } returns payloadId
every { payloadId.toString() } returns "abc123"
every { collaboratorClient.generatePayload() } returns payload
runBlocking {
val result = client.callTool("generate_collaborator_payload", emptyMap())
delay(100)
result.expectTextContent(
"Payload: abc123.burpcollaborator.net\n" +
"Payload ID: abc123\n" +
"Collaborator server: burpcollaborator.net"
)
}
verify(exactly = 1) { collaboratorClient.generatePayload() }
}
@Test
fun `generate payload with custom data should pass custom data`() {
val payload = mockk<CollaboratorPayload>()
val payloadId = mockk<InteractionId>()
every { payload.toString() } returns "custom123.burpcollaborator.net"
every { payload.id() } returns payloadId
every { payloadId.toString() } returns "custom123"
every { collaboratorClient.generatePayload(any<String>()) } returns payload
runBlocking {
val result = client.callTool(
"generate_collaborator_payload", mapOf(
"customData" to "mydata"
)
)
delay(100)
result.expectTextContent(
"Payload: custom123.burpcollaborator.net\n" +
"Payload ID: custom123\n" +
"Collaborator server: burpcollaborator.net"
)
}
verify(exactly = 1) { collaboratorClient.generatePayload("mydata") }
}
@Test
fun `get interactions should return dns interaction details`() {
val dnsDetails = mockk<DnsDetails>().also {
every { it.queryType() } returns DnsQueryType.A
}
val interaction = mockInteraction("int-001", InteractionType.DNS, dnsDetails = dnsDetails)
every { collaboratorClient.getAllInteractions() } returns listOf(interaction)
runBlocking {
val result = client.callTool("get_collaborator_interactions", emptyMap())
delay(100)
val text = result.expectTextContent()
assertTrue(text.contains("\"id\":\"int-001\""))
assertTrue(text.contains("\"type\":\"DNS\""))
assertTrue(text.contains("\"queryType\":\"A\""))
assertTrue(text.contains("\"clientIp\":\"10.0.0.1\""))
}
verify(exactly = 1) { collaboratorClient.getAllInteractions() }
}
@Test
fun `get interactions should return http interaction details`() {
val mockRequest = mockk<burp.api.montoya.http.message.requests.HttpRequest>()
every { mockRequest.toString() } returns "GET / HTTP/1.1"
val mockResponse = mockk<burp.api.montoya.http.message.responses.HttpResponse>()
every { mockResponse.toString() } returns "HTTP/1.1 200 OK"
val mockRequestResponse = mockk<burp.api.montoya.http.message.HttpRequestResponse>()
every { mockRequestResponse.request() } returns mockRequest
every { mockRequestResponse.response() } returns mockResponse
val httpDetails = mockk<HttpDetails>().also {
every { it.protocol() } returns HttpProtocol.HTTP
every { it.requestResponse() } returns mockRequestResponse
}
val interaction = mockInteraction("int-002", InteractionType.HTTP, httpDetails = httpDetails)
every { collaboratorClient.getAllInteractions() } returns listOf(interaction)
runBlocking {
val result = client.callTool("get_collaborator_interactions", emptyMap())
delay(100)
val text = result.expectTextContent()
assertTrue(text.contains("\"type\":\"HTTP\""))