-
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathSentryApollo4HttpInterceptor.kt
More file actions
428 lines (362 loc) · 13.8 KB
/
SentryApollo4HttpInterceptor.kt
File metadata and controls
428 lines (362 loc) · 13.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
package io.sentry.apollo4
import com.apollographql.apollo.api.http.HttpHeader
import com.apollographql.apollo.api.http.HttpRequest
import com.apollographql.apollo.api.http.HttpResponse
import com.apollographql.apollo.exception.ApolloHttpException
import com.apollographql.apollo.network.http.HttpInterceptor
import com.apollographql.apollo.network.http.HttpInterceptorChain
import io.sentry.BaggageHeader
import io.sentry.Breadcrumb
import io.sentry.Hint
import io.sentry.IScopes
import io.sentry.ISpan
import io.sentry.ScopesAdapter
import io.sentry.SentryEvent
import io.sentry.SentryIntegrationPackageStorage
import io.sentry.SentryLevel
import io.sentry.SentryOptions.DEFAULT_PROPAGATION_TARGETS
import io.sentry.SpanDataConvention
import io.sentry.SpanDataConvention.HTTP_METHOD_KEY
import io.sentry.SpanStatus
import io.sentry.TypeCheckHint.APOLLO_REQUEST
import io.sentry.TypeCheckHint.APOLLO_RESPONSE
import io.sentry.exception.ExceptionMechanismException
import io.sentry.protocol.Mechanism
import io.sentry.protocol.Request
import io.sentry.protocol.Response
import io.sentry.util.HttpUtils
import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion
import io.sentry.util.Platform
import io.sentry.util.PropagationTargetsUtils
import io.sentry.util.SpanUtils
import io.sentry.util.TracingUtils
import io.sentry.util.UrlUtils
import io.sentry.vendor.Base64
import java.util.Locale
import okio.Buffer
import org.jetbrains.annotations.ApiStatus
private const val TRACE_ORIGIN = "auto.graphql.apollo4"
class SentryApollo4HttpInterceptor
@JvmOverloads
constructor(
@ApiStatus.Internal private val scopes: IScopes = ScopesAdapter.getInstance(),
private val beforeSpan: BeforeSpanCallback? = null,
private val captureFailedRequests: Boolean = DEFAULT_CAPTURE_FAILED_REQUESTS,
private val failedRequestTargets: List<String> = listOf(DEFAULT_PROPAGATION_TARGETS),
) : HttpInterceptor {
init {
addIntegrationToSdkVersion("Apollo4")
if (captureFailedRequests) {
SentryIntegrationPackageStorage.getInstance().addIntegration("Apollo4ClientError")
}
}
private val regex: Regex by lazy { "(?i)\"errors\"\\s*:\\s*\\[".toRegex() }
override suspend fun intercept(request: HttpRequest, chain: HttpInterceptorChain): HttpResponse {
val activeSpan = if (Platform.isAndroid()) scopes.transaction else scopes.span
val operationId = decodeHeaderValue(request, OPERATION_ID_HEADER_NAME)
val operationName = decodeHeaderValue(request, OPERATION_NAME_HEADER_NAME)
val operationType = decodeHeaderValue(request, OPERATION_TYPE_HEADER_NAME)
var span: ISpan? = null
if (activeSpan != null) {
span = startChild(request, activeSpan, operationName, operationType, operationId)
}
val modifiedRequest = maybeAddTracingHeaders(scopes, request, span)
var httpResponse: HttpResponse? = null
var statusCode: Int? = null
try {
httpResponse = chain.proceed(modifiedRequest)
statusCode = httpResponse.statusCode
span?.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, statusCode)
span?.status = SpanStatus.fromHttpStatusCode(statusCode)
captureEvent(modifiedRequest, httpResponse, operationName, operationType)
return httpResponse
} catch (e: Throwable) {
// client errors don't throw anymore in v4, but we should still be able to detect all of them
// by looking at the status code and/or errors in the response body
when (e) {
is ApolloHttpException -> {
statusCode = e.statusCode
span?.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, statusCode)
span?.status = SpanStatus.fromHttpStatusCode(statusCode, SpanStatus.INTERNAL_ERROR)
}
else -> span?.status = SpanStatus.INTERNAL_ERROR
}
span?.throwable = e
throw e
} finally {
finish(
span,
modifiedRequest,
httpResponse,
statusCode,
operationName,
operationType,
operationId,
)
}
}
private fun maybeAddTracingHeaders(
scopes: IScopes,
request: HttpRequest,
span: ISpan?,
): HttpRequest {
var cleanedHeaders = removeSentryInternalHeaders(request.headers).toMutableList()
if (!isIgnored()) {
TracingUtils.traceIfAllowed(
scopes,
request.url,
request.headers.filter { it.name == BaggageHeader.BAGGAGE_HEADER }.map { it.value },
span,
)
?.let {
cleanedHeaders.add(HttpHeader(it.sentryTraceHeader.name, it.sentryTraceHeader.value))
it.baggageHeader?.let { baggageHeader ->
cleanedHeaders =
cleanedHeaders
.filterNot { it.name == BaggageHeader.BAGGAGE_HEADER }
.toMutableList()
.apply { add(HttpHeader(baggageHeader.name, baggageHeader.value)) }
}
it.w3cTraceparentHeader?.let { w3cHeader ->
cleanedHeaders.add(HttpHeader(w3cHeader.name, w3cHeader.value))
}
}
}
val requestBuilder = request.newBuilder().apply { headers(cleanedHeaders) }
return requestBuilder.build()
}
private fun isIgnored(): Boolean =
SpanUtils.isIgnored(scopes.getOptions().ignoredSpanOrigins, TRACE_ORIGIN)
private fun removeSentryInternalHeaders(headers: List<HttpHeader>): List<HttpHeader> =
headers.filterNot { header ->
INTERNAL_HEADER_NAMES.any { internalHeader -> header.name.equals(internalHeader, true) }
}
private fun startChild(
request: HttpRequest,
activeSpan: ISpan,
operationName: String?,
operationType: String?,
operationId: String?,
): ISpan {
val urlDetails = UrlUtils.parse(request.url)
val method = request.method.name
val operation = if (operationType != null) "http.graphql.$operationType" else "http.graphql"
val variables = decodeHeaderValue(request, VARIABLES_HEADER_NAME)
val description = "${operationType ?: method} ${operationName ?: urlDetails.urlOrFallback}"
return activeSpan.startChild(operation, description).apply {
urlDetails.applyToSpan(this)
spanContext.origin = TRACE_ORIGIN
operationId?.let { setData("operationId", it) }
variables?.let { setData("variables", it) }
setData(HTTP_METHOD_KEY, method.uppercase(Locale.ROOT))
}
}
private fun decodeHeaderValue(request: HttpRequest, headerName: String): String? {
return getHeader(headerName, request.headers)?.let {
try {
String(Base64.decode(it, Base64.NO_WRAP))
} catch (e: Throwable) {
scopes.options.logger.log(
SentryLevel.ERROR,
"Error decoding internal apolloHeader $headerName",
e,
)
return null
}
}
}
private fun finish(
span: ISpan?,
request: HttpRequest,
response: HttpResponse?,
statusCode: Int?,
operationName: String?,
operationType: String?,
operationId: String?,
) {
var responseContentLength: Long? = null
response?.body?.buffer?.size?.ifHasValidLength { responseContentLength = it }
if (span != null) {
statusCode?.let { span.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, statusCode) }
responseContentLength?.let {
span.setData(SpanDataConvention.HTTP_RESPONSE_CONTENT_LENGTH_KEY, it)
}
if (beforeSpan != null) {
try {
val result = beforeSpan.execute(span, request, response)
if (result == null) {
// Span is dropped
span.spanContext.sampled = false
}
} catch (e: Throwable) {
scopes.options.logger.log(
SentryLevel.ERROR,
"An error occurred while executing beforeSpan in ApolloInterceptor",
e,
)
}
}
span.finish()
}
val breadcrumb = Breadcrumb.http(request.url, request.method.name, statusCode)
request.body?.contentLength.ifHasValidLength { contentLength ->
breadcrumb.setData("request_body_size", contentLength)
}
operationName?.let { breadcrumb.setData("operation_name", it) }
operationType?.let { breadcrumb.setData("operation_type", it) }
operationId?.let { breadcrumb.setData("operation_id", it) }
val hint = Hint().also { it.set(APOLLO_REQUEST, request) }
response?.let { httpResponse ->
responseContentLength?.let { breadcrumb.setData("response_body_size", it) }
hint.set(APOLLO_RESPONSE, httpResponse)
}
scopes.addBreadcrumb(breadcrumb, hint)
}
// Extensions
private fun Long?.ifHasValidLength(fn: (Long) -> Unit) {
if (this != null && this != -1L) {
fn.invoke(this)
}
}
private fun getHeader(key: String, headers: List<HttpHeader>): String? =
headers.firstOrNull { it.name.equals(key, true) }?.value
private fun getHeaders(headers: List<HttpHeader>): MutableMap<String, String>? {
// Headers are only sent if isSendDefaultPii is enabled due to PII
if (!scopes.options.isSendDefaultPii) {
return null
}
val headersMap = mutableMapOf<String, String>()
for (item in headers) {
val name = item.name
// header is only sent if isn't sensitive
if (HttpUtils.containsSensitiveHeader(name)) {
continue
}
headersMap[name] = item.value
}
return headersMap.ifEmpty { null }
}
private fun captureEvent(
request: HttpRequest,
response: HttpResponse,
operationName: String?,
operationType: String?,
) {
// return if the feature is disabled
if (!captureFailedRequests) {
return
}
// wrap everything up in a try catch block so every exception is swallowed and degraded
// gracefully
try {
// we pay the price to read the response in the memory to check if there's any errors
// GraphQL does not throw status code 400+ for every type of error
val body =
try {
response.body?.peek()?.readUtf8() ?: ""
} catch (e: Throwable) {
scopes.options.logger.log(SentryLevel.ERROR, "Error reading the response body.", e)
// bail out because the response body has the most important information
return
}
// if the response body does not have the errors field, do not raise an issue
if (body.isEmpty() || !regex.containsMatchIn(body)) {
return
}
// not possible to get a parameterized url, but we remove at least the
// query string and the fragment.
// url example: https://api.github.com/users/getsentry/repos/#fragment?query=query
// url will be: https://api.github.com/users/getsentry/repos/
// ideally we'd like a parameterized url: https://api.github.com/users/{user}/repos/
// but that's not possible
val urlDetails = UrlUtils.parse(request.url)
// return if it's not a target match
if (!PropagationTargetsUtils.contain(failedRequestTargets, urlDetails.urlOrFallback)) {
return
}
val mechanism = Mechanism().apply { type = "SentryApollo4Interceptor" }
val fingerprints = mutableListOf<String>()
val builder = StringBuilder()
builder.append("GraphQL Request failed")
operationName?.let {
builder.append(", name: $it")
fingerprints.add(operationName)
}
operationType?.let {
builder.append(", type: $it")
fingerprints.add(operationType)
}
val exception = SentryApollo4ClientException(builder.toString())
val mechanismException =
ExceptionMechanismException(mechanism, exception, Thread.currentThread(), true)
val event = SentryEvent(mechanismException)
val hint = Hint()
hint.set(APOLLO_REQUEST, request)
hint.set(APOLLO_RESPONSE, response)
val sentryRequest =
Request().apply {
urlDetails.applyToRequest(this)
// Cookie is only sent if isSendDefaultPii is enabled
cookies =
if (scopes.options.isSendDefaultPii) getHeader("Cookie", request.headers) else null
method = request.method.name
headers = getHeaders(request.headers)
apiTarget = "graphql"
request.body?.let {
bodySize = it.contentLength
val buffer = Buffer()
try {
it.writeTo(buffer)
data = buffer.readUtf8()
} catch (e: Throwable) {
scopes.options.logger.log(SentryLevel.ERROR, "Error reading the request body.", e)
// continue because the response body alone can already give some insights
} finally {
buffer.close()
}
}
}
val sentryResponse =
Response().apply {
// Set-Cookie is only sent if isSendDefaultPii is enabled due to PII
cookies =
if (scopes.options.isSendDefaultPii) {
getHeader("Set-Cookie", response.headers)
} else {
null
}
headers = getHeaders(response.headers)
statusCode = response.statusCode
response.body?.buffer?.size?.ifHasValidLength { contentLength ->
bodySize = contentLength
}
data = body
}
fingerprints.add(response.statusCode.toString())
event.request = sentryRequest
event.contexts.setResponse(sentryResponse)
event.fingerprints = fingerprints
scopes.captureEvent(event, hint)
} catch (e: Throwable) {
scopes.options.logger.log(SentryLevel.ERROR, "Error capturing the GraphQL error.", e)
}
}
/** The BeforeSpan callback */
fun interface BeforeSpanCallback {
/**
* Mutates span before being added.
*
* @param span the span to mutate or drop
* @param request the Apollo request object
* @param response the Apollo response object
*/
fun execute(span: ISpan, request: HttpRequest, response: HttpResponse?): ISpan?
}
companion object {
const val DEFAULT_CAPTURE_FAILED_REQUESTS = true
init {
SentryIntegrationPackageStorage.getInstance()
.addPackage("maven:io.sentry:sentry-apollo-4", BuildConfig.VERSION_NAME)
}
}
}