Repository navigation
Expand file tree
/
Copy pathSentryApollo4HttpInterceptorTest.kt
More file actions
582 lines (522 loc) · 19.1 KB
/
Copy pathSentryApollo4HttpInterceptorTest.kt
File metadata and controls
582 lines (522 loc) · 19.1 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
package io.sentry.apollo4
import com.apollographql.apollo.ApolloCall
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.api.ApolloResponse
import com.apollographql.apollo.api.Operation
import com.apollographql.apollo.api.http.HttpMethod
import com.apollographql.apollo.api.http.HttpRequest
import com.apollographql.apollo.api.http.HttpResponse
import com.apollographql.apollo.exception.ApolloException
import com.apollographql.apollo.exception.ApolloHttpException
import com.apollographql.apollo.network.http.HttpInterceptor
import com.apollographql.apollo.network.http.HttpInterceptorChain
import com.google.common.truth.Truth.assertThat
import io.sentry.BaggageHeader
import io.sentry.Breadcrumb
import io.sentry.DataCategory
import io.sentry.Hint
import io.sentry.ILogger
import io.sentry.IScopes
import io.sentry.ITransaction
import io.sentry.Scope
import io.sentry.ScopeCallback
import io.sentry.ScopeType
import io.sentry.SentryLevel
import io.sentry.SentryOptions
import io.sentry.SentryOptions.DEFAULT_PROPAGATION_TARGETS
import io.sentry.SentryTraceHeader
import io.sentry.SentryTracer
import io.sentry.SpanDataConvention
import io.sentry.SpanDataConvention.HTTP_METHOD_KEY
import io.sentry.SpanStatus
import io.sentry.TraceContext
import io.sentry.TracesSamplingDecision
import io.sentry.TransactionContext
import io.sentry.W3CTraceparentHeader
import io.sentry.apollo4.SentryApollo4HttpInterceptor.BeforeSpanCallback
import io.sentry.apollo4.generated.LaunchDetailsQuery
import io.sentry.clientreport.DiscardReason
import io.sentry.mockServerRequestTimeoutMillis
import io.sentry.protocol.SdkVersion
import io.sentry.protocol.SentryTransaction
import io.sentry.util.Apollo4PlatformTestManipulator
import java.util.concurrent.TimeUnit
import kotlin.reflect.KSuspendFunction1
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.SocketPolicy
import okio.Buffer
import okio.ForwardingSource
import okio.buffer
import org.junit.Before
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.check
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import org.mockito.kotlin.whenever
class SentryApollo4HttpInterceptorTestWithV4Implementation :
SentryApollo4HttpInterceptorTest(ApolloCall<*>::execute)
class SentryApollo4HttpInterceptorTestWithV3Implementation :
SentryApollo4HttpInterceptorTest(ApolloCall<*>::executeV3)
abstract class SentryApollo4HttpInterceptorTest(
private val executeQueryImplementation:
KSuspendFunction1<ApolloCall<*>, ApolloResponse<out Operation.Data>>
) {
class Fixture {
val server = MockWebServer()
val options =
SentryOptions().apply {
dsn = "https://key@sentry.io/proj"
setTracePropagationTargets(listOf(DEFAULT_PROPAGATION_TARGETS))
sdkVersion = SdkVersion("test", "1.2.3")
}
val scope = Scope(options)
val scopes =
mock<IScopes>().also {
whenever(it.options).thenReturn(options)
doAnswer { (it.arguments[0] as ScopeCallback).run(scope) }
.whenever(it)
.configureScope(any())
doAnswer { (it.arguments[1] as ScopeCallback).run(scope) }
.whenever(it)
.configureScope(anyOrNull<ScopeType>(), any())
}
private var httpInterceptor =
SentryApollo4HttpInterceptor(scopes, captureFailedRequests = false)
@SuppressWarnings("LongParameterList")
fun getSut(
httpStatusCode: Int = 200,
responseBody: String =
"""{
"data": {
"launch": {
"__typename": "Launch",
"id": "83",
"site": "CCAFS SLC 40",
"mission": {
"__typename": "Mission",
"name": "Amos-17",
"missionPatch": "https://images2.imgbox.com/a0/ab/XUoByiuR_o.png"
}
}
}
}""",
socketPolicy: SocketPolicy = SocketPolicy.KEEP_OPEN,
interceptor: HttpInterceptor? = null,
addThirdPartyBaggageHeader: Boolean = false,
beforeSpan: BeforeSpanCallback? = null,
): ApolloClient {
server.enqueue(
MockResponse()
.setBody(responseBody)
.setSocketPolicy(socketPolicy)
.setResponseCode(httpStatusCode)
)
if (beforeSpan != null) {
httpInterceptor =
SentryApollo4HttpInterceptor(scopes, beforeSpan, captureFailedRequests = false)
}
val builder =
ApolloClient.Builder()
.serverUrl(server.url("/").toString())
.addHttpInterceptor(httpInterceptor)
interceptor?.let { builder.addHttpInterceptor(interceptor) }
if (addThirdPartyBaggageHeader) {
builder
.addHttpHeader("baggage", "thirdPartyBaggage=someValue")
.addHttpHeader(
"baggage",
"secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue",
)
}
return builder.build()
}
}
private val fixture = Fixture()
@Before
fun setup() {
Apollo4PlatformTestManipulator.pretendIsAndroid(false)
}
@Test
fun `creates a span around the successful request`() {
executeQuery()
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it, httpStatusCode = 200)
assertEquals(SpanStatus.OK, it.spans.first().status)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `creates a span around the failed request`() {
executeQuery(fixture.getSut(httpStatusCode = 403))
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it, httpStatusCode = 403)
assertEquals(SpanStatus.PERMISSION_DENIED, it.spans.first().status)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `get http status from ApolloHttpException in failed request`() {
val failingInterceptor =
object : HttpInterceptor {
override suspend fun intercept(
request: HttpRequest,
chain: HttpInterceptorChain,
): HttpResponse = throw ApolloHttpException(404, mock(), mock(), "")
}
executeQuery(fixture.getSut(interceptor = failingInterceptor))
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it, httpStatusCode = 404, contentLength = null)
assertEquals("POST", it.spans.first().data?.get(SpanDataConvention.HTTP_METHOD_KEY))
assertEquals(404, it.spans.first().data?.get(SpanDataConvention.HTTP_STATUS_CODE_KEY))
assertEquals(SpanStatus.NOT_FOUND, it.spans.first().status)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `creates a span around the request failing with network error`() {
executeQuery(fixture.getSut(socketPolicy = SocketPolicy.DISCONNECT_DURING_REQUEST_BODY))
verify(fixture.scopes)
.captureTransaction(
check {
assertTransactionDetails(it, httpStatusCode = null, contentLength = null)
assertEquals(SpanStatus.INTERNAL_ERROR, it.spans.first().status)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `does not add sentry trace header to the request if host is disallowed`() {
fixture.options.setTracePropagationTargets(listOf("some-host-that-does-not-exist"))
executeQuery(isSpanActive = false)
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
}
@Test
fun `when there is no active span, does not add sentry trace header to the request`() {
executeQuery(isSpanActive = false)
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNotNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
}
@Test
fun `does not add sentry-trace header when span origin is ignored`() {
fixture.options.setIgnoredSpanOrigins(listOf("auto.graphql.apollo4"))
executeQuery(isSpanActive = false)
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
}
@Test
fun `when there is an active span, adds sentry trace headers to the request`() {
executeQuery()
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNotNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
}
@Test
fun `when there is an active span, existing baggage headers are merged with sentry baggage into single header`() {
executeQuery(sut = fixture.getSut(addThirdPartyBaggageHeader = true))
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNotNull(recorderRequest.headers[BaggageHeader.BAGGAGE_HEADER])
val baggageHeaderValues = recorderRequest.headers.values(BaggageHeader.BAGGAGE_HEADER)
assertEquals(baggageHeaderValues.size, 1)
assertTrue(
baggageHeaderValues[0].startsWith(
"thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue"
)
)
assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key"))
assertTrue(baggageHeaderValues[0].contains("sentry-transaction=op"))
assertTrue(baggageHeaderValues[0].contains("sentry-trace_id"))
}
@Test
fun `does not read response body if failed request target does not match`(): Unit = runBlocking {
val bodyRead =
interceptWithContentType(
contentType = null,
url = "https://excluded.example/graphql",
)
assertThat(bodyRead).isFalse()
}
@Test
fun `does not read multipart mixed response body`(): Unit = runBlocking {
val bodyRead = interceptWithContentType("Multipart/Mixed; boundary=graphql")
assertThat(bodyRead).isFalse()
verify(fixture.scopes, never()).captureEvent(any(), any<Hint>())
}
@Test
fun `does not read event stream response body`(): Unit = runBlocking {
val bodyRead = interceptWithContentType(" text/event-stream ; charset=utf-8")
assertThat(bodyRead).isFalse()
verify(fixture.scopes, never()).captureEvent(any(), any<Hint>())
}
@Test
fun `reads json response body for failed request detection`(): Unit = runBlocking {
val bodyRead = interceptWithContentType("application/json; charset=utf-8")
assertThat(bodyRead).isTrue()
verify(fixture.scopes).captureEvent(any(), any<Hint>())
}
@Test
fun `reads response body without content type for failed request detection`(): Unit =
runBlocking {
val bodyRead = interceptWithContentType(null)
assertThat(bodyRead).isTrue()
verify(fixture.scopes).captureEvent(any(), any<Hint>())
}
/** Runs the interceptor against a GraphQL error body and returns whether the body was read. */
private suspend fun interceptWithContentType(
contentType: String?,
url: String = "https://target.example/graphql",
): Boolean {
var bodyRead = false
val body =
object : ForwardingSource(Buffer().writeUtf8("{\"errors\":[{\"message\":\"error\"}]}")) {
override fun read(sink: Buffer, byteCount: Long): Long {
bodyRead = true
return super.read(sink, byteCount)
}
}
.buffer()
val request = HttpRequest.Builder(HttpMethod.Post, url).build()
val responseBuilder = HttpResponse.Builder(200).body(body)
contentType?.let { responseBuilder.addHeader("content-type", it) }
val response = responseBuilder.build()
val chain =
object : HttpInterceptorChain {
override suspend fun proceed(request: HttpRequest): HttpResponse = response
}
val interceptor =
SentryApollo4HttpInterceptor(
fixture.scopes,
captureFailedRequests = true,
failedRequestTargets = listOf("target.example"),
)
interceptor.intercept(request, chain)
return bodyRead
}
@Test
fun `customizer modifies span`() {
executeQuery(
fixture.getSut(
beforeSpan = { span, request, response ->
span.description = "overwritten description"
span
}
)
)
verify(fixture.scopes)
.captureTransaction(
check {
assertEquals(1, it.spans.size)
val httpClientSpan = it.spans.first()
assertEquals("overwritten description", httpClientSpan.description)
},
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `returning null in beforeSpan callback drops span`() {
val onDiscard = mock<SentryOptions.OnDiscardCallback>()
fixture.options.onDiscard = onDiscard
executeQuery(fixture.getSut(beforeSpan = { _, _, _ -> null }))
verifyNoMoreInteractions(onDiscard)
verify(fixture.scopes)
.captureTransaction(
check { assertEquals(0, it.spans.size) },
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
}
@Test
fun `reports callback errors only for sampled spans`(): Unit = runBlocking {
for (sampled in listOf(true, false, null)) {
val onDiscard = mock<SentryOptions.OnDiscardCallback>()
fixture.options.onDiscard = onDiscard
val tx = SentryTracer(TransactionContext("op", "desc"), fixture.scopes)
tx.spanContext.sampled = sampled
whenever(fixture.scopes.span).thenReturn(tx)
val sut =
fixture.getSut(
beforeSpan = { span, _, _ ->
span.spanContext.sampled = false
error("callback failed")
}
)
assertThat(executeQueryImplementation(sut.query(LaunchDetailsQuery("83"))).data).isNotNull()
tx.finish()
if (sampled == true) {
verify(onDiscard).execute(DiscardReason.CALLBACK_ERROR, DataCategory.Span, 1)
}
verifyNoMoreInteractions(onDiscard)
}
}
@Test
fun `when beforeSpan throws, drops span and preserves response`(): Unit = runBlocking {
val failure = IllegalStateException("callback failed")
val logger = mock<ILogger>()
fixture.options.isDebug = true
fixture.options.setLogger(logger)
val tx =
SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes)
whenever(fixture.scopes.span).thenReturn(tx)
val sut =
fixture.getSut(
beforeSpan = { span, _, _ ->
span.description = "partially modified"
throw failure
}
)
val response = executeQueryImplementation(sut.query(LaunchDetailsQuery("83")))
assertThat(response.data).isNotNull()
val span = tx.children.single()
assertThat(span.isSampled).isFalse()
assertThat(span.isFinished).isTrue()
tx.finish()
verify(fixture.scopes)
.captureTransaction(
check { assertThat(it.spans).isEmpty() },
anyOrNull<TraceContext>(),
anyOrNull(),
anyOrNull(),
)
verify(fixture.scopes).addBreadcrumb(any<Breadcrumb>(), anyOrNull())
verify(logger)
.log(
SentryLevel.ERROR,
"An error occurred while executing beforeSpan in ApolloInterceptor",
failure,
)
}
@Test
fun `adds breadcrumb when http calls succeeds`() {
executeQuery(fixture.getSut())
verify(fixture.scopes)
.addBreadcrumb(
check<Breadcrumb> {
assertEquals("http", it.type)
// response_body_size is added but mock webserver returns 0 always
assertEquals(0L, it.data["response_body_size"])
assertEquals(193L, it.data["request_body_size"])
},
anyOrNull(),
)
}
@Test
fun `sets SDKVersion Info`() {
assertNotNull(fixture.scopes.options.sdkVersion)
assert(fixture.scopes.options.sdkVersion!!.integrationSet.contains("Apollo4"))
}
@Test
fun `attaches to root transaction on Android`() {
Apollo4PlatformTestManipulator.pretendIsAndroid(true)
executeQuery(fixture.getSut())
verify(fixture.scopes).transaction
}
@Test
fun `attaches to child span on non-Android`() {
Apollo4PlatformTestManipulator.pretendIsAndroid(false)
executeQuery(fixture.getSut())
verify(fixture.scopes).span
}
@Test
fun `adds W3C traceparent header when propagateTraceparent is enabled`() {
fixture.options.isPropagateTraceparent = true
executeQuery()
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNotNull(recorderRequest.headers[W3CTraceparentHeader.TRACEPARENT_HEADER])
}
@Test
fun `does not add W3C traceparent header when propagateTraceparent is disabled`() {
fixture.options.isPropagateTraceparent = false
executeQuery()
val recorderRequest =
fixture.server.takeRequest(mockServerRequestTimeoutMillis, TimeUnit.MILLISECONDS)!!
assertNotNull(recorderRequest.headers[SentryTraceHeader.SENTRY_TRACE_HEADER])
assertNull(recorderRequest.headers[W3CTraceparentHeader.TRACEPARENT_HEADER])
}
private fun assertTransactionDetails(
it: SentryTransaction,
httpStatusCode: Int? = 200,
contentLength: Long? = 0L,
) {
assertEquals(1, it.spans.size)
val httpClientSpan = it.spans.first()
assertEquals("http.graphql", httpClientSpan.op)
assertEquals(
"Post http://${fixture.server.hostName}:${fixture.server.port}/",
httpClientSpan.description,
)
assertNotNull(httpClientSpan.data) {
assertEquals("POST", it[HTTP_METHOD_KEY])
httpStatusCode?.let { code ->
assertEquals(code, it[SpanDataConvention.HTTP_STATUS_CODE_KEY])
}
contentLength?.let { contentLength ->
assertEquals(contentLength, it[SpanDataConvention.HTTP_RESPONSE_CONTENT_LENGTH_KEY])
}
}
}
private fun executeQuery(
sut: ApolloClient = fixture.getSut(),
isSpanActive: Boolean = true,
id: String = "83",
) = runBlocking {
var tx: ITransaction? = null
if (isSpanActive) {
tx =
SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes)
whenever(fixture.scopes.transaction).thenReturn(tx)
whenever(fixture.scopes.span).thenReturn(tx)
}
val coroutine = launch {
try {
executeQueryImplementation(sut.query(LaunchDetailsQuery(id)))
} catch (e: ApolloException) {
return@launch
}
}
coroutine.join()
tx?.finish()
}
}