-
-
Notifications
You must be signed in to change notification settings - Fork 469
Expand file tree
/
Copy pathSentrySpringIntegrationTest.kt
More file actions
531 lines (458 loc) · 17 KB
/
SentrySpringIntegrationTest.kt
File metadata and controls
531 lines (458 loc) · 17 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
package io.sentry.spring.mvc
import io.sentry.IScopes
import io.sentry.ITransportFactory
import io.sentry.Sentry
import io.sentry.SentryOptions
import io.sentry.SpanDataConvention
import io.sentry.SpanStatus
import io.sentry.checkEvent
import io.sentry.checkTransaction
import io.sentry.spring.EnableSentry
import io.sentry.spring.SentryExceptionResolver
import io.sentry.spring.SentrySpringFilter
import io.sentry.spring.SentryTaskDecorator
import io.sentry.spring.SentryUserFilter
import io.sentry.spring.SentryUserProvider
import io.sentry.spring.SpringSecuritySentryUserProvider
import io.sentry.spring.exception.SentryCaptureExceptionParameter
import io.sentry.spring.exception.SentryCaptureExceptionParameterConfiguration
import io.sentry.spring.tracing.SentrySpanClientWebRequestFilter
import io.sentry.spring.tracing.SentryTracingConfiguration
import io.sentry.spring.tracing.SentryTracingFilter
import io.sentry.spring.tracing.SentryTransaction
import io.sentry.transport.ITransport
import java.util.concurrent.Callable
import java.util.concurrent.TimeUnit
import kotlin.test.BeforeTest
import kotlin.test.Test
import org.assertj.core.api.Assertions.assertThat
import org.awaitility.Awaitility
import org.awaitility.kotlin.await
import org.junit.AfterClass
import org.junit.BeforeClass
import org.junit.runner.RunWith
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.reset
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.context.annotation.Lazy
import org.springframework.core.Ordered
import org.springframework.core.env.Environment
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.factory.PasswordEncoderFactories
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.stereotype.Service
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions
import org.springframework.web.reactive.function.client.WebClient
@RunWith(SpringRunner::class)
@SpringBootTest(classes = [App::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SentrySpringIntegrationTest {
companion object {
@BeforeClass
fun `configure awaitlity`() {
Awaitility.setDefaultTimeout(500, TimeUnit.MILLISECONDS)
}
@AfterClass
fun `reset awaitility`() {
Awaitility.reset()
}
}
@Autowired lateinit var transport: ITransport
@Autowired lateinit var someService: SomeService
@Autowired lateinit var anotherService: AnotherService
@Autowired lateinit var scopes: IScopes
@LocalServerPort var port: Int? = null
@BeforeTest
fun `reset mocks`() {
reset(transport)
}
@Test
fun `attaches request and user information to SentryEvents`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val headers = HttpHeaders()
headers["X-FORWARDED-FOR"] = listOf("169.128.0.1")
val entity = HttpEntity<Void>(headers)
restTemplate.exchange("http://localhost:$port/hello", HttpMethod.GET, entity, Void::class.java)
verify(transport)
.send(
checkEvent { event ->
assertThat(event.request).isNotNull()
assertThat(event.request!!.url).isEqualTo("http://localhost:$port/hello")
assertThat(event.user).isNotNull()
assertThat(event.user!!.username).isEqualTo("user")
assertThat(event.user!!.ipAddress).isEqualTo("169.128.0.1")
},
anyOrNull(),
)
}
@Test
fun `attaches request body to SentryEvents`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val headers = HttpHeaders().apply { this.contentType = MediaType.APPLICATION_JSON }
val httpEntity = HttpEntity("""{"body":"content"}""", headers)
restTemplate.exchange(
"http://localhost:$port/bodyAsParam",
HttpMethod.POST,
httpEntity,
Void::class.java,
)
verify(transport)
.send(
checkEvent { event ->
assertThat(event.request).isNotNull()
assertThat(event.request!!.data).isEqualTo("""{"body":"content"}""")
},
anyOrNull(),
)
}
@Test
fun `attaches request body to SentryEvents on empty ControllerMethod Params`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val headers = HttpHeaders().apply { this.contentType = MediaType.APPLICATION_JSON }
val httpEntity = HttpEntity("""{"body":"content"}""", headers)
restTemplate.exchange(
"http://localhost:$port/body",
HttpMethod.POST,
httpEntity,
Void::class.java,
)
verify(transport)
.send(
checkEvent { event ->
assertThat(event.request).isNotNull()
assertThat(event.request!!.data).isEqualTo("""{"body":"content"}""")
},
anyOrNull(),
)
}
@Test
fun `attaches first ip address if multiple addresses exist in a header`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val headers = HttpHeaders()
headers["X-FORWARDED-FOR"] = listOf("169.128.0.1, 192.168.0.1")
val entity = HttpEntity<Void>(headers)
restTemplate.exchange("http://localhost:$port/hello", HttpMethod.GET, entity, Void::class.java)
verify(transport)
.send(
checkEvent { event ->
assertThat(event.user).isNotNull()
assertThat(event.user!!.ipAddress).isEqualTo("169.128.0.1")
},
anyOrNull(),
)
}
@Test
fun `sends events for unhandled exceptions`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/throws", String::class.java)
verify(transport)
.send(
checkEvent { event ->
assertThat(event.exceptions).isNotNull().isNotEmpty
val ex = event.exceptions!!.first()
assertThat(ex.value).isEqualTo("something went wrong")
assertThat(ex.mechanism).isNotNull()
assertThat(ex.mechanism!!.isHandled).isFalse()
assertThat(ex.mechanism!!.type).isEqualTo(SentryExceptionResolver.MECHANISM_TYPE)
},
anyOrNull(),
)
}
@Test
fun `attaches transaction name to events`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/throws", String::class.java)
verify(transport)
.send(
checkEvent { event -> assertThat(event.transaction).isEqualTo("GET /throws") },
anyOrNull(),
)
}
@Test
fun `does not send events for handled exceptions`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/throws-handled", String::class.java)
verify(transport, never())
.send(checkEvent { event -> assertThat(event).isNotNull() }, anyOrNull())
}
@Test
fun `calling a method annotated with @SentryCaptureException captures exception`() {
val exception = java.lang.RuntimeException("test exception")
anotherService.aMethodThatTakesAnException(exception)
verify(transport)
.send(
checkEvent { assertThat(it.exceptions!!.first().value).isEqualTo(exception.message) },
anyOrNull(),
)
}
@Test
fun `calling a method annotated with @SentryCaptureException captures exception in later param`() {
val exception = java.lang.RuntimeException("test exception")
anotherService.aMethodThatTakesAnExceptionAsLaterParam("a", "b", exception)
verify(transport)
.send(
checkEvent { assertThat(it.exceptions!!.first().value).isEqualTo(exception.message) },
anyOrNull(),
)
}
@Test
fun `calling a method annotated with @SentryTransaction creates transaction`() {
someService.aMethod()
verify(transport)
.send(checkTransaction { assertThat(it.status).isEqualTo(SpanStatus.OK) }, anyOrNull())
}
@Test
fun `calling a method annotated with @SentryTransaction throwing exception associates Sentry event with transaction`() {
try {
someService.aMethodThrowing()
} catch (e: Exception) {
scopes.captureException(e)
}
verify(transport)
.send(
checkEvent {
assertThat(it.contexts.trace).isNotNull
assertThat(it.contexts.trace!!.operation).isEqualTo("bean")
},
anyOrNull(),
)
}
@Test
fun `calling a method annotated with @SentryTransaction, where an inner span is created within transaction, throwing exception associates Sentry event with inner span`() {
try {
someService.aMethodWithInnerSpanThrowing()
} catch (e: Exception) {
scopes.captureException(e)
}
verify(transport)
.send(
checkEvent {
assertThat(it.contexts.trace).isNotNull
assertThat(it.contexts.trace!!.operation).isEqualTo("child-op")
},
anyOrNull(),
)
}
@Test
fun `sets user on transaction`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/hello", String::class.java)
// transactions are sent after response is returned
await.untilAsserted {
verify(transport)
.send(
checkTransaction { transaction ->
assertThat(transaction.user).isNotNull()
assertThat(transaction.user!!.username).isEqualTo("user")
},
anyOrNull(),
)
}
}
@Test
fun `scope is applied to events triggered in async methods`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/callable", String::class.java)
await.untilAsserted {
verify(transport)
.send(
checkEvent { event ->
assertThat(event.message!!.formatted)
.isEqualTo("this message should be in the scope of the request")
assertThat(event.request).isNotNull()
assertThat(event.request!!.url).isEqualTo("http://localhost:$port/callable")
},
anyOrNull(),
)
}
}
@Test
fun `WebClient http request execution is turned into a span`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/webClient", String::class.java)
// transactions are sent after response is returned
await.untilAsserted {
verify(transport)
.send(
checkTransaction { transaction ->
assertThat(transaction.spans).hasSize(1)
val span = transaction.spans.first()
assertThat(span.op).isEqualTo("http.client")
assertThat(span.description).isEqualTo("GET http://localhost:$port/hello")
assertThat(span.data?.get(SpanDataConvention.HTTP_STATUS_CODE_KEY)).isEqualTo(200)
assertThat(span.status).isEqualTo(SpanStatus.OK)
},
anyOrNull(),
)
}
}
}
@SpringBootApplication
@EnableSentry(
dsn = "http://key@localhost/proj",
sendDefaultPii = true,
maxRequestBodySize = SentryOptions.RequestSize.MEDIUM,
)
@Import(SentryTracingConfiguration::class, SentryCaptureExceptionParameterConfiguration::class)
open class App {
@Bean
open fun mockTransportFactory(transport: ITransport): ITransportFactory {
val factory = mock<ITransportFactory>()
whenever(factory.create(any(), any())).thenReturn(transport)
return factory
}
@Bean open fun mockTransport() = mock<ITransport>()
@Bean open fun tracesSamplerCallback() = SentryOptions.TracesSamplerCallback { 1.0 }
@Bean
open fun springSecuritySentryUserProvider(sentryOptions: SentryOptions) =
SpringSecuritySentryUserProvider(sentryOptions)
@Bean
open fun sentryUserFilter(scopes: IScopes, @Lazy sentryUserProviders: List<SentryUserProvider>) =
FilterRegistrationBean<SentryUserFilter>().apply {
this.filter = SentryUserFilter(scopes, sentryUserProviders)
this.order = Ordered.LOWEST_PRECEDENCE
}
@Bean
open fun sentrySpringFilter(scopes: IScopes) =
FilterRegistrationBean<SentrySpringFilter>().apply {
this.filter = SentrySpringFilter(scopes)
this.order = Ordered.HIGHEST_PRECEDENCE
}
@Bean
open fun sentryTracingFilter(scopes: IScopes) =
FilterRegistrationBean<SentryTracingFilter>().apply {
this.filter = SentryTracingFilter(scopes)
this.order = Ordered.HIGHEST_PRECEDENCE + 1 // must run after SentrySpringFilter
}
@Bean open fun sentryTaskDecorator() = SentryTaskDecorator()
@Bean
open fun webClient(scopes: IScopes): WebClient {
return WebClient.builder()
.filter(ExchangeFilterFunctions.basicAuthentication("user", "password"))
.filter(SentrySpanClientWebRequestFilter(scopes))
.build()
}
}
@Service
open class AnotherService {
@SentryCaptureExceptionParameter open fun aMethodThatTakesAnException(e: Exception) {}
@SentryCaptureExceptionParameter
open fun aMethodThatTakesAnExceptionAsLaterParam(a: String, b: String, e: Exception) {}
}
@Service
open class SomeService {
@SentryTransaction(operation = "bean")
open fun aMethod() {
Thread.sleep(100)
}
@SentryTransaction(operation = "bean")
open fun aMethodThrowing() {
throw RuntimeException("oops")
}
@SentryTransaction(operation = "bean")
open fun aMethodWithInnerSpanThrowing() {
val span = Sentry.getSpan()!!.startChild("child-op")
try {
throw RuntimeException("oops")
} catch (e: Exception) {
span.status = SpanStatus.INTERNAL_ERROR
span.throwable = e
throw e
} finally {
span.finish()
}
}
}
@RestController
class HelloController(private val webClient: WebClient, private val env: Environment) {
@GetMapping("/hello")
fun hello(): String {
Sentry.captureMessage("hello")
return "hello"
}
@PostMapping("/body")
fun body() {
Sentry.captureMessage("body")
}
@PostMapping("/bodyAsParam")
fun bodyWithReadingBodyInController(@RequestBody body: String) {
Sentry.captureMessage("body")
}
@GetMapping("/throws")
fun throws() {
throw RuntimeException("something went wrong")
}
@GetMapping("/throws-handled")
fun throwsHandled() {
throw CustomException("handled exception")
}
@GetMapping("/callable")
fun callable(): Callable<String> {
return Callable {
Sentry.captureMessage("this message should be in the scope of the request")
"from callable"
}
}
@GetMapping("/webClient")
fun webClient(): String? {
return webClient
.get()
.uri("http://localhost:${env.getProperty("local.server.port")}/hello")
.retrieve()
.bodyToMono(String::class.java)
.block()
}
}
class CustomException(message: String) : RuntimeException(message)
@ControllerAdvice
class ExceptionHandlers {
@ExceptionHandler(CustomException::class)
fun handle(e: CustomException) = ResponseEntity.badRequest().build<Void>()
}
@Configuration
open class SecurityConfiguration : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic()
}
@Bean
override fun userDetailsService(): UserDetailsService {
val encoder: PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
val user: UserDetails =
User.builder()
.passwordEncoder { rawPassword -> encoder.encode(rawPassword) }
.username("user")
.password("password")
.roles("USER")
.build()
return InMemoryUserDetailsManager(user)
}
}