Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

### Fixes

- Session Replay: Fix Compose masking for Jetpack Compose 1.13. If the SDK can't walk the Compose tree of a screen, it now masks the whole Compose view instead of recording it unmasked ([#6626](https://github.com/getsentry/sentry-java/pull/6626))
- Session Replay: Send Ktor client network request start and end times in milliseconds, so the requests line up with the replay ([#6619](https://github.com/getsentry/sentry-java/pull/6619))
- Nav3: Stop attributing errors and spans from an Activity or ViewPager2 page without a `SentryNavEffect` to the most recently visited Nav3 root ([#6483](https://github.com/getsentry/sentry-java/pull/6483))
- Android: Count deep sleep in breadcrumb, screenshot and view hierarchy debounce windows, so the first low-memory or battery breadcrumb after a long Doze is no longer dropped ([#6590](https://github.com/getsentry/sentry-java/pull/6590))
Expand Down
25 changes: 25 additions & 0 deletions sentry-android-replay/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import com.android.build.api.variant.HasHostTestsBuilder
import com.android.build.api.variant.HostTestBuilder
import io.gitlab.arturbosch.detekt.Detekt
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.dsl.KotlinVersion
Expand All @@ -16,6 +18,10 @@ plugins {
id("io.sentry.robolectric")
}

// Session Replay calls Compose internals, whose mangled JVM names change between Compose versions.
// Creating extra build types to run tests against the latest stable, and latest preview version.
val composeUiTestVersions = mapOf("composeUi112" to "1.12.1", "composeUi113" to "1.13.0-rc01")

android {
compileSdk = libs.versions.compileSdk.get().toInt()
compileSdkMinor = libs.versions.compileSdkMinor.get().toInt()
Expand All @@ -37,6 +43,12 @@ android {
buildTypes {
getByName("debug") { consumerProguardFiles("proguard-rules.pro") }
getByName("release") { consumerProguardFiles("proguard-rules.pro") }
composeUiTestVersions.keys.forEach { name ->
create(name) {
initWith(getByName("release"))
matchingFallbacks += "release"
}
}
}

// AGP 9 only generates unit tests for the testBuildType. The debug variant is
Expand Down Expand Up @@ -73,6 +85,9 @@ android {

androidComponents.beforeVariants {
it.enable = !Config.Android.shouldSkipDebugVariant(it.buildType)
if (it.buildType in composeUiTestVersions) {
(it as HasHostTestsBuilder).hostTests[HostTestBuilder.UNIT_TEST_TYPE]?.enable = true
}
}
}

Expand Down Expand Up @@ -102,6 +117,16 @@ dependencies {
testImplementation(libs.coil.compose)
}

composeUiTestVersions.forEach { (buildType, version) ->
configurations
.matching { it.name == "${buildType}UnitTestRuntimeClasspath" }
.configureEach {
resolutionStrategy.eachDependency {
if (requested.group == "androidx.compose.ui") useVersion(version)
}
}
}

tasks.withType<Detekt>().configureEach {
// Target version of the generated JVM bytecode. It is used for type resolution.
jvmTarget = JavaVersion.VERSION_1_8.toString()
Expand Down
2 changes: 1 addition & 1 deletion sentry-android-replay/detekt-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@
<ID>ReturnCount:ReplayGestureConverter.kt$ReplayGestureConverter$fun convert( event: MotionEvent, recorderConfig: ScreenshotRecorderConfig, ): List&lt;RRWebIncrementalSnapshotEvent>?</ID>
<ID>ReturnCount:ReplayIntegration.kt$ReplayIntegration$override fun captureReplay(isTerminating: Boolean?): SentryId</ID>
<ID>ReturnCount:ScreenshotRecorder.kt$ScreenshotRecorder$fun capture()</ID>
<ID>ReturnCount:SentryLayoutNodeHelper.kt$SentryLayoutNodeHelper$@Suppress("UNCHECKED_CAST") fun getChildren(node: LayoutNode): List&lt;LayoutNode></ID>
<ID>ReturnCount:SentryLayoutNodeHelper.kt$SentryLayoutNodeHelper$@JvmStatic @Suppress("UNCHECKED_CAST") fun getChildren(node: LayoutNode): List&lt;LayoutNode></ID>
<ID>ReturnCount:SentryLayoutNodeHelper.kt$SentryLayoutNodeHelper$fun isTransparent(node: LayoutNode): Boolean</ID>
<ID>ReturnCount:ViewHierarchyNode.kt$ViewHierarchyNode.Companion$@JvmStatic fun fromView( view: View, parent: ViewHierarchyNode?, distance: Int, options: SentryMaskingOptions, ): ViewHierarchyNode</ID>
<ID>ReturnCount:ViewHierarchyNode.kt$ViewHierarchyNode.Companion$private fun View.shouldMask(options: SentryMaskingOptions): Boolean</ID>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,8 @@ internal object ComposeViewHierarchyNode {
}

try {
val rootNode = (view as? Owner)?.root ?: return false
val rootNode =
(view as? Owner)?.root ?: error("${view::class.java.name} is not a Compose Owner")
rootNode.traverse(parent, isComposeRoot = true, options, logger)
} catch (e: Throwable) {
logger.log(
Expand All @@ -300,11 +301,28 @@ internal object ComposeViewHierarchyNode {
.trimIndent(),
)
// fail fast in our own sample/UI-test apps (see SentryReplayDebug), so regressions surface
// as crashes instead of silently skipping the whole Compose subtree (i.e. not masking it)
// as crashes instead of a fully masked Compose view
if (SentryReplayDebug.failFast) {
throw e
}
return false
// We can't tell which parts of the Compose view are sensitive, so we mask all of it,
// regardless of the masking options
parent.children =
listOf(
GenericViewHierarchyNode(
x = parent.x,
y = parent.y,
width = parent.width,
height = parent.height,
elevation = parent.elevation,
distance = 0,
parent = parent,
shouldMask = true,
isImportantForContentCapture = true,
isVisible = parent.isVisible,
visibleRect = parent.visibleRect,
),
)
}

return true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ import java.lang.reflect.Method
* This class is not thread-safe, as Compose UI operations are expected to be performed on the main
* thread.
*
* Compiled against Compose >= 1.10 where the mangled names use the "ui" module suffix (e.g.
* getChildren$ui()). For apps still on Compose < 1.10 (where the suffix is "$ui_release"), the
* direct call will throw [NoSuchMethodError] and we fall back to reflection-based accessors that
* are resolved and cached on first use.
* The internal `children` and `outerCoordinator` aren't called directly, as Kotlin mangles their
* JVM names with a module suffix that changed between Compose versions (`$ui_release` before 1.10,
* `$ui` in 1.10 - 1.12, `$androidx_compose_ui_ui` since 1.13). Since Compose 1.8, LayoutNode
* implements `SemanticsInfo`, whose unmangled `childrenInfo` and `isTransparent()` call them from
* within the Compose version the app ships. For apps on Compose < 1.8 the direct call will throw
* [NoSuchMethodError] and we fall back to reflection-based accessors on the `$ui_release` names,
* that are resolved and cached on first use.
*/
internal object SentryLayoutNodeHelper {
private class Fallback(val getChildren: Method?, val getOuterCoordinator: Method?)
Expand All @@ -37,16 +40,17 @@ internal object SentryLayoutNodeHelper {
}
}

@JvmStatic
@Suppress("UNCHECKED_CAST")
fun getChildren(node: LayoutNode): List<LayoutNode> {
when (useFallback) {
false -> return node.children
false -> return node.childrenInfo as List<LayoutNode>
true -> {
return getFallback().getChildren!!.invoke(node) as List<LayoutNode>
}
null -> {
try {
return node.children.also { useFallback = false }
return (node.childrenInfo as List<LayoutNode>).also { useFallback = false }
} catch (_: NoSuchMethodError) {
useFallback = true
return getFallback().getChildren!!.invoke(node) as List<LayoutNode>
Expand All @@ -57,15 +61,15 @@ internal object SentryLayoutNodeHelper {

fun isTransparent(node: LayoutNode): Boolean {
when (useFallback) {
false -> return node.outerCoordinator.isTransparent()
false -> return node.isTransparent()
true -> {
val fb = getFallback()
val coordinator = fb.getOuterCoordinator!!.invoke(node) as NodeCoordinator
return coordinator.isTransparent()
}
null -> {
try {
return node.outerCoordinator.isTransparent().also { useFallback = false }
return node.isTransparent().also { useFallback = false }
} catch (_: NoSuchMethodError) {
useFallback = true
val fb = getFallback()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
package io.sentry.android.replay.viewhierarchy

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
Expand All @@ -32,13 +36,15 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.test.ext.junit.runners.AndroidJUnit4
import coil.compose.AsyncImage
import com.google.common.truth.Truth.assertThat
import io.sentry.NoOpLogger
import io.sentry.SentryOptions
import io.sentry.android.replay.maskAllImages
import io.sentry.android.replay.maskAllText
import io.sentry.android.replay.sentryReplayMask
import io.sentry.android.replay.sentryReplayUnmask
import io.sentry.android.replay.util.ComposeTextLayout
import io.sentry.android.replay.util.MaskRenderer
import io.sentry.android.replay.util.traverse
import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.GenericViewHierarchyNode
import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.ImageViewHierarchyNode
Expand Down Expand Up @@ -287,6 +293,74 @@ class ComposeMaskingOptionsTest {
assertTrue(genericNodes.none { it.shouldMask })
}

@Test
fun `when walking the Compose tree throws a LinkageError, the whole Compose view is masked`() {
assertComposeViewFullyMaskedWhenGetChildrenThrows(NoSuchMethodError())
}

@Test
fun `when walking the Compose tree throws a RuntimeException, the whole Compose view is masked`() {
assertComposeViewFullyMaskedWhenGetChildrenThrows(IllegalStateException())
}

@Test
fun `when a Compose view has no Owner, the whole view is masked`() {
val activity = buildActivity(ComponentActivity::class.java).setup()
val composeView = AndroidComposeViewWithoutOwner(activity.get())
activity.get().setContentView(composeView)
shadowOf(Looper.getMainLooper()).idle()
val options =
SentryOptions().apply {
sessionReplay.maskAllText = false
sessionReplay.maskAllImages = false
}
val composeViewNode = ViewHierarchyNode.fromView(composeView, null, 0, options.sessionReplay)

val handled =
ComposeViewHierarchyNode.fromView(
composeView,
composeViewNode,
options.sessionReplay,
NoOpLogger.getInstance(),
)

assertTrue(handled)
assertThat(composeViewNode.renderMasks()).containsExactly(composeViewNode.visibleRect)
}

private fun assertComposeViewFullyMaskedWhenGetChildrenThrows(error: Throwable) {
val activity = buildActivity(ComposeMaskingOptionsActivity::class.java).setup()
shadowOf(Looper.getMainLooper()).idle()
val options =
SentryOptions().apply {
sessionReplay.maskAllText = false
sessionReplay.maskAllImages = false
}
val composeView = assertNotNull(activity.get().window.decorView.lookupComposeView())
val composeViewNode = ViewHierarchyNode.fromView(composeView, null, 0, options.sessionReplay)

val handled =
Mockito.mockStatic(SentryLayoutNodeHelper.javaClass).use {
mock: MockedStatic<SentryLayoutNodeHelper> ->
mock.`when`<Any> { SentryLayoutNodeHelper.getChildren(any<LayoutNode>()) }.thenThrow(error)

ComposeViewHierarchyNode.fromView(
composeView,
composeViewNode,
options.sessionReplay,
NoOpLogger.getInstance(),
)
}

assertTrue(handled)
assertThat(composeViewNode.renderMasks()).containsExactly(composeViewNode.visibleRect)
}

private fun ViewHierarchyNode.renderMasks(): List<Rect> {
val bitmap = Bitmap.createBitmap(1000, 2000, Bitmap.Config.ARGB_8888)
return MaskRenderer().use { it.renderMasks(bitmap, this) }
}

private inline fun <reified T> Activity.collectNodesOfType(options: SentryOptions): List<T> {
val root = window.decorView
val viewHierarchy = ViewHierarchyNode.fromView(root, null, 0, options.sessionReplay)
Expand Down Expand Up @@ -319,6 +393,8 @@ class ComposeMaskingOptionsTest {
}
}

private class AndroidComposeViewWithoutOwner(context: Context) : FrameLayout(context)

private class ComposeMaskingOptionsActivity : ComponentActivity() {
companion object {
var textModifierApplier: (() -> Modifier)? = null
Expand Down
Loading