diff --git a/CHANGELOG.md b/CHANGELOG.md index b83b1238ba2..f9851e542b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,12 @@ ### Fixes -- Nav3: `sentry-android-navigation3` no longer declares a dependency on `androidx.lifecycle:lifecycle-runtime-compose`. Nav3 apps already depend on it via `navigation3-ui`, so no app changes are necessary ([#6699](https://github.com/getsentry/sentry-java/pull/6699)) - Profiling: No longer crash on API 35+ devices whose framework can't load `ProfilingManager`. Perfetto profiling is turned off on those devices instead ([#6742](https://github.com/getsentry/sentry-java/pull/6742)) +### Dependencies + +- Nav3: `sentry-android-navigation3` no longer declares a dependency on `androidx.lifecycle:lifecycle-runtime-compose`. Nav3 apps already depend on it via `navigation3-ui`, so no app changes are necessary ([#6699](https://github.com/getsentry/sentry-java/pull/6699)) + ## 8.65.1 ### Fixes diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index fab767c4bf8..7a6cf51d181 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -87,6 +87,7 @@ dependencies { testImplementation(libs.androidx.test.ext.junit) testImplementation(libs.androidx.viewpager2) testImplementation(libs.google.truth) + testImplementation(libs.kotlin.test.junit) testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) testImplementation(libs.roboelectric) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index aa012117158..b977c6fccc9 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt @@ -91,7 +91,8 @@ public class SentryBackStackEntry( * - [CharSequence] * - [Char] * - [Boolean] - * - any [Number] (`NaN` and infinite values are sent as strings) + * - any [Number] (`NaN` and infinite values are sent as the strings `"NaN"`, `"Infinity"`, and + * `"-Infinity"`, which JSON can represent) * - enums (via [Enum.name]) * - `null` * @@ -109,9 +110,9 @@ public class SentryBackStackEntry( * All non-supported argument types are stringified via `toString()`, as are map keys. * * No arguments will be recorded for a back stack entry if [map] throws or returns `null`, or if its - * arguments are cyclic, too deeply nested, too large, or contain map keys that stringify to the - * same string. If the SDK drops an entry's arguments, it adds a `dropped_by_sentry` field and - * corresponding reason (e.g., `duplicate_key`) in the Sentry UI. + * arguments are cyclic, too deeply nested, or too large, or contain a map with two keys that are + * stringified the same way (e.g., `1` and `"1"`). If the SDK drops an entry's arguments, it adds a + * `dropped_by_sentry` field and corresponding reason (e.g., `duplicate_key`) in the Sentry UI. * * **Using kotlinx.serialization** * diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index 0a70af1ac31..e15194da1c2 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt @@ -1,5 +1,6 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.compose.runtime.snapshots.Snapshot import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper @@ -26,7 +27,7 @@ import java.util.IdentityHashMap * **Threading policy** * * This class performs work synchronously on the calling thread. The host app's - * [BackStackEntryMapper] is invoked on that same thread and should remain small, non-blocking, and + * `BackStackEntryMapper` is invoked on that same thread and should remain small, non-blocking, and * safe for the caller's threading context. */ internal class BackStackConverter( @@ -86,7 +87,12 @@ internal class BackStackConverter( } val sanitizedArguments = - info.arguments?.let(sanitizer::sanitizeEntry) ?: SanitizedArguments(emptyMap()) + info.arguments?.let { arguments -> + // Argument conversion may read Compose state through host app code. Suppress read + // observation so changes to that state don't trigger recomposition solely b/c our + // telemetry code read it. + Snapshot.withoutReadObservation { sanitizer.sanitizeEntry(arguments) } + } ?: SanitizedArguments(emptyMap()) val formattedName = NormalizedSentryBackStackEntry.formatName(info.name) return if (formattedName.isBlank()) { @@ -303,18 +309,19 @@ internal class BackStackConverter( override fun fillInStackTrace(): Throwable = this } - private companion object { + companion object { - private const val MAX_CHARACTER_WARNING = - "Nav3 arguments exceeded the maximum total character count for one backstack update. Skipping " + - "arguments for this and older captured entries." + const val MAX_CHARACTER_WARNING = + "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + + "this and older entries." - private const val MAX_COUNT_WARNING = - "Nav3 arguments exceeded the maximum total count for one backstack update. Skipping arguments for " + - "this and older captured entries." + const val MAX_COUNT_WARNING = + "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + + "and older entries." - private const val STRUCTURE_WARNING = - "Nav3 argument sanitization failed (possibly a cyclic or deeply nested structure). Skipping arguments." + const val STRUCTURE_WARNING = + "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + + "entry's arguments." } } @@ -332,8 +339,7 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper returned a blank name while processing this back stack update. " + - "Using $UNKNOWN_ENTRY_NAME instead.", + "Nav3 backStackEntryMapper returned a blank name. Using $UNKNOWN_ENTRY_NAME.", ) hasLoggedInvalidNameWarning = true } @@ -345,8 +351,7 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper threw while resolving an entry. " + - "Using $UNKNOWN_ENTRY_NAME without arguments instead.", + "Nav3 backStackEntryMapper threw. Using $UNKNOWN_ENTRY_NAME without arguments.", throwable, ) hasLoggedMapperFailureWarning = true @@ -359,10 +364,8 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this back " + - "stack update. Falling back to toString(). Use String, CharSequence, Char, Number, " + - "Boolean, Enum, Map, Collection, object Array, and primitive array values for reliable " + - "results.", + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper.", typeName, ) hasLoggedUnsupportedValueWarning = true diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt index 8cf28a3a3fd..988000c6b67 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt @@ -1,7 +1,10 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.lifecycle.LifecycleEventObserver import io.sentry.Breadcrumb import io.sentry.Hint +import io.sentry.IScope +import io.sentry.IScopes import io.sentry.SentryIntegrationPackageStorage import io.sentry.SentryLevel.INFO import io.sentry.SentryOptions @@ -16,6 +19,9 @@ import io.sentry.compose.navigation3.internal.lifecycle.INavScope import io.sentry.compose.navigation3.internal.lifecycle.INavScopes import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_CONTEXT_KEY import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_OP +import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator +import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo +import io.sentry.compose.navigation3.internal.lifecycle.NavScopes import io.sentry.compose.navigation3.internal.lifecycle.NavTransactionRequest import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion import java.lang.ref.WeakReference @@ -379,3 +385,70 @@ private class NavBreadcrumbs(private val scopes: INavScopes) { scopes.addBreadcrumb(breadcrumb, hint) } } + +/** + * A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with those of + * other `BackStackObserver`s. + * + * Coordination is achieved via [NavScopes]. + * + * **Usage** + * + * Call [attach] before the first [onBackStackChanged], and call [dispose] when observation ends. + * + * Instances targeting the same [IScope] must be created with the same [NavLeaseCoordinator]. + * + * **Thread safety** + * + * This class is ***not*** thread-safe. Invocations should be confined to the same thread as the + * [LifecycleEventObserver] callbacks through which the [NavLeaseCoordinator] observes the attached + * lifecycle. + */ +internal class CoordinatedBackStackObserver( + scopes: IScopes, + options: SentryNavOptions, + entryMapper: ForwardingBackStackEntryMapper, + coordinator: NavLeaseCoordinator, +) { + + private val navScopes = NavScopes(scopes, coordinator) + private val observer = BackStackObserver(navScopes, options, entryMapper) + + fun attach(rootInfo: NavRootInfo) { + navScopes.attach(rootInfo) + } + + fun onBackStackChanged(backStack: List) { + navScopes.onBackStackUpdate() + observer.onBackStackChanged(backStack) + } + + fun dispose() { + // Call disposal on both the observer and navScopes in case their (currently overlapping) + // implementations drift over time. + observer.dispose() + navScopes.dispose() + } +} + +/** + * The [NavLeaseCoordinator] shared by default by all [CoordinatedBackStackObserver]s. + * + * **Lifetime** + * + * The default coordinator lives as long as the process, since lease state follows nav root + * lifecycles rather than the SDK's. Closing and re-initializing the SDK doesn't require a reset + * because: + * + * - `SentryNavEffect` resolves the current scopes on every call; + * + * - while the SDK is closed, bookkeeping continues without a scope; and + * + * - unpublishing compares by reference, so values published to an earlier scope don't affect the + * current one. + * + * Limitation: A nav transaction that's still running when the SDK is closed and re-initialized can + * be bound to the new scope the next time it's published, although its client has been closed. + * Spans then attach to it, and are lost, until it times out or the next navigation finishes it. + */ +internal val defaultNavLeaseCoordinator: NavLeaseCoordinator = NavLeaseCoordinator() diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt deleted file mode 100644 index a7d30a998f3..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt +++ /dev/null @@ -1,76 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack - -import androidx.lifecycle.LifecycleEventObserver -import io.sentry.IScope -import io.sentry.IScopes -import io.sentry.compose.navigation3.SentryNavOptions -import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator -import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo -import io.sentry.compose.navigation3.internal.lifecycle.NavScopes - -/** - * A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with those of - * other `BackStackObserver`s. - * - * Coordination is achieved via [NavScopes]. - * - * **Usage** - * - * Call [attach] before the first [onBackStackChanged], and call [dispose] when observation ends. - * - * Instances targeting the same [IScope] must be created with the same [NavLeaseCoordinator]. - * - * **Thread safety** - * - * This class is ***not*** thread-safe. Invocations should be confined to the same thread as the - * [LifecycleEventObserver] callbacks through which the [NavLeaseCoordinator] observes the attached - * lifecycle. - */ -internal class CoordinatedBackStackObserver( - scopes: IScopes, - options: SentryNavOptions, - entryMapper: ForwardingBackStackEntryMapper, - coordinator: NavLeaseCoordinator, -) { - - private val navScopes = NavScopes(scopes, coordinator) - private val observer = BackStackObserver(navScopes, options, entryMapper) - - fun attach(rootInfo: NavRootInfo) { - navScopes.attach(rootInfo) - } - - fun onBackStackChanged(backStack: List) { - navScopes.onBackStackUpdate() - observer.onBackStackChanged(backStack) - } - - fun dispose() { - // Call disposal on both the observer and navScopes in case their (currently overlapping) - // implementations drift over time. - observer.dispose() - navScopes.dispose() - } -} - -/** - * The [NavLeaseCoordinator] shared by default by all [CoordinatedBackStackObserver]s. - * - * **Lifetime** - * - * The default coordinator lives as long as the process, since lease state follows nav root - * lifecycles rather than the SDK's. Closing and re-initializing the SDK doesn't require a reset - * because: - * - * - `SentryNavEffect` resolves the current scopes on every call; - * - * - while the SDK is closed, bookkeeping continues without a scope; and - * - * - unpublishing compares by reference, so values published to an earlier scope don't affect the - * current one. - * - * Limitation: A nav transaction that's still running when the SDK is closed and re-initialized can - * be bound to the new scope the next time it's published, although its client has been closed. - * Spans then attach to it, and are lost, until it times out or the next navigation finishes it. - */ -internal val defaultNavLeaseCoordinator: NavLeaseCoordinator = NavLeaseCoordinator() diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md new file mode 100644 index 00000000000..bc8bb10067e --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md @@ -0,0 +1,22 @@ +# `io.sentry.compose.navigation3.internal.backstack` + +This package converts a host app's back stack into Sentry navigation data: screen names, navigation +breadcrumbs, transactions, and the captured back stack. + +## Mapping and sanitization + +The host app's `BackStackEntryMapper` supplies each entry's name and optional arguments in a +`SentryBackStackEntry`. Properties are the fields and values on the host's back stack entry; +arguments are the values the mapper chooses to expose as `SentryBackStackEntry.arguments`. + +Arguments are the mapper's output before sanitization. `BackStackConverter` normalizes entry names +and sanitizes arguments before they are recorded. Sanitization can stringify values or drop an +entry's arguments when they are invalid or exceed the limits in `ArgumentConstraints`. +The value and character budgets are shared across the entries captured in one back stack update. + +## Observation and coordination + +`BackStackObserver` detects changes and records navigation data for one back stack. +`CoordinatedBackStackObserver` connects that observer to `NavScopes`, which coordinates access to +shared scope state with other navigation roots. The lifecycle and ownership rules live in the +[sibling lifecycle package](../lifecycle/README.md). diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md index c7fe450590d..d4161499e1d 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md @@ -7,6 +7,11 @@ This package is meant to encapsulate knowledge about the possibility of multiple raises. Addressing those concerns is complicated. Confining them here makes them easier to reason about and easier to swap for alternative logic should we someday need to. +## Dependencies + +This package may ***not*** depend on any other `io.sentry.compose.navigation3` package, Compose, or +`androidx.navigation3`. It may use Android framework and AndroidX Lifecycle APIs directly. + ## Limitations Support for multiple `SentryNavEffect`s is restricted to the scenarios documented in the diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt index 34801621011..ae1750f00dc 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt @@ -93,7 +93,9 @@ internal class StagedNavData { * Clears the screen and nav context this instance published, unless something else has replaced * them in [realScope] since. */ + @Suppress("AvoidReferentialEquality") fun clearPublishedStateFrom(realScope: IScope) { + // Identity tracks the screen we published; equal but distinct host replacements must survive. if (publishedScreen != null && realScope.screen === publishedScreen) { realScope.screen = null } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt new file mode 100644 index 00000000000..2ba320a31e8 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -0,0 +1,103 @@ +package io.sentry.compose.navigation3 + +import com.google.common.truth.Truth.assertThat +import java.io.File +import org.junit.Test + +/** Enforces the lifecycle package's dependency boundary. */ +class PackageBoundariesTest { + + private val sources: List = + File(SOURCE_ROOT) + .walkTopDown() + .filter { it.isFile && it.extension == "kt" } + .map(SourceFile::parse) + .toList() + + @Test + fun `the lifecycle package has no imports from other Sentry navigation3 packages, Compose, or AndroidX Nav3`() { + val lifecycleSources = sources.filter { it.packageName.isIn(LIFECYCLE) } + + val violations = lifecycleSources.importsMatching { + (it.isIn(ROOT) && !it.isIn(LIFECYCLE)) || + it.isIn("androidx.navigation3") || + (it.isIn("androidx") && "compose" in it.split('.')) + } + + assertThat(lifecycleSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + // Check that the import reader finds the declarations the rules inspect. + + @Test + fun `reads the package and the targets of plain, aliased, and wildcard imports`() { + val file = File.createTempFile("Parsed", ".kt").apply { deleteOnExit() } + file.writeText( + """ + |@file:Suppress("unused") + | + |package com.example.feature + | + |import com.example.Plain + |import com.example.wildcard.* + |import com.example.Original as Alias + | + |class Parsed + """ + .trimMargin(), + ) + + val parsed = SourceFile.parse(file) + + assertThat(parsed.packageName).isEqualTo("com.example.feature") + assertThat(parsed.imports) + .containsExactly("com.example.Plain", "com.example.wildcard", "com.example.Original") + .inOrder() + } + + @Test + fun `reads imports from the module's Kotlin sources`() { + val imports = sources.flatMap { it.imports } + + assertThat(imports).contains("androidx.lifecycle.LifecycleOwner") + } + + /** A source file's location, package, and import targets. */ + private class SourceFile( + val path: String, + val packageName: String, + val imports: List, + ) { + companion object { + private val PACKAGE = Regex("""^package\s+([\w.]+)""") + private val IMPORT = Regex("""^import\s+([\w.]+?)(?:\.\*)?(?:\s+as\s+\w+)?\s*;?\s*$""") + + fun parse(file: File): SourceFile { + val lines = file.readLines().map(String::trim) + return SourceFile( + path = file.invariantSeparatorsPath, + packageName = + lines.firstNotNullOfOrNull { PACKAGE.find(it)?.groupValues?.get(1) }.orEmpty(), + imports = lines.mapNotNull { IMPORT.find(it)?.groupValues?.get(1) }, + ) + } + } + } + + private companion object { + const val SOURCE_ROOT = "src/main/kotlin" + const val ROOT = "io.sentry.compose.navigation3" + const val LIFECYCLE = "$ROOT.internal.lifecycle" + + /** Whether this name is [packageName] or lies inside it. */ + fun String.isIn(packageName: String): Boolean = + this == packageName || startsWith("$packageName.") + + /** Each import matching [isForbidden], as `path: name`. */ + fun List.importsMatching(isForbidden: (String) -> Boolean): List = + flatMap { file -> + file.imports.filter(isForbidden).map { "${file.path}: $it" } + } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt new file mode 100644 index 00000000000..d9f0f76864a --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt @@ -0,0 +1,239 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel.WARNING +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.ArgumentSanitizer +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.SanitizedArguments +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.WarningState +import kotlin.test.assertFailsWith +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify + +class ArgumentSanitizerTest { + + private class OpaqueValue { + override fun toString(): String = "opaque-value" + } + + private class ThrowingValue(val failure: IllegalStateException = IllegalStateException("boom")) { + @Suppress("ExceptionRaisedInUnexpectedLocation") override fun toString(): String = throw failure + } + + private val logger = mock() + private val sanitizer = ArgumentSanitizer(logger, WarningState()) + + private val laterArguments = mapOf("id" to "123") + + private companion object { + private const val UNSUPPORTED_VALUE_WARNING = + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper." + } + + // Plain maps + + @Test + fun `sanitizeEntry() - returns the arguments of a plain map as written`() { + val arguments = + mapOf("id" to "123", "filters" to mapOf("tags" to listOf("a", "b")), "page" to 2) + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized).isEqualTo(SanitizedArguments(arguments)) + } + + @Test + fun `sanitizeEntry() - returns empty arguments without a drop reason for an empty map`() { + val sanitized = sanitizer.sanitizeEntry(emptyMap()) + + assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), dropReason = null)) + } + + // Unsupported values + + @Test + fun `sanitizeEntry() - logs the unsupported value warning with the value type`() { + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) + + verify(logger).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue")) + } + + @Test + fun `the unsupported value warning is logged once across entries sanitized by one sanitizer`() { + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue(), "alsoOpaque" to OpaqueValue())) + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) + + verify(logger, times(1)).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue")) + } + + // Dropped arguments + + @Test + fun `sanitizeEntry() - drops arguments over the value budget and logs the value budget warning`() { + // The list and its elements are one value more than the budget. + val sanitized = sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES) { it })) + + assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_COUNT_WARNING)) + } + + @Test + fun `sanitizeEntry() - drops arguments over the character budget and logs the character budget warning`() { + // The key and the value are one character more than the budget. + val sanitized = sanitizer.sanitizeEntry(mapOf("v" to "x".repeat(MAX_ARGUMENT_CHARACTERS))) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + } + + @Test + fun `an entry whose own map contains itself is dropped without writing its contents again`() { + // The entry's own map is the cycle check's root, so "self" is rejected as soon as it begins, + // once the 30 scalars and "self" have spent 31 values. Otherwise its contents would be written + // once more before the cycle is found, spending another 31 values of the shared budget. + val selfContaining = mutableMapOf() + repeat(30) { selfContaining["k$it"] = it } + selfContaining["self"] = selfContaining + // A list and its elements, which spend exactly the values left. + val rest = mapOf("values" to List(MAX_ARGUMENT_VALUES - 31 - 1) { it }) + + val dropped = sanitizer.sanitizeEntry(selfContaining) + val later = sanitizer.sanitizeEntry(rest) + + assertThat(dropped) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + assertThat(later).isEqualTo(SanitizedArguments(rest)) + } + + // Budgets shared across entries + + @Test + fun `entries sanitized by one sanitizer share the value budget`() { + // Each of the first two entries uses half of the value budget: a list and its elements. + val half = MAX_ARGUMENT_VALUES / 2 + val first = sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + val second = sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + val third = sanitizer.sanitizeEntry(mapOf("one" to 1)) + + assertThat(first.dropReason).isNull() + assertThat(second.dropReason).isNull() + assertThat(third).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `entries sanitized by one sanitizer share the character budget`() { + // Each of the first two entries uses half of the character budget: a key and its value. + val half = MAX_ARGUMENT_CHARACTERS / 2 + val first = sanitizer.sanitizeEntry(mapOf("a" to "x".repeat(half - 1))) + val second = sanitizer.sanitizeEntry(mapOf("b" to "x".repeat(half - 1))) + val third = sanitizer.sanitizeEntry(mapOf("c" to null)) + + assertThat(first.dropReason).isNull() + assertThat(second.dropReason).isNull() + assertThat(third).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + // Failures + + @Test + fun `sanitizeEntry() - drops arguments for a sanitization failure when a value throws`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("ok" to 1, "throwing" to ThrowingValue())) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED)) + } + + @Test + fun `sanitizeEntry() - logs the structure warning with the exception when a value throws`() { + val throwing = ThrowingValue() + + sanitizer.sanitizeEntry(mapOf("throwing" to throwing)) + + verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), eq(throwing.failure)) + } + + @Test + fun `sanitizeEntry() - rethrows fatal errors thrown during sanitization`() { + val fatal = + object { + override fun toString(): String = throw StackOverflowError("fatal") + } + + assertFailsWith { + sanitizer.sanitizeEntry(mapOf("fatal" to fatal)) + } + verify(logger, never()) + .log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), any()) + } + + @Test + fun `a container from an entry that failed sanitization isn't treated as a cycle in later entries`() { + val holder = mutableListOf(ThrowingValue()) + sanitizer.sanitizeEntry(mapOf("holder" to holder)) + holder.clear() + + val sanitized = sanitizer.sanitizeEntry(mapOf("holder" to holder)) + + assertThat(sanitized).isEqualTo(SanitizedArguments(mapOf("holder" to emptyList()))) + } + + // Later entries after a drop + + @Test + fun `entries after the value budget is exhausted are dropped without another warning`() { + sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES) { it })) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + verify(logger, times(1)).log(eq(WARNING), eq(ArgumentSanitizer.MAX_COUNT_WARNING)) + } + + @Test + fun `entries after the character budget is exhausted are dropped without another warning`() { + sanitizer.sanitizeEntry(mapOf("v" to "x".repeat(MAX_ARGUMENT_CHARACTERS))) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + verify(logger, times(1)).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + } + + @Test + fun `an entry dropped for invalid structure doesn't drop later entries`() { + val cyclic = mutableListOf() + cyclic.add(cyclic) + sanitizer.sanitizeEntry(mapOf("cyclic" to cyclic)) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + + @Test + fun `an entry dropped for a duplicate map key doesn't drop later entries`() { + sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", "1" to "b"))) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + + @Test + fun `an entry that failed sanitization doesn't drop later entries`() { + sanitizer.sanitizeEntry(mapOf("throwing" to ThrowingValue())) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index 9799eee8357..d07f3733118 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -1,18 +1,26 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat import io.sentry.ILogger +import io.sentry.JsonSerializer import io.sentry.SentryLevel.WARNING +import io.sentry.SentryOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import java.io.StringWriter import java.util.AbstractCollection +import kotlin.test.assertFailsWith import org.junit.Test +import org.mockito.kotlin.any import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify @@ -33,6 +41,16 @@ class BackStackConverterTest { private val logger = mock() + private companion object { + const val BLANK_NAME_WARNING = + "Nav3 backStackEntryMapper returned a blank name. Using /unknown." + const val MAPPER_FAILURE_WARNING = + "Nav3 backStackEntryMapper threw. Using /unknown without arguments." + const val UNSUPPORTED_VALUE_WARNING = + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper." + } + private val defaultEntryMapper = BackStackEntryMapper { entry -> SentryBackStackEntry(entry::class.simpleName ?: "") @@ -95,7 +113,7 @@ class BackStackConverterTest { } @Test - fun `convert preserves input order when top entry is first`() { + fun `convert with KEEP_FIRST returns entries in back stack order`() { val sut = getSut() val routes = @@ -114,20 +132,20 @@ class BackStackConverterTest { } @Test - fun `convert preserves input order when top entry is last`() { + fun `convert with KEEP_LAST returns entries in back stack order`() { val sut = getSut() val routes = sut.convert( - listOf(HomeScreen(), ProfileScreen("123"), SettingsScreen("privacy")), - RetentionPolicy.KEEP_FIRST, + listOf(SettingsScreen("privacy"), ProfileScreen("123"), HomeScreen()), + RetentionPolicy.KEEP_LAST, ) assertThat(routes) .containsExactly( - NormalizedSentryBackStackEntry("/HomeScreen"), - NormalizedSentryBackStackEntry("/ProfileScreen"), NormalizedSentryBackStackEntry("/SettingsScreen"), + NormalizedSentryBackStackEntry("/ProfileScreen"), + NormalizedSentryBackStackEntry("/HomeScreen"), ) .inOrder() } @@ -320,13 +338,19 @@ class BackStackConverterTest { verify(logger) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper returned a blank name while processing this back stack update. " + - "Using /unknown instead.", - ), + eq(BLANK_NAME_WARNING), ) } + @Test + fun `convert logs the blank name warning once per back stack update`() { + val sut = getSut(entryMapper = { SentryBackStackEntry(" ") }) + + sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + + verify(logger, times(1)).log(eq(WARNING), eq(BLANK_NAME_WARNING)) + } + @Test fun `convert returns unknown name without arguments if mapper returns null`() { val sut = getSut(entryMapper = { null }) @@ -349,13 +373,28 @@ class BackStackConverterTest { verify(logger) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper threw while resolving an entry. Using /unknown without arguments instead.", - ), - org.mockito.kotlin.any(), + eq(MAPPER_FAILURE_WARNING), + any(), ) } + @Test + fun `convert logs the mapper failure warning once per back stack update`() { + val sut = getSut(entryMapper = { error("boom") }) + + sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + + verify(logger, times(1)).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + } + + @Test + fun `convert rethrows fatal errors thrown by the mapper`() { + val sut = getSut(entryMapper = { throw StackOverflowError("fatal") }) + + assertFailsWith { sut.convert(HomeScreen()) } + verify(logger, never()).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + } + @Test fun `convert returns arguments in proper serializable form`() { val text = StringBuilder("hello") @@ -471,18 +510,31 @@ class BackStackConverterTest { verify(logger, times(1)) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this " + - "back stack update. Falling back to toString(). Use String, CharSequence, Char, " + - "Number, Boolean, Enum, Map, Collection, object Array, and primitive array values " + - "for reliable results.", - ), + eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue"), ) } @Test - fun `unsupported value warning can recur with a fresh update state`() { + fun `convert hides state reads during argument sanitization from snapshot observation`() { + val arguments = mutableStateMapOf("state" to "value") + val sut = getSut(entryMapper = { entry -> entryInfo(entry, arguments) }) + val observedReads = mutableListOf() + val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) + + val converted = + try { + snapshot.enter { sut.convert(HomeScreen()) } + } finally { + snapshot.dispose() + } + + assertThat(converted.arguments).isEqualTo(mapOf("state" to "value")) + assertThat(observedReads).isEmpty() + } + + @Test + fun `convert logs the unsupported value warning again in a later back stack update`() { class OpaqueValue { override fun toString(): String = "opaque-value" } @@ -497,12 +549,7 @@ class BackStackConverterTest { verify(logger, times(1)) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this " + - "back stack update. Falling back to toString(). Use String, CharSequence, Char, " + - "Number, Boolean, Enum, Map, Collection, object Array, and primitive array values " + - "for reliable results.", - ), + eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue"), ) } @@ -555,6 +602,18 @@ class BackStackConverterTest { assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) } + @Test + fun `convert starts each back stack update with a fresh argument budget`() { + val sut = + getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(150) { it })) }) + + sut.convert(HomeScreen()) + val entry = sut.convert(HomeScreen()) + + assertThat(entry.arguments).isEqualTo(mapOf("values" to List(150) { it })) + assertThat(entry.argumentDropReason).isNull() + } + @Test fun `convert reports sanitization failures`() { class ThrowingValue { @@ -627,6 +686,31 @@ class BackStackConverterTest { .inOrder() } + @Test + fun `converted entries with non-finite number arguments serialize to valid JSON through Sentry's JSON serializer`() { + val sut = + getSut( + entryMapper = { entry -> + entryInfo( + entry, + mapOf( + "price" to Double.NaN, + "limits" to floatArrayOf(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), + ), + ) + }, + ) + val serializedEntry = sut.convert(HomeScreen()).serialize() + val json = StringWriter() + + JsonSerializer(SentryOptions()).serialize(serializedEntry, json) + + assertThat(json.toString()) + .isEqualTo( + """{"entry":"/HomeScreen","entry_arguments":{"price":"NaN","limits":["Infinity","-Infinity"]}}""", + ) + } + @Test fun `serialize includes the reason arguments were dropped`() { val entry = diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt index 6f56285b496..d0546d7adea 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt @@ -40,6 +40,19 @@ class ForwardingBackStackEntryMapperTest { assertThat(mapped?.arguments).isNull() } + @Test + fun `map() - forwards to the mapper current when map is called`() { + var mapper = BackStackEntryMapper { SentryBackStackEntry("first") } + val sut = ForwardingBackStackEntryMapper { mapper } + val first = sut.map(HomeScreen()) + mapper = BackStackEntryMapper { SentryBackStackEntry("second") } + + val second = sut.map(HomeScreen()) + + assertThat(first).isEqualTo(SentryBackStackEntry("first")) + assertThat(second).isEqualTo(SentryBackStackEntry("second")) + } + @Test fun `mapper forwards null results`() { val sut = ForwardingBackStackEntryMapper { BackStackEntryMapper { null } } diff --git a/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt b/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt index ff52464cb2d..3e904910e7c 100644 --- a/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt @@ -233,4 +233,17 @@ class HttpUtilsTest { Locale.setDefault(originalLocale) } } + + @Test + fun `sensitive data key check matches keys containing denylist terms in any case`() { + assertThat(HttpUtils.containsSensitiveDataKey("authToken")).isTrue() + assertThat(HttpUtils.containsSensitiveDataKey("X-API-KEY")).isTrue() + assertThat(HttpUtils.containsSensitiveDataKey("SessionId")).isTrue() + } + + @Test + fun `sensitive data key check doesn't match keys without denylist terms`() { + assertThat(HttpUtils.containsSensitiveDataKey("productId")).isFalse() + assertThat(HttpUtils.containsSensitiveDataKey("query")).isFalse() + } }