|
| 1 | +package io.sentry.android.core; |
| 2 | + |
| 3 | +import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion; |
| 4 | + |
| 5 | +import android.os.Build; |
| 6 | +import android.os.Handler; |
| 7 | +import android.os.Looper; |
| 8 | +import android.webkit.WebView; |
| 9 | +import androidx.annotation.MainThread; |
| 10 | +import io.sentry.BaggageHeader; |
| 11 | +import io.sentry.ILogger; |
| 12 | +import io.sentry.IScopes; |
| 13 | +import io.sentry.Sentry; |
| 14 | +import io.sentry.SentryLevel; |
| 15 | +import io.sentry.util.ExceptionUtils; |
| 16 | +import io.sentry.util.LoadClass; |
| 17 | +import io.sentry.util.TracingUtils; |
| 18 | +import java.util.Arrays; |
| 19 | +import java.util.Collections; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Map; |
| 22 | +import java.util.WeakHashMap; |
| 23 | +import org.jetbrains.annotations.NotNull; |
| 24 | +import org.jetbrains.annotations.Nullable; |
| 25 | + |
| 26 | +/** |
| 27 | + * Connects the app's trace with the trace of web content shown in a {@link WebView}. |
| 28 | + * |
| 29 | + * <p>{@link #addTracePropagation(WebView, List)} writes the current trace into every document the |
| 30 | + * WebView loads from an allowed host as {@code sentry-trace} and {@code baggage} meta tags, before |
| 31 | + * any page script runs. A {@code @sentry/browser} running in the page with {@code |
| 32 | + * browserTracingIntegration} then continues the trace on pageload. |
| 33 | + * |
| 34 | + * <p>Requires the {@code androidx.webkit:webkit} dependency and an Android System WebView that |
| 35 | + * supports {@code WebViewFeature.DOCUMENT_START_SCRIPT}. |
| 36 | + */ |
| 37 | +public final class SentryWebViewTracing { |
| 38 | + |
| 39 | + static final @NotNull String SCRIPT_HANDLER_CLASS_NAME = "androidx.webkit.ScriptHandler"; |
| 40 | + |
| 41 | + private static final @NotNull String INTEGRATION_NAME = "WebViewTracePropagation"; |
| 42 | + |
| 43 | + /** |
| 44 | + * Counts, per WebView, the calls that finished replacing Sentry's script on the WebView's thread. |
| 45 | + * Weak keys, so it doesn't keep WebViews alive. |
| 46 | + */ |
| 47 | + private static final @NotNull Map<WebView, Long> replacements = |
| 48 | + Collections.synchronizedMap(new WeakHashMap<>()); |
| 49 | + |
| 50 | + private SentryWebViewTracing() {} |
| 51 | + |
| 52 | + /** |
| 53 | + * Same as {@link #addTracePropagation(WebView, List)}. |
| 54 | + * |
| 55 | + * @param webView the WebView to connect |
| 56 | + * @param allowedHosts hosts whose pages receive the trace |
| 57 | + * @return true if the trace propagation script was installed |
| 58 | + */ |
| 59 | + @MainThread |
| 60 | + public static boolean addTracePropagation( |
| 61 | + final @NotNull WebView webView, final @NotNull String... allowedHosts) { |
| 62 | + return addTracePropagation(webView, Arrays.asList(allowedHosts)); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Installs a script that writes the current trace into documents the WebView loads from an |
| 67 | + * allowed host. Call it on the main thread, before loading a URL: it applies to documents that |
| 68 | + * start loading after the call. |
| 69 | + * |
| 70 | + * <p>{@code allowedHosts} is a trust boundary: only list hosts whose content you control. A page |
| 71 | + * matches when its hostname equals an entry or is a subdomain of it, over https. Entries are |
| 72 | + * normalized, so a scheme, a path, and a trailing dot are ignored. A port other than 443 limits |
| 73 | + * the entry to pages served on that port (for example {@code "example.com:8443"}). |
| 74 | + * |
| 75 | + * <p>The trace is a snapshot taken when this is called. To propagate a newer trace to a later |
| 76 | + * page load, call this again: it replaces the script Sentry installed earlier and leaves other |
| 77 | + * scripts alone. If the call fails, no Sentry script is left on the WebView. |
| 78 | + * |
| 79 | + * <p>The root span name ({@code sentry-transaction}) is removed from {@code baggage}, as it is |
| 80 | + * free-form text that may carry user data. |
| 81 | + * |
| 82 | + * @param webView the WebView to connect |
| 83 | + * @param allowedHosts hosts whose pages receive the trace |
| 84 | + * @return true if the script was installed; false if androidx.webkit is missing, the WebView does |
| 85 | + * not support document-start scripts, {@code allowedHosts} has no valid entry, or there is no |
| 86 | + * trace (for example the SDK is not initialized), or it is called off the WebView's thread |
| 87 | + */ |
| 88 | + @MainThread |
| 89 | + public static boolean addTracePropagation( |
| 90 | + final @NotNull WebView webView, final @NotNull List<String> allowedHosts) { |
| 91 | + return addTracePropagation(webView, allowedHosts, Sentry.getCurrentScopes(), new LoadClass()); |
| 92 | + } |
| 93 | + |
| 94 | + static boolean addTracePropagation( |
| 95 | + final @NotNull WebView webView, |
| 96 | + final @NotNull List<String> allowedHosts, |
| 97 | + final @NotNull IScopes scopes, |
| 98 | + final @NotNull LoadClass loadClass) { |
| 99 | + // Registered on use rather than on success, like the other SDKs, so adoption counts apps that |
| 100 | + // wired the feature up even when this call cannot install. |
| 101 | + addIntegrationToSdkVersion(INTEGRATION_NAME); |
| 102 | + |
| 103 | + if (!loadClass.isClassAvailable(SCRIPT_HANDLER_CLASS_NAME, scopes.getOptions())) { |
| 104 | + scopes |
| 105 | + .getOptions() |
| 106 | + .getLogger() |
| 107 | + .log( |
| 108 | + SentryLevel.WARNING, |
| 109 | + "WebView trace propagation requires the androidx.webkit dependency, skipping."); |
| 110 | + return false; |
| 111 | + } |
| 112 | + return install(webView, allowedHosts, scopes, new AndroidxWebViewScriptInstaller()); |
| 113 | + } |
| 114 | + |
| 115 | + static boolean install( |
| 116 | + final @NotNull WebView webView, |
| 117 | + final @NotNull List<String> allowedHosts, |
| 118 | + final @NotNull IScopes scopes, |
| 119 | + final @NotNull WebViewScriptInstaller installer) { |
| 120 | + final @NotNull ILogger logger = scopes.getOptions().getLogger(); |
| 121 | + |
| 122 | + // WebView methods throw when called off the WebView's thread; fail like any other misuse. |
| 123 | + if (!isOnWebViewThread(webView)) { |
| 124 | + logger.log( |
| 125 | + SentryLevel.WARNING, |
| 126 | + "addTracePropagation must be called on the WebView's thread, skipping WebView trace propagation."); |
| 127 | + removeOnWebViewThread(webView, installer, logger); |
| 128 | + return false; |
| 129 | + } |
| 130 | + |
| 131 | + try { |
| 132 | + return replaceScript(webView, allowedHosts, scopes, installer, logger); |
| 133 | + } catch (LinkageError e) { |
| 134 | + // androidx.webkit is compileOnly, so the version in the app's apk may be older than the one |
| 135 | + // we compiled against and lack the APIs used here. |
| 136 | + logger.log( |
| 137 | + SentryLevel.WARNING, |
| 138 | + "androidx.webkit is too old for WebView trace propagation, skipping.", |
| 139 | + e); |
| 140 | + return false; |
| 141 | + } finally { |
| 142 | + // Counted once the replacement is done, so an off-thread call made while it runs doesn't |
| 143 | + // later remove the script it installed. Only written on the WebView's thread. |
| 144 | + replacements.put(webView, replacementsOf(webView) + 1); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + private static boolean replaceScript( |
| 149 | + final @NotNull WebView webView, |
| 150 | + final @NotNull List<String> allowedHosts, |
| 151 | + final @NotNull IScopes scopes, |
| 152 | + final @NotNull WebViewScriptInstaller installer, |
| 153 | + final @NotNull ILogger logger) { |
| 154 | + // Remove Sentry's previous script first, so a failed re-add never leaves a stale trace behind. |
| 155 | + installer.removeInstalledScript(webView); |
| 156 | + |
| 157 | + final @NotNull List<String> hosts = WebViewTracePropagationScript.normalizeHosts(allowedHosts); |
| 158 | + if (hosts.isEmpty()) { |
| 159 | + logger.log( |
| 160 | + SentryLevel.WARNING, |
| 161 | + "No valid allowedHosts provided, skipping WebView trace propagation."); |
| 162 | + return false; |
| 163 | + } |
| 164 | + |
| 165 | + if (!installer.isDocumentStartScriptSupported()) { |
| 166 | + logger.log( |
| 167 | + SentryLevel.WARNING, |
| 168 | + "The WebView does not support document-start scripts, skipping WebView trace propagation."); |
| 169 | + return false; |
| 170 | + } |
| 171 | + |
| 172 | + final @Nullable TracingUtils.TracingHeaders headers = |
| 173 | + TracingUtils.trace(scopes, null, scopes.getSpan()); |
| 174 | + if (headers == null) { |
| 175 | + logger.log( |
| 176 | + SentryLevel.DEBUG, |
| 177 | + "No trace available (the SDK is disabled or not initialized), skipping WebView trace propagation."); |
| 178 | + return false; |
| 179 | + } |
| 180 | + |
| 181 | + final @Nullable BaggageHeader baggageHeader = headers.getBaggageHeader(); |
| 182 | + final @Nullable String baggage = |
| 183 | + WebViewTracePropagationScript.stripTransactionFromBaggage( |
| 184 | + baggageHeader == null ? null : baggageHeader.getValue()); |
| 185 | + final @NotNull String script = |
| 186 | + WebViewTracePropagationScript.build( |
| 187 | + hosts, headers.getSentryTraceHeader().getValue(), baggage); |
| 188 | + |
| 189 | + try { |
| 190 | + if (!installer.installScript( |
| 191 | + webView, script, WebViewTracePropagationScript.originRules(allowedHosts))) { |
| 192 | + logger.log( |
| 193 | + SentryLevel.WARNING, |
| 194 | + "The WebView does not support document-start scripts, skipping WebView trace propagation."); |
| 195 | + return false; |
| 196 | + } |
| 197 | + } catch (IllegalArgumentException e) { |
| 198 | + logger.log( |
| 199 | + SentryLevel.WARNING, "Invalid allowedHosts, skipping WebView trace propagation.", e); |
| 200 | + return false; |
| 201 | + } |
| 202 | + |
| 203 | + return true; |
| 204 | + } |
| 205 | + |
| 206 | + /** |
| 207 | + * A failed call must not leave a stale trace behind, but off the WebView's thread the script can |
| 208 | + * only be removed later, on that thread. The removal is skipped if a call on the WebView's thread |
| 209 | + * replaced this WebView's script in the meantime, so it never removes a newer script. |
| 210 | + */ |
| 211 | + private static void removeOnWebViewThread( |
| 212 | + final @NotNull WebView webView, |
| 213 | + final @NotNull WebViewScriptInstaller installer, |
| 214 | + final @NotNull ILogger logger) { |
| 215 | + final long replacementsSeen = replacementsOf(webView); |
| 216 | + new Handler(webViewLooper(webView)) |
| 217 | + .post( |
| 218 | + () -> { |
| 219 | + if (replacementsOf(webView) != replacementsSeen) { |
| 220 | + return; |
| 221 | + } |
| 222 | + // Runs outside of any app call, so only fatal errors may escape: for example, the |
| 223 | + // WebView may have been destroyed since. |
| 224 | + try { |
| 225 | + installer.removeInstalledScript(webView); |
| 226 | + } catch (LinkageError e) { |
| 227 | + logger.log( |
| 228 | + SentryLevel.WARNING, |
| 229 | + "androidx.webkit is too old for WebView trace propagation, skipping.", |
| 230 | + e); |
| 231 | + } catch (Throwable e) { |
| 232 | + ExceptionUtils.rethrowIfFatal(e); |
| 233 | + logger.log( |
| 234 | + SentryLevel.WARNING, |
| 235 | + "Failed to remove the WebView trace propagation script.", |
| 236 | + e); |
| 237 | + } |
| 238 | + }); |
| 239 | + } |
| 240 | + |
| 241 | + private static long replacementsOf(final @NotNull WebView webView) { |
| 242 | + final @Nullable Long count = replacements.get(webView); |
| 243 | + return count == null ? 0 : count; |
| 244 | + } |
| 245 | + |
| 246 | + private static boolean isOnWebViewThread(final @NotNull WebView webView) { |
| 247 | + return Looper.myLooper() == webViewLooper(webView); |
| 248 | + } |
| 249 | + |
| 250 | + private static @NotNull Looper webViewLooper(final @NotNull WebView webView) { |
| 251 | + return Build.VERSION.SDK_INT >= Build.VERSION_CODES.P |
| 252 | + ? webView.getWebViewLooper() |
| 253 | + : Looper.getMainLooper(); |
| 254 | + } |
| 255 | +} |
0 commit comments