-
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathSentrySpringIntegrationTest.kt
More file actions
353 lines (299 loc) · 10.8 KB
/
SentrySpringIntegrationTest.kt
File metadata and controls
353 lines (299 loc) · 10.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
package io.sentry.spring.boot4.it
import io.sentry.DefaultSpanFactory
import io.sentry.IScopes
import io.sentry.ITransportFactory
import io.sentry.Sentry
import io.sentry.SentryOpenTelemetryMode
import io.sentry.SentryOptions
import io.sentry.checkEvent
import io.sentry.checkTransaction
import io.sentry.spring7.tracing.SentrySpan
import io.sentry.transport.ITransport
import kotlin.test.BeforeTest
import kotlin.test.Test
import org.assertj.core.api.Assertions.assertThat
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.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.resttestclient.TestRestTemplate
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.server.LocalServerPort
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.crypto.factory.PasswordEncoderFactories
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.web.SecurityFilterChain
import org.springframework.stereotype.Service
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean
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
@RunWith(SpringRunner::class)
@SpringBootTest(
classes = [App::class],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties =
[
"sentry.dsn=http://key@localhost/proj",
"sentry.send-default-pii=true",
"sentry.traces-sample-rate=1.0",
"sentry.max-request-body-size=medium",
"sentry.enable-backpressure-handling=false",
],
)
class SentrySpringIntegrationTest {
@Autowired lateinit var transport: ITransport
@MockitoSpyBean lateinit var scopes: IScopes
@LocalServerPort var port: Int? = null
@BeforeTest
fun reset() {
reset(transport)
}
@Test
fun `attaches request and user information to SentryEvents`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val headers = HttpHeaders()
headers.put("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.put("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()
},
anyOrNull(),
)
}
@Test
fun `sends events for error logs`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/logging", String::class.java)
verify(transport)
.send(
checkEvent { event ->
assertThat(event.message).isNotNull()
assertThat(event.message!!.message).isEqualTo("event from logger")
},
anyOrNull(),
)
}
@Test
fun `attaches span context to events triggered within transaction`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/performance", String::class.java)
verify(transport)
.send(checkEvent { event -> assertThat(event.contexts.trace).isNotNull() }, anyOrNull())
}
@Test
fun `tracing filter does not overwrite resposne status code`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
val response =
restTemplate.getForEntity("http://localhost:$port/performance", String::class.java)
assertThat(response.statusCode).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
}
@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(scopes, never()).captureEvent(any())
}
@Test
fun `sets user on transaction`() {
val restTemplate = TestRestTemplate().withBasicAuth("user", "password")
restTemplate.getForEntity("http://localhost:$port/performance", String::class.java)
verify(transport)
.send(
checkTransaction { transaction ->
assertThat(transaction.transaction).isEqualTo("GET /performance")
assertThat(transaction.user).isNotNull()
assertThat(transaction.user!!.username).isEqualTo("user")
},
anyOrNull(),
)
}
}
@SpringBootApplication
open class App {
private val transport = mock<ITransport>().also { whenever(it.isHealthy).thenReturn(true) }
@Bean
open fun mockTransportFactory(): ITransportFactory {
val factory = mock<ITransportFactory>()
whenever(factory.create(any(), any())).thenReturn(transport)
return factory
}
@Bean open fun mockTransport() = transport
@Bean
open fun optionsCallback() =
Sentry.OptionsConfiguration<SentryOptions> { options ->
// due to OTel being on the classpath we need to set the default again
options.spanFactory = DefaultSpanFactory()
options.openTelemetryMode = SentryOpenTelemetryMode.OFF
}
}
@RestController
class HelloController(private val helloService: HelloService) {
private val logger = LoggerFactory.getLogger(HelloController::class.java)
@GetMapping("/hello")
fun hello() {
Sentry.captureMessage("hello")
}
@GetMapping("/throws")
fun throws() {
throw RuntimeException("something went wrong")
}
@GetMapping("/throws-handled")
fun throwsHandled() {
throw CustomException("handled exception")
}
@GetMapping("/performance")
fun performance() {
helloService.throws()
}
@GetMapping("/logging")
fun logging() {
logger.error("event from logger")
}
@PostMapping("/body")
fun body() {
Sentry.captureMessage("body")
}
@PostMapping("/bodyAsParam")
fun bodyWithReadingBodyInController(@RequestBody body: String) {
Sentry.captureMessage("body")
}
}
@Service
open class HelloService {
@SentrySpan
open fun throws() {
throw RuntimeException("something went wrong")
}
}
@Configuration
open class SecurityConfiguration {
@Bean
open fun userDetailsService(): InMemoryUserDetailsManager {
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)
}
@Bean
@Throws(Exception::class)
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http
.csrf { it.disable() }
.authorizeHttpRequests { it.anyRequest().authenticated() }
.httpBasic {}
return http.build()
}
}
class CustomException(message: String) : RuntimeException(message)
@ControllerAdvice
class ExceptionHandlers {
@ExceptionHandler(CustomException::class)
fun handle(e: CustomException) = ResponseEntity.badRequest().build<Void>()
}