diff --git a/.github/workflows/integration-tests-nav3-r8.yml b/.github/workflows/integration-tests-nav3-r8.yml index 9271eaa18f6..67e13b0644b 100644 --- a/.github/workflows/integration-tests-nav3-r8.yml +++ b/.github/workflows/integration-tests-nav3-r8.yml @@ -1,7 +1,7 @@ name: Nav3 Built-in Back Stack Mappers R8 Check -# Verifies behavior of BackStackEntryMapper.SerialName from sentry-android-navigation3 in -# R8-minified builds on an emulator. Runs tests in: +# Verifies behavior of BackStackEntryMapper.SerialName and SerialNameAndProperties from +# sentry-android-navigation3 in R8-minified builds on an emulator. Runs tests in: # # - R8 full mode against the compile floor of kotlinx-serialization-core and its latest stable # release; and @@ -34,7 +34,7 @@ on: - 'gradle/dependency-matrix.versions.toml' - 'buildSrc/**' - 'build-logic/**' - # Utilities the mapper uses to handle exceptions. + # Utilities the mappers use to handle exceptions and filter sensitive arguments. - 'sentry/src/main/java/io/sentry/util/**' pull_request: paths: *nav3-r8-paths diff --git a/CHANGELOG.md b/CHANGELOG.md index 67b7e9fbe0d..9933642970c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,12 +10,17 @@ ### Features - Nav3: Add `BackStackEntryMapper.SerialName`, a convenience mapper that names back stack entries after their [serial names](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-serial-descriptor/serial-name.html) ([#6703](https://github.com/getsentry/sentry-java/pull/6703)) +- Nav3: Add `BackStackEntryMapper.SerialNameAndProperties`, which is like `SerialName` except that it also records the properties of each back stack entry as arguments ([#6706](https://github.com/getsentry/sentry-java/pull/6706)) ### Improvements - Nav3: Record why a back stack entry is `/unknown` via an `unknown_entry_reason` next to it in the Sentry UI ([#6801](https://github.com/getsentry/sentry-java/pull/6801)) - A `BackStackEntryMapper` that throws now records `"unknown_entry_reason": "mapping_failed"` instead of `"dropped_by_sentry": "mapping_failed"` in the entry's arguments. +### Behavioral Changes + +- Nav3: `SentryNavOptions.maxCapturedBackStackEntries` is now capped at 25, and larger values are treated as 25 ([#6707](https://github.com/getsentry/sentry-java/pull/6707)) + ### Fixes - Session Replay: Stop dropping or freezing video when the device clock changes mid-recording ([#6542](https://github.com/getsentry/sentry-java/pull/6542)) diff --git a/scripts/test-nav3-built-in-back-stack-mappers-r8.sh b/scripts/test-nav3-built-in-back-stack-mappers-r8.sh index 98c7cf43113..122d3fcef31 100755 --- a/scripts/test-nav3-built-in-back-stack-mappers-r8.sh +++ b/scripts/test-nav3-built-in-back-stack-mappers-r8.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -# Verifies BackStackEntryMapper.SerialName in R8-minified builds on a booted emulator or device. +# Verifies BackStackEntryMapper.SerialName and SerialNameAndProperties in R8-minified builds on a +# booted emulator or device. Each APK is launched once per mapper. # See sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md. # # Usage: @@ -12,6 +13,7 @@ module="nav3-built-in-back-stack-mappers-r8-check" moduleDir="sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check" appId="io.sentry.tests.nav3.r8" tag="NAV3_R8_CHECK" +mappers=(SerialName SerialNameAndProperties) copyApk() { cp "${moduleDir}/build/outputs/apk/release/nav3-built-in-back-stack-mappers-r8-check-release.apk" "$1" @@ -47,9 +49,11 @@ build() { done } -# Installs and launches APK $1, prints its check's output, and fails unless the check passed. +# Installs and launches APK $1 to check mapper $2, prints its check's output, and fails unless the +# check passed. runApk() { local apk="$1" + local mapper="$2" adb uninstall "$appId" > /dev/null 2>&1 || true adb install "$apk" > /dev/null || return 1 # Reads only this launch's lines, so the previous APK's RESULT=PASS can't hide a failure. The @@ -57,7 +61,8 @@ runApk() { local since sleep 1 since="$(adb shell "date +'%m-%d %H:%M:%S.000'" | tr -d '\r')" || return 1 - adb shell am start -W -n "${appId}/.BuiltInBackStackMappersActivity" > /dev/null || return 1 + adb shell am start -W -n "${appId}/.BuiltInBackStackMappersActivity" --es mapper "$mapper" \ + > /dev/null || return 1 local output="" for _ in $(seq 1 60); do @@ -78,6 +83,12 @@ runApk() { adb logcat -d -T "$since" -b crash | grep -A 20 "$appId" || true return 1 fi + # The Activity checks SerialName if the extra is missing, so a launch that passed for the wrong + # mapper would otherwise go unnoticed. + if ! sed -E "s/^.*${tag}: //" <<< "$output" | tr -d '\r' | grep -qx "MAPPER=${mapper}"; then + echo "Expected MAPPER=${mapper}, but the Activity checked another mapper." + return 1 + fi } run() { @@ -94,11 +105,13 @@ run() { for apk in "${apks[@]}"; do local name name="$(basename "$apk" .apk)" - echo "=== $name" - if ! runApk "$apk"; then - echo "FAILED: $name" - failed=1 - fi + for mapper in "${mappers[@]}"; do + echo "=== $name ($mapper)" + if ! runApk "$apk" "$mapper"; then + echo "FAILED: $name ($mapper)" + failed=1 + fi + done done if [[ $failed -ne 0 ]]; then diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md index 70d3a616ec5..5637f2343d8 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md @@ -1,10 +1,10 @@ # nav3-built-in-back-stack-mappers-r8-check -Checks that `BackStackEntryMapper.SerialName` works after R8 obfuscation: +Checks that `BackStackEntryMapper.SerialName` and `BackStackEntryMapper.SerialNameAndProperties` work after R8 obfuscation: -- The names and `unknown_entry_reason`s that `SentryNavEffect` records in the `Navigation` context match expectations. -- The mapper's kotlinx.serialization compatibility check passes. -- R8 actually obfuscates a representative class. +- The names, `unknown_entry_reason`s, and arguments that `SentryNavEffect` records in the `Navigation` context match expectations. +- The mappers' kotlinx.serialization compatibility checks pass. +- R8 actually obfuscates a representative class, and the fields of a class whose properties are recorded. The app uses kotlinx.serialization's consumer rules and its own `proguard-rules.pro`; the SDK supplies no keep rules for app serialization classes. @@ -18,7 +18,8 @@ Boot an emulator or device, then run: ``` Versions come from `gradle/dependency-matrix.versions.toml`. Both floor and latestStable run in R8 full mode; floor also runs in compat mode -to cover older named-companion rules. Each APK must report `RESULT=PASS`. +to cover older named-companion rules. Each APK is launched once per mapper (`--es mapper SerialName` or `SerialNameAndProperties`), and +each launch must report `RESULT=PASS`. CI also runs the module's unit tests against latestStable. @@ -31,6 +32,6 @@ upgrade and passing checks. Closing the PR tells Dependabot to ignore that versi compilers may still work. **Test failure:** investigate changes to serializer lookup, serial descriptors, or R8 rules. Fix incorrect names or unexpected `/unknown` -results, then merge the fix with the update. +results or arguments, then merge the fix with the update. Preserve support for the floor in either case; see "Version floor" in the `kotlinx` package README. diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts index 8902055f5d4..de39c52698e 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts @@ -1,4 +1,4 @@ -// Checks BackStackEntryMapper.SerialName in R8-minified release builds. See README.md. +// Checks the built-in BackStackEntryMappers in R8-minified release builds. See README.md. plugins { id("com.android.application") alias(libs.plugins.kotlin.android) diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt index c201a87059e..6d307c5e8da 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt @@ -12,8 +12,11 @@ import io.sentry.compose.navigation3.SentryNavOptions import kotlinx.coroutines.delay /** - * Shows every [Expectation]'s key as one back stack to `SentryNavEffect` with - * `BackStackEntryMapper.SerialName`, and reports the names and reasons it records. + * Shows every [Expectation]'s key as one back stack to `SentryNavEffect` with the built-in mapper + * named by the [MAPPER_EXTRA] intent extra (`BackStackEntryMapper.SerialName` by default), and + * reports the names, reasons, and arguments it records. + * + * Only one `SentryNavEffect` records an Activity's back stack, so each mapper needs its own launch. * * An exception crashes the Activity, which the runner script reports as a failure. */ @@ -23,6 +26,20 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { super.onCreate(savedInstanceState) // Before the mapper's first map() call, which runs its compatibility check. + val mapperName = intent.getStringExtra(MAPPER_EXTRA) ?: SERIAL_NAME + val includeProperties = + when (mapperName) { + SERIAL_NAME -> false + SERIAL_NAME_AND_PROPERTIES -> true + else -> error("Unknown $MAPPER_EXTRA: $mapperName") + } + val mapper = + if (includeProperties) { + BackStackEntryMapper.SerialNameAndProperties + } else { + BackStackEntryMapper.SerialName + } + val logger = RecordingLogger() val recorder = BackStackRecorder() initSentry(this, logger, recorder) @@ -45,7 +62,7 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { } setContent { - SentryNavEffect(backStack, BackStackEntryMapper.SerialName, options) + SentryNavEffect(backStack, mapper, options) LaunchedEffect(Unit) { // The back stack reaches the scope once the effect holds the Activity's nav lease. @@ -55,18 +72,27 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { if (recorded != null) break delay(RECORD_RETRY_MILLIS) } - report(expectations, recorded?.reversed(), logger, recorder.lastEventSummary) + report( + mapperName, + includeProperties, + expectations, + recorded?.reversed(), + logger, + recorder.lastEventSummary, + ) } } } private fun report( + mapperName: String, + includeProperties: Boolean, expectations: List, recorded: List?, logger: RecordingLogger, lastEventSummary: String, ) { - val lines = mutableListOf() + val lines = mutableListOf("MAPPER=$mapperName") var failures = 0 if (recorded?.size != expectations.size) { @@ -83,8 +109,11 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { entry.unknownEntryReason == null val unnamedAsExpected = unnamed && entry.unknownEntryReason in expectation.unknownEntryReasons - // SerialName never returns arguments, so no entry it maps may have any. - val passed = !entry.hasArguments && (namedAsExpected || unnamedAsExpected) + // SerialName returns no arguments, and an unnamed entry has none with either mapper. + val expectedArguments = + if (includeProperties && !unnamed) expectation.expectedArguments else null + val argumentsAsExpected = entry.arguments == expectedArguments + val passed = argumentsAsExpected && (namedAsExpected || unnamedAsExpected) val fellBack = expectation.expected != null && unnamedAsExpected if (!passed) failures++ @@ -93,7 +122,11 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { "${if (passed) "PASS" else "FAIL"} ${expectation.label} " + "(runtime class ${expectation.key.javaClass.name}): " + "expected=${expectation.expected?.let { "/$it" } ?: UNKNOWN} actual=${entry.name}" + - (if (entry.hasArguments) " (has arguments)" else "") + + (if (!argumentsAsExpected) { + " arguments=${entry.arguments} (expected $expectedArguments)" + } else { + "" + }) + (if (unnamed) { " reason=${entry.unknownEntryReason} (expected ${expectation.unknownEntryReasons})" } else if (entry.unknownEntryReason != null) { @@ -114,11 +147,19 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { lines.forEach { Log.i(TAG, it) } } - private companion object { - const val TAG = "NAV3_R8_CHECK" - const val UNKNOWN = "/unknown" - const val RECORD_ATTEMPTS = 50 - const val RECORD_RETRY_MILLIS = 100L + companion object { + /** + * The intent extra that names the mapper to check: [SERIAL_NAME] (the default) or + * [SERIAL_NAME_AND_PROPERTIES]. + */ + const val MAPPER_EXTRA = "mapper" + const val SERIAL_NAME = "SerialName" + const val SERIAL_NAME_AND_PROPERTIES = "SerialNameAndProperties" + + private const val TAG = "NAV3_R8_CHECK" + private const val UNKNOWN = "/unknown" + private const val RECORD_ATTEMPTS = 50 + private const val RECORD_RETRY_MILLIS = 100L } } @@ -128,7 +169,8 @@ class Check(val description: String, val passed: Boolean) /** * A back stack key and the name `SentryNavEffect` should record for it with * [BackStackEntryMapper.SerialName], or `null` if it should be unnamed, with one of - * [unknownEntryReasons]. + * [unknownEntryReasons]. [expectedArguments] are the arguments it should record for a named key + * with [BackStackEntryMapper.SerialNameAndProperties], or `null` if none. * * A key with an [expected] name may also have [unknownEntryReasons], if neither * kotlinx.serialization nor R8 guarantees whether it can be named. It may then instead be recorded @@ -139,6 +181,7 @@ class Expectation( val key: Any, val expected: String?, val unknownEntryReasons: Set = emptySet(), + val expectedArguments: Map? = null, ) { init { require(expected != null || unknownEntryReasons.isNotEmpty()) { diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/CompatibilityLogChecks.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/CompatibilityLogChecks.kt index 5a7c86951b6..649d1de8a2f 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/CompatibilityLogChecks.kt +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/CompatibilityLogChecks.kt @@ -82,13 +82,14 @@ fun compatibilityLogChecks(logger: RecordingLogger): List { } /** - * The prefixes of the messages the mapper logs when its compatibility check fails, or a built-in - * mapper can't be created. + * The prefixes of the messages the mapper logs when one of its compatibility checks fails, or a + * built-in mapper can't be created. * * See `KotlinxMapperDiagnostics` and `BuiltInBackStackEntryMappers` in sentry-android-navigation3. */ private val COMPATIBILITY_MESSAGE_PREFIXES = listOf( "Nav3 couldn't verify kotlinx.serialization compatibility", + "Nav3 SerialNameAndProperties is incompatible", "Nav3 built-in mapper creation failed", ) diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/RecordedBackStack.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/RecordedBackStack.kt index 828cf4baeb2..75f443299b6 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/RecordedBackStack.kt +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/RecordedBackStack.kt @@ -14,7 +14,10 @@ const val SERIALIZER_NOT_FOUND = "serializer_not_found" const val SERIALIZER_ACCESS_THREW = "serializer_access_threw" /** One back stack entry as SentryNavEffect records it in the `Navigation` context. */ -class RecordedEntry(val name: String?, val unknownEntryReason: String?, val hasArguments: Boolean) +class RecordedEntry(val name: String?, val unknownEntryReason: String?, val arguments: Map<*, *>?) { + val hasArguments: Boolean + get() = arguments != null +} /** * Captures the back stack SentryNavEffect records, by reading the `Navigation` context of an event @@ -55,7 +58,7 @@ class BackStackRecorder : SentryOptions.BeforeSendCallback { RecordedEntry( name = fields["entry"] as String?, unknownEntryReason = fields["unknown_entry_reason"] as String?, - hasArguments = "entry_arguments" in fields, + arguments = fields["entry_arguments"] as Map<*, *>?, ) } diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt index b94cf9bd838..df2afdd0c10 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt @@ -3,6 +3,7 @@ package io.sentry.tests.nav3.r8 import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.Transient import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor @@ -33,6 +34,41 @@ enum class SerializableEnum { @Serializable private data class PrivateTopLevelClass(val id: String) +@Serializable +enum class SortOrder { + @SerialName("ascending") ASC, +} + +@Serializable @JvmInline value class Price(val cents: Int) + +@Serializable data class Filter(val sessionId: String, val query: String) + +@Serializable +sealed interface Origin { + @Serializable @SerialName("search") data class Search(val term: String) : Origin + + @Serializable @SerialName("deeplink") data object DeepLink : Origin +} + +/** Uses every encoding rule of `BackStackEntryMapper.SerialNameAndProperties`, plus filtering. */ +@Serializable +data class ArgumentsKey( + val productId: Int, + val quantity: UInt, + val authToken: String, + val price: Price, + val sort: SortOrder, + val tags: List, + val sizes: Set, + val counts: Map, + val filter: Filter, + val filters: List, + val origin: Origin, + val fallbackOrigin: Origin, + val note: String?, + @Transient val cache: String = "not encoded", +) + /** Named by its custom serializer, which the plugin's companion `serializer()` returns. */ @Serializable(with = SlugSerializer::class) class Slug(val value: String) @@ -78,7 +114,7 @@ data class NamedCompanionKey(val id: String) { * Like [NamedCompanionKey], but covered by kotlinx.serialization's named-companion R8 rules * (`proguard-rules.pro`), as the * [troubleshooting docs](https://docs.sentry.io/platforms/android/integrations/navigation/#the-entry-type-has-a-named-companion-object-and-the-app-uses-r8) - * tell apps to add. + * instruct host apps to add. */ @Serializable data class NamedCompanionKeyWithRules(val id: String) { @@ -104,6 +140,7 @@ class Holder { "private nested class", PrivateNestedClass("1"), "io.sentry.tests.nav3.r8.Holder.PrivateNestedClass", + expectedArguments = mapOf("id" to "1"), ), ) } @@ -111,17 +148,69 @@ class Holder { private const val PKG = "io.sentry.tests.nav3.r8" +private val ID_ARGUMENTS = mapOf("id" to "1") + +private val argumentsKey = + ArgumentsKey( + productId = 42, + quantity = UInt.MAX_VALUE, + authToken = "secret", + price = Price(999), + sort = SortOrder.ASC, + tags = listOf("a", "b"), + sizes = setOf(1, 2), + counts = mapOf("apiKey" to 1, "views" to 2), + filter = Filter(sessionId = "secret", query = "shoes"), + filters = listOf(Filter(sessionId = "secret", query = "hats")), + origin = Origin.Search("shoes"), + fallbackOrigin = Origin.DeepLink, + note = null, + ) + +private val argumentsKeyArguments = + mapOf( + "productId" to 42, + "quantity" to 4_294_967_295L, + "authToken" to "[Filtered]", + "price" to 999, + "sort" to "ascending", + "tags" to listOf("a", "b"), + "sizes" to listOf(1, 2), + "counts" to mapOf("apiKey" to "[Filtered]", "views" to 2), + "filter" to mapOf("sessionId" to "[Filtered]", "query" to "shoes"), + "filters" to listOf(mapOf("sessionId" to "[Filtered]", "query" to "hats")), + "origin" to mapOf("type" to "search", "value" to mapOf("term" to "shoes")), + "fallbackOrigin" to mapOf("type" to "deeplink", "value" to emptyMap()), + "note" to null, + ) + fun serializableExpectations(): List = listOf( Expectation("public data object", PublicObject, "$PKG.PublicObject"), - Expectation("data class with @SerialName", NamedClass("1"), "Named"), - Expectation("data class", DefaultNamedClass("1"), "$PKG.DefaultNamedClass"), + Expectation( + "data class with @SerialName", + NamedClass("1"), + "Named", + expectedArguments = ID_ARGUMENTS, + ), + Expectation( + "data class", + DefaultNamedClass("1"), + "$PKG.DefaultNamedClass", + expectedArguments = ID_ARGUMENTS, + ), Expectation("sealed child object", Sealed.Child, "$PKG.Sealed.Child"), - Expectation("sealed leaf class", Sealed.Leaf("1"), "$PKG.Sealed.Leaf"), + Expectation( + "sealed leaf class", + Sealed.Leaf("1"), + "$PKG.Sealed.Leaf", + expectedArguments = ID_ARGUMENTS, + ), Expectation( "serializable enum", SerializableEnum.A, "$PKG.SerializableEnum", + expectedArguments = mapOf("value" to "A"), ), // In R8 full mode too, as AGP's default ProGuard files keep Signature and // kotlinx.serialization's rules keep @Serializable classes. @@ -131,24 +220,44 @@ fun serializableExpectations(): List = "private top-level class", PrivateTopLevelClass("1"), "$PKG.PrivateTopLevelClass", + expectedArguments = ID_ARGUMENTS, + ), + Expectation( + "class with a custom serializer", + Slug("shoes"), + "slug", + expectedArguments = mapOf("value" to "shoes"), ), - Expectation("class with a custom serializer", Slug("shoes"), "slug"), Expectation( "enum constant with a body", TabWithBody.HOME, "$PKG.TabWithBody", + expectedArguments = mapOf("value" to "HOME"), + ), + Expectation( + "value class", + TabId("feed"), + "$PKG.TabId", + expectedArguments = mapOf("value" to "feed"), + ), + Expectation( + "arguments key", + argumentsKey, + "$PKG.ArgumentsKey", + expectedArguments = argumentsKeyArguments, ), - Expectation("value class", TabId("feed"), "$PKG.TabId"), Expectation( "named companion without rules", NamedCompanionKey.of("1"), "$PKG.NamedCompanionKey", if (BuildConfig.NAMED_COMPANION_ALWAYS_NAMED) emptySet() else setOf(SERIALIZER_NOT_FOUND), + ID_ARGUMENTS, ), Expectation( "named companion with rules", NamedCompanionKeyWithRules.of("1"), "$PKG.NamedCompanionKeyWithRules", + expectedArguments = ID_ARGUMENTS, ), ) + Holder.keys() @@ -158,4 +267,10 @@ fun minificationChecks(): List = "PublicObject was renamed (runtime class ${PublicObject::class.java.name})", PublicObject::class.java.name != "$PKG.PublicObject", ), + // Argument names come from serializer descriptors, so they survive R8 renaming fields. + Check( + "ArgumentsKey fields were renamed " + + "(fields ${ArgumentsKey::class.java.declaredFields.map { it.name }})", + ArgumentsKey::class.java.declaredFields.none { it.name == "productId" }, + ), ) diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationSampleConfig.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationSampleConfig.kt index 61bde68b2a3..e7e88d228b2 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationSampleConfig.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationSampleConfig.kt @@ -2,6 +2,9 @@ package io.sentry.samples.android.navigation.common import io.sentry.Sentry +/** The most back stack entries `SentryNavOptions` captures; it treats larger values as this. */ +internal const val MAX_CAPTURED_BACK_STACK_ENTRIES = 25 + /** Configuration shared by nav sample apps. */ internal data class NavigationSampleConfig( val enableNavigationTransactions: Boolean = true, diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationSetupScreen.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationSetupScreen.kt index bef3414ab4f..869b44ecccb 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationSetupScreen.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationSetupScreen.kt @@ -123,6 +123,7 @@ internal fun NavigationSetupScreen( NavigationSetupCounterRow( label = "Max captured back stack entries", value = configuration.maxCapturedBackStackEntries, + maxValue = MAX_CAPTURED_BACK_STACK_ENTRIES, enabled = configuration.captureBackStack, ) { onConfigurationChanged(configuration.copy(maxCapturedBackStackEntries = it)) @@ -247,6 +248,7 @@ private fun NavigationSetupCheckboxRow( private fun NavigationSetupCounterRow( label: String, value: Int, + maxValue: Int, enabled: Boolean, onValueChange: (Int) -> Unit, ) { @@ -317,8 +319,8 @@ private fun NavigationSetupCounterRow( NavigationSetupCounterButton( label = "+", - enabled = enabled, - onClick = { onValueChange(value + 1) }, + enabled = enabled && value < maxValue, + onClick = { onValueChange((value + 1).coerceAtMost(maxValue)) }, color = sentryPurple, ) } diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt index 647df3c7658..8b6eb59bec4 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt @@ -251,10 +251,19 @@ private fun Nav3SampleApp( integrationMode.includeArguments, ) { if (!isPerformanceScenario) { - // Names each route after its serial name, and adds the arguments the route selects. + BackStackEntryMapper.SerialNameAndProperties + } else if (performanceMapperMode == Nav3PerformanceMapperMode.SERIAL_NAME_AND_PROPERTIES) { + // Times the duration of each call to the built-in mapper, which includes encoding the + // route's properties. + val mapper = + if (integrationMode.includeArguments) { + BackStackEntryMapper.SerialNameAndProperties + } else { + BackStackEntryMapper.SerialName + } BackStackEntryMapper { route -> - BackStackEntryMapper.SerialName.map(route)?.let { entry -> - SentryBackStackEntry(name = entry.name, arguments = route.arguments) + performanceState.recordNameExtraction("Nav3Stress.serialNameAndPropertiesMapping") { + mapper.map(route) } } } else if (performanceMapperMode == Nav3PerformanceMapperMode.SERIAL_NAME) { diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt index a83747a2cd2..2cc9f5d466b 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt @@ -307,7 +307,7 @@ internal fun MultiRootNavDisplay( // Keep this before the NavDisplay below: TracedNav3Route's resume tagging relies on it. SentryNavEffect( backStack = backStack, - backStackEntryMapper = BackStackEntryMapper.SerialName, + backStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties, options = options, ) val backHost = LocalNav3SampleHost.current ?: activity.javaClass.simpleName diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt index f771e9997b8..96d7acf6cb4 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt @@ -41,6 +41,7 @@ import io.sentry.DataCategory import io.sentry.Sentry import io.sentry.SentryOptions import io.sentry.clientreport.DiscardReason +import io.sentry.samples.android.navigation.common.MAX_CAPTURED_BACK_STACK_ENTRIES import java.util.Locale import java.util.concurrent.atomic.AtomicLong import kotlin.math.ceil @@ -578,15 +579,26 @@ internal enum class Nav3PerformanceArgumentMode(val label: String) { LARGE("Large"), } -/** - * Selects the performance scenario's mapper. - * - * [CUSTOM] provides synthetic arguments and separate extractor timings. [SERIAL_NAME] uses the - * built-in mapper, which extracts names only; each of its calls is timed as name extraction. - */ +/** Selects the performance scenario's mapper. */ internal enum class Nav3PerformanceMapperMode(val label: String) { + + /** Provides synthetic arguments and separate extractor timings. */ CUSTOM("Custom"), + + /** + * Uses the built-in mapper, which extracts names only. + * + * Each of its calls is timed as a name extraction. + */ SERIAL_NAME("SerialName"), + + /** + * Uses the built-in mapper that also records each route's properties. + * + * It records the route's real properties rather than the synthetic arguments that the "Argument + * shape" control selects, so that control is disabled in this mode. + */ + SERIAL_NAME_AND_PROPERTIES("SerialNameAndProperties"), } internal enum class Nav3PerformanceIntegrationMode( @@ -651,10 +663,10 @@ internal enum class Nav3PerformancePreset( Nav3PerformanceExtractorMode.NORMAL, Nav3PerformanceArgumentMode.FLAT, ), - CAPTURE_100_OF_100( - "Capture 100 of 100", - 100, + CAPTURE_25_OF_100( + "Capture 25 of 100", 100, + MAX_CAPTURED_BACK_STACK_ENTRIES, Nav3PerformanceIntegrationMode.FULL_STACK, Nav3PerformanceExtractorMode.NORMAL, Nav3PerformanceArgumentMode.FLAT, @@ -662,7 +674,7 @@ internal enum class Nav3PerformancePreset( HEAVY( "Heavy", 50, - 50, + MAX_CAPTURED_BACK_STACK_ENTRIES, Nav3PerformanceIntegrationMode.FULL_STACK, Nav3PerformanceExtractorMode.NORMAL, Nav3PerformanceArgumentMode.NESTED, @@ -670,7 +682,7 @@ internal enum class Nav3PerformancePreset( SUPER_HEAVY( "Super heavy", 100, - 100, + MAX_CAPTURED_BACK_STACK_ENTRIES, Nav3PerformanceIntegrationMode.FULL_STACK, Nav3PerformanceExtractorMode.HEAVY, Nav3PerformanceArgumentMode.LARGE, @@ -678,7 +690,7 @@ internal enum class Nav3PerformancePreset( NO_ARGUMENTS( "No arguments", 100, - 100, + MAX_CAPTURED_BACK_STACK_ENTRIES, Nav3PerformanceIntegrationMode.FULL_STACK_WITHOUT_ARGUMENTS, Nav3PerformanceExtractorMode.HEAVY, Nav3PerformanceArgumentMode.LARGE, @@ -686,7 +698,7 @@ internal enum class Nav3PerformancePreset( TOP_ONLY( "Top only", 30, - 30, + MAX_CAPTURED_BACK_STACK_ENTRIES, Nav3PerformanceIntegrationMode.TOP_ONLY, Nav3PerformanceExtractorMode.NORMAL, Nav3PerformanceArgumentMode.FLAT, @@ -694,7 +706,7 @@ internal enum class Nav3PerformancePreset( DISABLED_CONTROL( "Disabled control", 30, - 30, + MAX_CAPTURED_BACK_STACK_ENTRIES, Nav3PerformanceIntegrationMode.DISABLED, Nav3PerformanceExtractorMode.NORMAL, Nav3PerformanceArgumentMode.EMPTY, @@ -866,7 +878,9 @@ internal fun Nav3PerformancePanel( }, onIncrement = { controls.onMaxCapturedBackStackEntriesChange( - (controls.maxCapturedBackStackEntries + 1).coerceAtMost(100), + (controls.maxCapturedBackStackEntries + 1).coerceAtMost( + MAX_CAPTURED_BACK_STACK_ENTRIES, + ), ) }, ) diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceLaunch.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceLaunch.kt index dbde8d1ae06..dc611518db1 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceLaunch.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceLaunch.kt @@ -10,7 +10,7 @@ import android.content.Intent * applied first, then [mapperMode] and [integrationMode], then [run] starts. For example: * ``` * adb shell am start -n io.sentry.samples.android.debug/io.sentry.samples.android.navigation.nav3.Nav3Activity \ - * --es nav3_perf_preset capture_100_of_100 --es nav3_perf_mapper_mode serial_name \ + * --es nav3_perf_preset capture_25_of_100 --es nav3_perf_mapper_mode serial_name \ * --es nav3_perf_run ab_comparison * ``` * diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt index d292324c7e2..28ac663db38 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt @@ -11,6 +11,8 @@ import io.sentry.samples.android.navigation.common.RouteNames import io.sentry.samples.android.navigation.common.RouteSpec import io.sentry.samples.android.navigation.common.RouteSpecs import io.sentry.samples.android.navigation.common.displayRoute +import kotlinx.serialization.EncodeDefault +import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -236,9 +238,12 @@ internal fun SnapshotStateList.replacePerformanceTop(generation: Int) } /** - * The sample's serializable back stack keys. Each `@SerialName` supplies its Sentry route name, - * using the Nav2 sample's [RouteNames] for shared routes. Only constructor properties are - * serialized. + * The sample's serializable back stack keys, which `BackStackEntryMapper.SerialNameAndProperties` + * maps: a route's `@SerialName` supplies its Sentry name, and each property's `@SerialName` its + * argument name. + * + * Both use the Nav2 sample's [RouteNames] and [NavArgs], so the two samples send the same data. + * Only constructor properties are serialized. * * [routeName] and [arguments] mirror the sample's mapper output so screens, tags, and transaction * checks can read them without invoking the mapper. Mapping stays in `SentryNavEffect`, keeping @@ -252,8 +257,8 @@ internal sealed interface Nav3Route { val routeName: String /** - * The route's arguments as the sample's mapper records them: each property under the Nav2 - * sample's [NavArgs] name, with a `null` campaign left out, as in the Nav2 sample. + * The route's arguments as `SerialNameAndProperties` records them: each property under its + * `@SerialName`, the Nav2 sample's [NavArgs] name, with a `null` campaign left out. */ val arguments: Map get() = emptyMap() @@ -335,11 +340,15 @@ internal sealed interface Nav3Route { get() = RouteNames.PRODUCT_LIST } + @OptIn(ExperimentalSerializationApi::class) @Serializable @SerialName(RouteNames.PRODUCT_DETAIL) data class ProductDetail( - val productId: String, - val source: String, + @SerialName(NavArgs.PRODUCT_ID) val productId: String, + @SerialName(NavArgs.SOURCE) val source: String, + // Omitted from the arguments when null, like the Nav2 sample. + @EncodeDefault(EncodeDefault.Mode.NEVER) + @SerialName(NavArgs.CAMPAIGN) val campaign: String? = null, ) : Nav3Route { override val routeName: String @@ -358,7 +367,7 @@ internal sealed interface Nav3Route { @Serializable @SerialName(RouteNames.CHECKOUT) - data class Checkout(val productId: String) : Nav3Route { + data class Checkout(@SerialName(NavArgs.PRODUCT_ID) val productId: String) : Nav3Route { override val routeName: String get() = RouteNames.CHECKOUT @@ -371,7 +380,7 @@ internal sealed interface Nav3Route { @Serializable @SerialName(RouteNames.CONFIRMATION) - data class Confirmation(val orderId: String) : Nav3Route { + data class Confirmation(@SerialName(NavArgs.ORDER_ID) val orderId: String) : Nav3Route { override val routeName: String get() = RouteNames.CONFIRMATION @@ -384,7 +393,7 @@ internal sealed interface Nav3Route { @Serializable @SerialName(RouteNames.PROMO_DIALOG) - data class PromoDialog(val promoId: String) : Nav3Route { + data class PromoDialog(@SerialName(NavArgs.PROMO_ID) val promoId: String) : Nav3Route { override val routeName: String get() = RouteNames.PROMO_DIALOG @@ -397,7 +406,7 @@ internal sealed interface Nav3Route { @Serializable @SerialName(RouteNames.SHARE_SHEET) - data class ShareSheet(val productId: String) : Nav3Route { + data class ShareSheet(@SerialName(NavArgs.PRODUCT_ID) val productId: String) : Nav3Route { override val routeName: String get() = RouteNames.SHARE_SHEET diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3SampleConfig.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3SampleConfig.kt index 88d752218cc..f31c06905fa 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3SampleConfig.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3SampleConfig.kt @@ -3,6 +3,7 @@ package io.sentry.samples.android.navigation.nav3 import android.content.Context import android.content.Intent import android.os.Bundle +import io.sentry.samples.android.navigation.common.MAX_CAPTURED_BACK_STACK_ENTRIES import io.sentry.samples.android.navigation.common.NavigationSampleConfig import io.sentry.samples.android.navigation.common.NavigationSampleConfigSnapshot @@ -37,7 +38,8 @@ internal fun Intent.nav3SampleConfig(): NavigationSampleConfig = getBooleanExtra(EXTRA_ENABLE_USER_INTERACTION_BREADCRUMBS, false), captureBackStack = getBooleanExtra(EXTRA_CAPTURE_BACK_STACK, true), maxCapturedBackStackEntries = - getIntExtra(EXTRA_MAX_CAPTURED_BACK_STACK_ENTRIES, 10).coerceAtLeast(1), + getIntExtra(EXTRA_MAX_CAPTURED_BACK_STACK_ENTRIES, 10) + .coerceIn(1, MAX_CAPTURED_BACK_STACK_ENTRIES), ) internal fun Context.nav3LaunchIntent( @@ -103,7 +105,8 @@ internal fun Bundle.nav3SampleConfiguration(): NavigationSampleConfig = enableUserInteractionBreadcrumbs = getBoolean(STATE_ENABLE_USER_INTERACTION_BREADCRUMBS, false), captureBackStack = getBoolean(STATE_CAPTURE_BACK_STACK, true), maxCapturedBackStackEntries = - getInt(STATE_MAX_CAPTURED_BACK_STACK_ENTRIES, 10).coerceAtLeast(1), + getInt(STATE_MAX_CAPTURED_BACK_STACK_ENTRIES, 10) + .coerceIn(1, MAX_CAPTURED_BACK_STACK_ENTRIES), ) private const val EXTRA_PREFIX = "io.sentry.samples.android.navigation.nav3" diff --git a/sentry-android-navigation3/README.md b/sentry-android-navigation3/README.md index 5b80d74bd91..a65903b80b5 100644 --- a/sentry-android-navigation3/README.md +++ b/sentry-android-navigation3/README.md @@ -9,7 +9,8 @@ This module requires Nav3. It doesn't declare its own dependencies on Compose, l your Nav3 dependency brings in. Because Nav3 back stacks can have arbitrary key types, host apps need to provide `SentryNavEffect` with a mapping between their back stack -keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` mapper). +keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` and `SerialNameAndProperties` +mappers). See the [Navigation for Android docs](https://docs.sentry.io/platforms/android/integrations/navigation/) for additional details, including configuration, supported setups, and limitations. diff --git a/sentry-android-navigation3/api/sentry-android-navigation3.api b/sentry-android-navigation3/api/sentry-android-navigation3.api index 04c3349cd46..04a7ba34aac 100644 --- a/sentry-android-navigation3/api/sentry-android-navigation3.api +++ b/sentry-android-navigation3/api/sentry-android-navigation3.api @@ -5,6 +5,7 @@ public abstract interface class io/sentry/compose/navigation3/BackStackEntryMapp public final class io/sentry/compose/navigation3/BackStackEntryMapper$Companion { public final fun getSerialName ()Lio/sentry/compose/navigation3/BackStackEntryMapper; + public final fun getSerialNameAndProperties ()Lio/sentry/compose/navigation3/BackStackEntryMapper; } public final class io/sentry/compose/navigation3/BuildConfig { diff --git a/sentry-android-navigation3/proguard-rules.pro b/sentry-android-navigation3/proguard-rules.pro index b34c23cc870..971f668a7ec 100644 --- a/sentry-android-navigation3/proguard-rules.pro +++ b/sentry-android-navigation3/proguard-rules.pro @@ -8,8 +8,9 @@ ##---------------Begin: proguard configuration for kotlinx.serialization ---------- -# Serial names survive R8 minification because Kotlin's serialization compiler plugin fixes them at compile time. Our built-in mapper -# fallback for private `@Serializable` objects relies on members preserved by kotlinx.serialization's own consumer rules. +# Serial names, including the property names `SerialNameAndProperties` records as argument keys, survive R8 minification because Kotlin's +# serialization compiler plugin fixes them at compile time. Our built-in mappers' fallback for private `@Serializable` objects relies on +# members preserved by kotlinx.serialization's own consumer rules. # We don't ship rules for `@Serializable` classes with named companion objects. kotlinx.serialization's rules cover them but only from # 1.10.0 on. A generic rule set that fixes older versions exists, but we don't apply it because it would keep `InnerClasses` and 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 7e11a788c3b..cb9ef4ff237 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 @@ -6,7 +6,8 @@ import org.jetbrains.annotations.ApiStatus /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * See [SerialName] for an out-of-the-box mapper, or else provide your own. + * See [SerialName] and [SerialNameAndProperties] for out-of-the-box mappers, or else provide your + * own. * * **Privacy / PII** * @@ -14,6 +15,10 @@ import org.jetbrains.annotations.ApiStatus * personal information. Only return names and arguments that are known to be safe or have been * pre-scrubbed. * + * Neither `sendDefaultPii` nor the `dataCollection` options change what any mapper returns. + * `SerialNameAndProperties` filters only a limited set of secrets; see its documentation for + * details. + * * **Performance** * * Mappers are invoked synchronously from [SentryNavEffect] on the same apply thread that runs the @@ -93,7 +98,7 @@ import org.jetbrains.annotations.ApiStatus * ) * * // Consider falling back to a built-in mapper for the rest. - * else -> BackStackEntryMapper.SerialName.map(entry) + * else -> BackStackEntryMapper.SerialNameAndProperties.map(entry) * } * } * ``` @@ -125,7 +130,8 @@ public fun interface BackStackEntryMapper { * ``` * * this mapper returns `"ProductDetailScreen"` for `ProductDetail(productId = "zyx987")` but - * omits the destination's properties (`productId`). + * omits the destination's properties (`productId`). (To return arguments too, see + * [SerialNameAndProperties].) * * **Name == SerialDescriptor.serialName** * @@ -142,7 +148,8 @@ public fun interface BackStackEntryMapper { * particular: * * - All constants of an enum share the enum class's serial name, regardless of any - * `@SerialName` on the constants. + * `@SerialName` on the constants. (A constant's `@SerialName` only changes how + * [SerialNameAndProperties] records it as an argument.) * * - Classes that share a custom serializer (`@Serializable(with = ...)`) share its descriptor's * serial name, regardless of any `@SerialName` on the classes. @@ -158,12 +165,69 @@ public fun interface BackStackEntryMapper { * Sentry displays `null` entries as "/unknown" with an `unknown_entry_reason`. With SDK * debugging enabled, the first unnamed entry of each class also logs a warning. * - * See the - * [Troubleshooting Guide](https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-back-stack-mapping) - * for more details. + * See the discussion of + * [Unknown Destination Names](https://docs.sentry.io/platforms/android/integrations/navigation/#unknown-destination-names) + * in the Sentry Android Navigation docs for more details. */ public val SerialName: BackStackEntryMapper get() = BuiltInBackStackEntryMappers.serialName + + /** + * Like [SerialName], but also returns the properties that each back stack entry's serializer + * encodes, as Sentry arguments. + * + * For instance, given: + * ``` + * @Serializable + * @SerialName("ProductDetailScreen") + * data class ProductDetail(val userId: String, val productId: String) : NavKey + * ``` + * + * this mapper returns `"ProductDetailScreen"` for `ProductDetail(userId = "123abc", productId = + * "zyx987")`, along with these arguments: + * ```json + * { + * "userId": "123abc", + * "productId": "zyx987" + * } + * ``` + * + * Entry names follow the rules for [SerialName]. Entries that can't be named are recorded as + * "/unknown" with an `unknown_entry_reason`. They're returned without arguments, since their + * inability to be named means they have no usable serializer. The argument limits described in + * [BackStackEntryMapper] apply. + * + * **Privacy / PII** + * + * This mapper returns every property that each back stack entry's serializer encodes, which may + * include private data and PII. Properties the serializer doesn't encode (e.g., `@Transient` + * ones) aren't returned. Apart from the limited filtering of secrets described below, + * properties are sent as-is. + * + * If an entry contains data that shouldn't be sent to Sentry, either filter that property out + * of this mapper's arguments, or use a custom [BackStackEntryMapper] that special-cases the + * entry and falls back to this mapper (or [SerialName]) for the rest. See + * [Choosing Which Arguments to Send](https://docs.sentry.io/platforms/android/integrations/navigation/#choosing-which-arguments-to-send) + * for examples. + * + * **Limited filtering of secrets** + * + * If a property's + * [serial name](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-serial-descriptor/serial-name.html) + * or map key contains a term from + * [Sentry's sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist) + * (ignoring case), then its value will be replaced with `"[Filtered]"`. See + * [Choosing Which Arguments to Send](https://docs.sentry.io/platforms/android/integrations/navigation/#choosing-which-arguments-to-send) + * for more details. + * + * **Argument encoding failures** + * + * Argument encoding failures preserve the entry's name and replace its arguments with a drop + * reason, e.g., `{"dropped_by_sentry": "encoding_failed"}`. With `debug` enabled, the first + * failure of each kind for each entry type also logs a warning. + */ + public val SerialNameAndProperties: BackStackEntryMapper + get() = BuiltInBackStackEntryMappers.serialNameAndProperties } } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt index c91b3b6f541..55061194743 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt @@ -7,6 +7,10 @@ import org.jetbrains.annotations.ApiStatus // sanitization when navigation changes are observed. internal const val DEFAULT_MAX_CAPTURED_BACK_STACK_ENTRIES = 5 +// Bounds the work done per back stack change to help ensure performance while still providing (more +// than) enough entries for host app's needs. +internal const val MAX_CAPTURED_BACK_STACK_ENTRIES = 25 + /** * Configuration info for a [SentryNavEffect]. * @@ -64,7 +68,7 @@ private constructor( /** * Maximum number of entries Sentry should record per captured back stack (starting with the - * most recent). Set to `0` to capture no back stack entries. + * most recent). Capped at 25. Set it to 0 to capture no back stack entries. * * Note: Sentry resolves and sanitizes up to [maxCapturedBackStackEntries] names + argument maps * whenever your back stack changes. Keep the back stack mapper lightweight, and reduce the max @@ -77,7 +81,8 @@ private constructor( enableNavigationBreadcrumbs = enableNavigationBreadcrumbs, enableNavigationTransactions = enableNavigationTransactions, captureBackStack = captureBackStack, - maxCapturedBackStackEntries = maxCapturedBackStackEntries, + maxCapturedBackStackEntries = + maxCapturedBackStackEntries.coerceAtMost(MAX_CAPTURED_BACK_STACK_ENTRIES), ) } 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 9285537508e..6e2aa982c06 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 @@ -5,10 +5,12 @@ import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentWriteResult +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.HostArgumentSource +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter -import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS -import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH -import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.internal.contract.BACK_STACK_ENTRY_ARGUMENTS_KEY @@ -18,7 +20,6 @@ import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY import io.sentry.util.ExceptionUtils -import java.util.IdentityHashMap /** * Converts the host app back stack into a list of [NormalizedSentryBackStackEntry]s. @@ -151,8 +152,10 @@ internal class BackStackConverter( /** * Sanitizes the arguments the [entryMapper] returns for back stack entries and returns them in a - * [serializable form][SanitizedArguments.values]. It bounds depth and total value count, and it - * rejects cyclic structures. + * [serializable form][SanitizedArguments.values]. + * + * Each entry's arguments are written by a [HostArgumentSource] into a [TreeArgumentSink], which + * bounds depth and total value count, and rejects cyclic structures. * * One instance is shared across every entry in a single [convert] call, so the value and * character budgets span the whole update. @@ -162,13 +165,9 @@ internal class BackStackConverter( private val warningState: WarningState, ) { - private var remainingValues = MAX_ARGUMENT_VALUES - private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + private val budget = ArgumentBudget() private var dropReason: ArgumentDropReason? = null - /** The maps and lists currently being sanitized, so that one containing itself is rejected. */ - private val activeContainers = IdentityHashMap() - /** * Sanitizes one entry's raw argument inputs and returns the result. * @@ -181,148 +180,29 @@ internal class BackStackConverter( * * [SanitizedArguments.dropReason] will be non-null if and only if arguments are dropped. */ - @Suppress("TooGenericExceptionCaught") fun sanitizeEntry(raw: Map): SanitizedArguments { dropReason?.let { reason -> return SanitizedArguments(emptyMap(), reason) } - return try { - SanitizedArguments(sanitizeMap(raw, depth = 0)) - } catch (drop: DropArguments) { - if (drop.reason.exhaustsUpdateBudget) { - dropReason = drop.reason - } - logger.log(WARNING, drop.warning) - SanitizedArguments(emptyMap(), drop.reason) - } catch (t: Throwable) { - // Extracted maps may invoke host app code while iterating or stringifying values. - ExceptionUtils.rethrowIfFatal(t) - logger.log(WARNING, STRUCTURE_WARNING, t) - SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) - } finally { - // A drop or failure leaves the containers it was inside of open. - activeContainers.clear() - } - } + val source = HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } - /** Sanitizes [map], whose values are at [depth] + 1. The entry's root map has depth 0. */ - private fun sanitizeMap(map: Map<*, *>, depth: Int): Map { - enter(map) - val sanitized = LinkedHashMap() - for ((key, value) in map) { - val name = spendText(key.toString()) - if (sanitized.containsKey(name)) { - throw duplicateKey(map, key, name) + return when (val result = TreeArgumentSink(budget).write(source)) { + is ArgumentWriteResult.Written -> SanitizedArguments(result.arguments) + is ArgumentWriteResult.Dropped -> drop(result.drop) + is ArgumentWriteResult.Failed -> { + logger.log(WARNING, DropArgumentsException.STRUCTURE_WARNING, result.cause) + SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) } - sanitized[name] = sanitizeValue(value, depth + 1) - } - activeContainers.remove(map) - return sanitized - } - - private fun sanitizeValue(value: Any?, depth: Int): Any? { - // A value at depth n is nested in n containers, counting the entry's root map. - if (depth > MAX_ARGUMENT_DEPTH) { - throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING) - } - if (--remainingValues < 0) { - throw DropArguments(ArgumentDropReason.MAX_COUNT, MAX_COUNT_WARNING) } - - if (value is Map<*, *>) { - return sanitizeMap(value, depth) - } - val collection = value?.asCollectionOrNull() ?: return sanitizeScalar(value) - - enter(value) - // Iterated without reading the collection's size, which the host app controls. - val sanitized = ArrayList() - for (element in collection) { - sanitized += sanitizeValue(element, depth + 1) - } - activeContainers.remove(value) - return sanitized - } - - private fun sanitizeScalar(value: Any?): Any? = - when (value) { - null, - is Boolean -> value - // JSON has no NaN or infinity, and Sentry's JSON writer throws for them, which would drop - // the whole event these arguments are attached to. We record them as strings instead. - is Number -> if (value.isNonFinite()) spendText(value.toString()) else value - is CharSequence -> spendText(value) - is Char -> spendText(value.toString()) - is Enum<*> -> spendText(value.name) - else -> { - warningState.logUnsupportedValueWarning(value::class.simpleName, logger) - spendText(value.toString()) - } - } - - /** - * Returns [text] as a [String] after spending its characters. - * - * Checks [text]'s length before converting it, so that host app text that doesn't fit isn't - * copied, and again after, in case a custom [CharSequence]'s length doesn't match its text. - */ - private fun spendText(text: CharSequence): String { - checkFits(text.length) - val string = text.toString() - checkFits(string.length) - remainingCharacters -= string.length - return string } - private fun checkFits(characters: Int) { - if (characters > remainingCharacters) { - throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, MAX_CHARACTER_WARNING) + private fun drop(drop: DropArgumentsException): SanitizedArguments { + if (drop.reason.exhaustsUpdateBudget) { + dropReason = drop.reason } - } - - private fun enter(container: Any) { - if (activeContainers.put(container, Unit) != null) { - throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING) - } - } - - /** - * Names only the colliding keys' types, as the keys themselves may contain host data. - * Collisions are rare, so we re-scan [map] instead of tracking the original keys of every map. - */ - private fun duplicateKey(map: Map<*, *>, key: Any?, name: String): DropArguments { - val otherKey = map.keys.firstOrNull { it !== key && it.toString() == name } - return DropArguments( - ArgumentDropReason.DUPLICATE_KEY, - "A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same string " + - "as another key (${otherKey?.let { it::class.simpleName }}). Dropping this entry's " + - "arguments.", - ) - } - - /** - * Control-flow signal to drop an entry's arguments, logging [warning]. Overrides - * [fillInStackTrace] to skip stack-trace capture. - */ - private class DropArguments(val reason: ArgumentDropReason, val warning: String) : - RuntimeException() { - override fun fillInStackTrace(): Throwable = this - } - - companion object { - - const val MAX_CHARACTER_WARNING = - "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + - "this and older entries." - - const val MAX_COUNT_WARNING = - "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + - "and older entries." - - const val STRUCTURE_WARNING = - "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + - "entry's arguments." + logger.log(WARNING, drop.warning) + return SanitizedArguments(emptyMap(), drop.reason) } } @@ -380,9 +260,7 @@ internal data class NormalizedSentryBackStackEntry( val name: String, /** Sanitized [SentryBackStackEntry.arguments] (i.e., bounded in size and depth). */ val arguments: Map = emptyMap(), - /** - * The reason why the SDK dropped host-provided arguments, or null if no arguments were dropped. - */ + /** The reason why the SDK dropped the entry's arguments, or null if no arguments were dropped. */ val argumentDropReason: ArgumentDropReason? = null, /** Why the entry was recorded as [UNKNOWN_ENTRY_NAME], or `null` if it has a name. */ val unknownEntryReason: UnknownEntryReason? = null, @@ -451,23 +329,3 @@ internal fun NormalizedSentryBackStackEntry.transactionData(): Map internal fun List.serialize(): List> = map(NormalizedSentryBackStackEntry::serialize) - -/** Returns this collection, or this array as a list, or `null` if it's neither. */ -private fun Any.asCollectionOrNull(): Collection<*>? = - when (this) { - is Collection<*> -> this - is Array<*> -> asList() - is BooleanArray -> asList() - is ByteArray -> asList() - is ShortArray -> asList() - is IntArray -> asList() - is LongArray -> asList() - is FloatArray -> asList() - is DoubleArray -> asList() - is CharArray -> asList() - else -> null - } - -/** Whether this is a NaN or infinite `Double` or `Float`. */ -private fun Number.isNonFinite(): Boolean = - (this is Double && !isFinite()) || (this is Float && !isFinite()) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt index 3fd1247a200..d359e7e4a47 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -23,7 +23,8 @@ internal object BuiltInBackStackEntryMappers { * A built-in [BackStackEntryMapper] for apps that use kotlinx.serialization and only need to * track the serial name of each of their back stack entries (and not each entry's properties). * - * Falls back to [UnavailableBackStackEntryMapper] if the kotlinx mapper can't be created. + * Falls back to [UnavailableBackStackEntryMapper] if the underlying kotlinx mapper can't be + * created. * * See [BackStackEntryMapper.SerialName] for more details. */ @@ -34,6 +35,21 @@ internal object BuiltInBackStackEntryMappers { create(logger) { KotlinxBackStackEntryMapper(logger = logger) } } + /** + * Like [serialName], but also returns the properties of each back stack entry as Sentry + * arguments. + * + * Falls back to [UnavailableBackStackEntryMapper] if the underlying kotlinx mapper can't be + * created. + * + * See [BackStackEntryMapper.SerialNameAndProperties] for more details. + */ + val serialNameAndProperties: BackStackEntryMapper = + // Deferred for the same reason as serialName. + DeferredBackStackEntryMapper { + create(logger) { KotlinxBackStackEntryMapper(includeProperties = true, logger = logger) } + } + /** * Returns the mapper created by [newKotlinxMapper], or an [UnavailableBackStackEntryMapper] if * the mapper can't be linked or initialized. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt new file mode 100644 index 00000000000..3e9df094957 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt @@ -0,0 +1,59 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentWriteResult +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY +import kotlinx.serialization.KSerializer + +/** Builds arguments from back stack entries using kotlinx.serialization. */ +internal object KotlinxArguments { + + /** + * The arguments of an entry whose properties can't be encoded, e.g., because the app's + * kotlinx.serialization version doesn't support the properties encoder. + */ + val UNENCODABLE: Map = droppedFor(ArgumentDropReason.ENCODING_FAILED) + + /** + * Returns [backStackEntry]'s properties, encoded with [serializer] and an [ArgumentBudget] of + * their own. + * + * If the entry breaks an argument limit or can't be encoded, reports why to [onFailure] and + * returns only the reason under [ARGUMENT_DROP_REASON_KEY], e.g., `{"dropped_by_sentry": + * "encoding_failed"}`. A host app mapper that copies or filters the arguments then passes the + * reason on as an ordinary argument. + */ + fun encode( + backStackEntry: Any, + serializer: KSerializer, + onFailure: (Throwable) -> Unit, + ): Map { + val result = + try { + TreeArgumentSink(ArgumentBudget()).write { + KotlinxPropertiesEncoder.encode(serializer, backStackEntry, it) + } + } catch (e: LinkageError) { + // write() rethrows LinkageErrors as fatal. This one may be specific to the entry's + // serializers, which a compatibility check can't exercise, so we drop only its properties. + ArgumentWriteResult.Failed(e) + } + + return when (result) { + is ArgumentWriteResult.Written -> result.arguments + is ArgumentWriteResult.Dropped -> { + onFailure(result.drop) + droppedFor(result.drop.reason) + } + is ArgumentWriteResult.Failed -> { + onFailure(result.cause) + UNENCODABLE + } + } + } + + private fun droppedFor(reason: ArgumentDropReason): Map = + mapOf(ARGUMENT_DROP_REASON_KEY to reason.serializedValue) +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt index 07cd2ffc47d..9ac4c296b08 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -5,21 +5,40 @@ import io.sentry.SentryLevel.DEBUG import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import io.sentry.util.ExceptionUtils import java.lang.reflect.GenericSignatureFormatError import java.lang.reflect.InvocationTargetException import java.lang.reflect.MalformedParameterizedTypeException +import java.util.Collections import java.util.concurrent.ConcurrentHashMap import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.StructureKind -/** Implementation of [BackStackEntryMapper.SerialName]. */ +/** + * Implementation of [BackStackEntryMapper.SerialName] and + * [BackStackEntryMapper.SerialNameAndProperties], each of which relies on kotlinx serializers. + */ internal class KotlinxBackStackEntryMapper( + /** + * Whether this mapper returns each back stack entry's properties as arguments, as well as its + * name. + */ + private val includeProperties: Boolean = false, /** * Returns the serializer of a back stack entry's `@Serializable` class, or `null` if there's none * (e.g. for a generic class). Only called for classes marked `@Serializable`. @@ -35,11 +54,16 @@ internal class KotlinxBackStackEntryMapper( private val isAnnotatedSerializable: (Class<*>) -> Boolean = serializableAnnotationCheck(), /** Throws a [LinkageError] if the app's kotlinx.serialization version is incompatible. */ checkCompatibility: () -> Unit = { checkKotlinxCompatibility() }, + /** + * Returns why the properties encoder can't be used with the app's kotlinx.serialization version, + * or `null` if it can. Only called if [includeProperties] is `true`. + */ + checkEncoderCompatibility: () -> Throwable? = { kotlinxEncoderIncompatibility() }, logger: () -> ILogger, ) : BackStackEntryMapper { // Serializer lookups use reflection and mapping runs on every navigation, so we cache each - // class's name. Cache size is bounded by the number of back stack entry types. + // class's serializer and name. Cache size is bounded by the number of back stack entry types. private val types = ConcurrentHashMap, CachedType>() private val diagnostics = KotlinxMapperDiagnostics(logger) @@ -59,6 +83,19 @@ internal class KotlinxBackStackEntryMapper( } } + /** + * `true` if the app's kotlinx.serialization version can't be used to encode properties. Entries + * with properties then record [ArgumentDropReason.ENCODING_FAILED] without being encoded. Names + * are unaffected. + */ + private val isEncodingIncompatible: Boolean = + includeProperties && + run { + val error = checkEncoderCompatibility() ?: return@run false + diagnostics.incompatibleEncoder(error) + true + } + override fun map(backStackEntry: Any): SentryBackStackEntry? { // An enum constant with a body is an instance of an anonymous subclass, which isn't // @Serializable itself, so we look up the enum class instead. @@ -72,7 +109,9 @@ internal class KotlinxBackStackEntryMapper( } } - return SentryBackStackEntry(cached.name) + val arguments = if (includeProperties) argumentsOf(type, cached, backStackEntry) else null + + return SentryBackStackEntry(cached.name, arguments) } private fun cachedType(type: Class<*>): CachedType { @@ -109,7 +148,10 @@ internal class KotlinxBackStackEntryMapper( if (serializer == null) { unresolved(type, error = null) } else { - CachedType.Resolved(serializer.descriptor.serialName) + val descriptor = serializer.descriptor + // Read before the shape, so a failure reading the shape doesn't cost the type its name. + val name = descriptor.serialName + CachedType.Resolved(name, serializer, includeProperties && hasProperties(descriptor)) } } catch (e: InvocationTargetException) { // The type's serializer() or descriptor threw through reflection, e.g., a custom serializer's @@ -206,11 +248,59 @@ internal class KotlinxBackStackEntryMapper( ) } + /** + * Whether entries described by [descriptor] may have properties. A class or object without + * properties records no arguments, so its entries aren't encoded. + */ + @OptIn(ExperimentalSerializationApi::class) + private fun hasProperties(descriptor: SerialDescriptor): Boolean = + try { + descriptor.elementsCount > 0 || + (descriptor.kind != StructureKind.CLASS && descriptor.kind != StructureKind.OBJECT) + } catch (_: LinkageError) { + // As for the name, a LinkageError from the type's own descriptor only fails this type. + true + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad b/c a custom serializer's descriptor is host app code, which may throw anything. The + // entry keeps its name, and encoding, which reads the same descriptor, records why its + // arguments are dropped. + ExceptionUtils.rethrowIfFatal(t) + true + } + + /** + * Returns the encoded arguments derived from [backStackEntry]'s properties, or `null` if its + * [type] has no properties. + */ + private fun argumentsOf( + type: Class<*>, + cached: CachedType.Resolved, + backStackEntry: Any, + ): Map? { + if (!cached.hasProperties) { + return null + } + if (isEncodingIncompatible) { + return KotlinxArguments.UNENCODABLE + } + @Suppress("UNCHECKED_CAST") + return KotlinxArguments.encode(backStackEntry, cached.serializer as KSerializer) { error -> + diagnostics.propertyFailure(type, error) + } + } + /** What [lookUp] found for a back stack entry type, cached so each type is looked up once. */ private sealed interface CachedType { - /** A type that can be named, and its [name]. */ - class Resolved(val name: String) : CachedType + /** + * A type that can be named: its [name], its [serializer], and whether it [hasProperties] to + * encode. `hasProperties` is always `false` if the mapper doesn't include properties. + */ + class Resolved( + val name: String, + val serializer: KSerializer<*>, + val hasProperties: Boolean, + ) : CachedType /** * A type that can't be named, e.g., because it isn't `@Serializable` or reading its serializer @@ -234,16 +324,25 @@ internal class KotlinxBackStackEntryMapper( /** * The warnings [KotlinxBackStackEntryMapper] logs if it can't find the serializer for a back stack - * entry or resolve the entry's name. + * entry, resolve the entry's name, or encode its properties. * - * Only decides what's logged. Whether a type is looked up again is up to the mapper. + * Only decides what's logged, and how often. Whether a type is looked up or encoded again is up to + * the mapper. * - * The R8 check matches the start of [compatibilityCheckFailed]'s message, so rewording it requires - * updating `CompatibilityLogChecks.kt` + * The R8 check matches the start of [compatibilityCheckFailed]'s and [incompatibleEncoder]'s + * messages, so rewording them requires updating `CompatibilityLogChecks.kt` * (`sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check`). */ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { + /** + * The kinds of property encoding failure already logged for each type. Failing types are still + * encoded again, as whether encoding fails can depend on the value, so this only keeps each + * warning from being logged more than once per type. + */ + private val loggedPropertyFailures = + Collections.newSetFromMap(ConcurrentHashMap, PropertyFailure>, Boolean>()) + /** Logs that entries of [type] can't be named because the type isn't `@Serializable`. */ fun notSerializable(type: Class<*>) { logger() @@ -281,6 +380,127 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { ) } + /** + * Logs [error] indicating that the app's kotlinx.serialization version can't be used to encode + * properties. Entries are recorded by name without arguments. + */ + fun incompatibleEncoder(error: Throwable) { + logger() + .log( + WARNING, + "Nav3 SerialNameAndProperties is incompatible with this app's kotlinx.serialization " + + "version. Recording names without arguments. $INCOMPATIBLE_KOTLINX_ADVICE", + error, + ) + } + + /** + * Logs why encoding the properties of an entry of [type] failed. Logged once per type and kind of + * failure, as whether encoding fails can depend on the entry's values (e.g., whether a contextual + * property is null, or which subtype a sealed property has). + * + * Attaches [error] unless it's a [DropArgumentsException], which carries only the reason that's + * logged. + */ + @Suppress("LongMethod") // One flat branch per kind of failure. + fun propertyFailure(type: Class<*>, error: Throwable) { + when (error) { + is DropArgumentsException -> + logOncePerType(type, PropertyFailure.OVER_LIMITS) { + log( + WARNING, + "Nav3 dropped arguments for type %s (%s). Limits are $MAX_ARGUMENT_DEPTH levels, " + + "$MAX_ARGUMENT_VALUES values, $MAX_ARGUMENT_CHARACTERS characters, and " + + "$MAX_SERIALIZER_NESTING nested serializer calls. Map keys must stringify to " + + "distinct strings. Use a custom BackStackEntryMapper to select fewer properties or " + + "flatten nested values.", + type.name, + error.reason.serializedValue, + ) + } + is SerializationException -> + logOncePerType(type, PropertyFailure.UNENCODABLE) { + log( + WARNING, + error, + "Nav3 couldn't encode properties for type %s. Recording names without arguments. " + + "Contextual and open polymorphic properties and structured map keys aren't " + + "supported. Use a custom BackStackEntryMapper to select supported properties or " + + "extract arguments directly. See the attached error.", + type.name, + ) + } + is ArgumentProtocolException -> + logOncePerType(type, PropertyFailure.PROTOCOL_VIOLATION) { + log( + WARNING, + error, + "Nav3 couldn't encode properties for type %s because a value was written outside " + + "the encoder's protocol (by a custom serializer or an SDK bug). Recording names " + + "without arguments. See the attached error.", + type.name, + ) + } + is LinkageError -> + logOncePerType(type, PropertyFailure.UNLOADABLE) { + log( + WARNING, + error, + "Nav3 couldn't encode properties for type %s because a required class couldn't be " + + "linked, initialized, or found. Recording names without arguments. See the " + + "attached error. If all types fail, kotlinx.serialization may be incompatible. " + + INCOMPATIBLE_KOTLINX_ADVICE, + type.name, + ) + } + else -> + logOncePerType(type, PropertyFailure.THROWING) { + log( + WARNING, + error, + "Nav3 couldn't encode properties for type %s because a serializer threw. Recording " + + "names without arguments. See the attached error.", + type.name, + ) + } + } + } + + /** Runs [log] on the logger unless a [failure] of this kind was already logged for [type]. */ + private inline fun logOncePerType( + type: Class<*>, + failure: PropertyFailure, + log: ILogger.() -> Unit, + ) { + if (loggedPropertyFailures.add(type to failure)) { + logger().log() + } + } + + /** Why encoding an entry's properties failed, which determines the warning we log. */ + private enum class PropertyFailure { + /** Encoding threw a [SerializationException], e.g., for a contextual property. */ + UNENCODABLE, + + /** + * The entry broke an argument limit, e.g., by having too many values, or has a map with two + * keys recorded as the same string. + */ + OVER_LIMITS, + + /** + * A value was written out of order or couldn't be recorded (an [ArgumentProtocolException]), + * e.g., by a custom serializer that writes values outside its elements. + */ + PROTOCOL_VIOLATION, + + /** A serializer threw something other than a [SerializationException] or [LinkageError]. */ + THROWING, + + /** A class a serializer needs couldn't be linked, initialized, or found. */ + UNLOADABLE, + } + /** * Logs why [type] can't be named. [error] is what reading its annotations, serializer, or * descriptor threw, or `null` if the serializer lookup found none without throwing. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt index ed5ac25d540..60f70ab2da1 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt @@ -2,23 +2,120 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.util.ExceptionUtils import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.TripleSerializer +import kotlinx.serialization.builtins.nullable +import kotlinx.serialization.builtins.serializer /** * Verifies that the host app's `kotlinx-serialization-core` version is compatible with the APIs * used by our built-in `BackStackEntryMapper`s. * - * Does so by calling each kotlinx.serialization API that [KotlinxBackStackEntryMapper] calls, looks - * up the built-in `String` serializer, and reads its serial name. + * Does so by calling each kotlinx.serialization API that [KotlinxBackStackEntryMapper] invokes, + * looks up the built-in `String` serializer, and reads its serial name. * - * Throws a [LinkageError] if the app's `kotlinx-serialization-core` version is incompatible. A - * `LinkageError` thrown here is conclusive: unlike looking up an app type's serializer, the check - * runs no app code and no serializer generated by a compiler plugin, either of which could throw - * one for reasons that affect only its own type. + * Throws a [LinkageError] if the app's `kotlinx-serialization-core` version is incompatible. + * + * Note: A `LinkageError` thrown here is conclusive. Unlike looking up an app type's serializer, the + * check runs no app code and no serializer generated by a compiler plugin, either of which could + * throw one for reasons that affect only its own type. */ internal fun checkKotlinxCompatibility( lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, ) { lookUpSerializer(String::class.java)?.descriptor?.serialName } + +/** + * Returns why the properties encoder can't be used with the host app's `kotlinx-serialization-core` + * version, or `null` if it can. + * + * Encodes [COMPATIBILITY_CHECK_VALUE] with [KotlinxPropertiesEncoder], as [KotlinxArguments.encode] + * does, and compares the output with [COMPATIBILITY_CHECK_ENCODING]. Like + * [checkKotlinxCompatibility], it uses only built-in serializers, so it runs no app code and no + * serializer generated by a compiler plugin. + * + * Unlike `checkKotlinxCompatibility`, every failure is taken into account, rather than just + * [LinkageError]s. An incompatible version may fail in other ways (e.g., a `NullPointerException` + * under R8) or silently encode wrong arguments, and recording no arguments is better than recording + * wrong ones. + */ +internal fun kotlinxEncoderIncompatibility( + /** Encodes [COMPATIBILITY_CHECK_VALUE] to the provided [ArgumentSink]. */ + encode: (ArgumentSink) -> Unit = ::encodeCompatibilityCheckValue, +): Throwable? = + try { + val sink = TreeArgumentSink(ArgumentBudget()) + encode(sink) + if (sink.argumentsOrThrow() == COMPATIBILITY_CHECK_ENCODING) { + null + } else { + EncoderProducedUnexpectedOutput() + } + } catch (e: LinkageError) { + // Returned rather than rethrown, so that an encoder that can't link only disables properties. + // Rethrown, it would fail the mapper's creation, and entries would lose their names too. + e + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad b/c an incompatible kotlinx.serialization version can fail the encoder in many ways. + ExceptionUtils.rethrowIfFatal(t) + t + } + +/** Encodes [COMPATIBILITY_CHECK_VALUE] to [sink], using only built-in serializers. */ +internal fun encodeCompatibilityCheckValue(sink: ArgumentSink) { + @Suppress("UNCHECKED_CAST") + KotlinxPropertiesEncoder.encode( + TripleSerializer( + String.serializer(), + ListSerializer(Int.serializer().nullable), + MapSerializer(String.serializer(), UInt.serializer()), + ) + as KSerializer, + COMPATIBILITY_CHECK_VALUE, + sink, + ) +} + +/** + * The value [kotlinxEncoderIncompatibility] encodes to check the properties encoder. + * + * Covers classes, lists, maps, nulls, and, through [UInt], value classes and the conversion of + * unsigned numbers, which encode wrong values rather than fail if kotlinx.serialization changes how + * it encodes them. + */ +private val COMPATIBILITY_CHECK_VALUE = + Triple("check", listOf(1, null), mapOf("count" to UInt.MAX_VALUE)) + +/** + * The expected encoding of [COMPATIBILITY_CHECK_VALUE]. + * + * None of its keys are on the + * [sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist), + * so none are filtered. + */ +private val COMPATIBILITY_CHECK_ENCODING: Map = + mapOf( + "first" to "check", + "second" to listOf(1, null), + "third" to mapOf("count" to UInt.MAX_VALUE.toLong()), + ) + +/** + * Signals that the properties encoder produced unexpected output for [COMPATIBILITY_CHECK_VALUE]. + * + * Suggests the app's `kotlinx-serialization-core` version shouldn't be trusted because it will + * likely mis-encode other properties, too. + */ +internal class EncoderProducedUnexpectedOutput : + RuntimeException( + // Message deliberately omits any back stack entry data, which could be sensitive. + "The kotlinx.serialization properties encoder produced unexpected output.", + ) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt new file mode 100644 index 00000000000..a42d66ee4bf --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt @@ -0,0 +1,471 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.util.HttpUtils +import io.sentry.util.UrlUtils +import java.math.BigInteger +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerializationException +import kotlinx.serialization.SerializationStrategy +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.StructureKind +import kotlinx.serialization.encoding.AbstractEncoder +import kotlinx.serialization.encoding.CompositeEncoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.modules.EmptySerializersModule +import kotlinx.serialization.modules.SerializersModule + +/** + * Encodes the properties of a `@Serializable` back stack entry as maps, lists, and scalars for use + * as [SentryBackStackEntry.arguments]. + * + * **Encoding formats** + * + * Uses a custom tree encoder because `kotlinx-serialization-core` provides no output format and + * Nav3 apps may not include `kotlinx-serialization-json`. + * + * - Classes and objects become property maps. Objects without properties record no arguments. + * + * - Lists and sets become lists. Maps use stringified scalar keys, such as strings, numbers, or + * enums. Structured map keys are rejected, matching `kotlinx-serialization-json`'s defaults. + * + * - Enums use their serial names. Value classes use their underlying values. + * + * - Unsigned numbers (`UByte`, `UShort`, `UInt`, `ULong`) retain their unsigned values. + * + * - Polymorphic properties become `{"type": , "value": }`. + * + * - Entries encoded as scalars, such as by a custom string serializer, become `{"value": }`. + * + * - Properties marked `@Transient` are omitted. + * + * **Argument limits** + * + * Writes through [ArgumentSink], which enforces the same size and structural limits as for custom + * mappers. Violations throw [DropArgumentsException], bounding traversal and allocation for cyclic, + * deeply nested, or large entries. + * + * Custom serializers can recurse without nesting properties, bypassing the sink's depth limit. The + * encoder separately limits nested serializer calls to [MAX_SERIALIZER_NESTING]. + * + * **Sensitive data** + * + * Values under property names or map keys matching Sentry's + * [sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist) + * are replaced with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE] without invoking their serializers. + * + * [SensitiveKeyFilter] checks every key the encoders write, and the encoders read its decision to + * skip filtered values' serializers. [ValueEncoder.encodeInline] also checks value classes' + * underlying property names, which aren't written as keys. + * + * The denylist originates from filtering HTTP headers, cookies, and query parameters. This encoder + * applies it to navigation arguments as a baseline for sensitive-data filtering. + */ +internal object KotlinxPropertiesEncoder { + + /** Key for top-level values encoded without a map, such as by a custom serializer. */ + const val VALUE_KEY: String = "value" + + /** + * Encodes [value] with [serializer], writing its top-level properties to [sink]'s root map. + * + * Throws [SerializationException] when a value cannot be encoded, such as when a contextual or + * open polymorphic property has no registered serializer. Throws [DropArgumentsException] when an + * argument limit is exceeded. + * + * Limit failures, including [MAX_SERIALIZER_NESTING], are recorded on [sink]. A serializer can + * catch [DropArgumentsException] and then throw a different exception or return normally, so read + * the outcome from the sink, e.g., with [TreeArgumentSink.write]. + */ + fun encode(serializer: KSerializer, value: Any, sink: ArgumentSink) { + val filteredSink = SensitiveKeyFilter(sink) + RootEncoder(filteredSink, SerializerNesting(filteredSink)) + .encodeSerializableValue(serializer, value) + // Checked here rather than when the arguments are read, so that a custom serializer that stops + // part-way is reported as an encoding failure on every path. + filteredSink.checkComplete() + } + + /** Encodes a single value and writes it to [sink]. Structures are delegated to child encoders. */ + private open class ValueEncoder( + protected val sink: SensitiveKeyFilter, + protected val nesting: SerializerNesting, + ) : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + protected open fun put(value: Any?) { + sink.scalar(value) + } + + /** Replaces a filtered value with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE]. */ + protected open fun putFiltered() { + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + } + + override fun encodeSerializableValue(serializer: SerializationStrategy, value: T) { + nesting.enter() + try { + serializer.serialize(this, value) + } finally { + nesting.exit() + } + } + + override fun encodeValue(value: Any) { + put(value) + } + + override fun encodeNull() { + put(null) + } + + override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) { + put(enumDescriptor.getElementName(index)) + } + + override fun encodeInline(descriptor: SerialDescriptor): Encoder = + when { + descriptor.serialName in UNSIGNED_SERIAL_NAMES -> UnsignedEncoder(::put) + // A value class records only its underlying value, so its underlying property's name + // never reaches encodeElement. We check it here instead. + descriptor.hasSensitiveUnderlyingProperty() -> { + putFiltered() + DiscardingEncoder + } + else -> this + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder = + // The sink checks the depth as the structure begins, so a cyclic or deeply nested entry + // stops here instead of recursing until the stack overflows. + when (descriptor.kind) { + StructureKind.LIST -> { + sink.beginList() + ListEncoder(sink, nesting) + } + StructureKind.MAP -> { + sink.beginMap() + MapEncoder(sink, nesting) + } + else -> { + sink.beginMap() + ClassEncoder(sink, nesting) + } + } + } + + /** + * Encodes the entry itself. A class's properties, or a map's entries, are written to the sink's + * root map. Anything else (e.g., a custom serializer that encodes to a string) is written under + * [VALUE_KEY]. + */ + private class RootEncoder(sink: SensitiveKeyFilter, nesting: SerializerNesting) : + ValueEncoder(sink, nesting) { + + override fun put(value: Any?) { + sink.key(VALUE_KEY) + sink.scalar(value) + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder = + when (descriptor.kind) { + StructureKind.LIST -> { + sink.key(VALUE_KEY) + super.beginStructure(descriptor) + } + StructureKind.MAP -> MapEncoder(sink, nesting, isRoot = true) + else -> ClassEncoder(sink, nesting, isRoot = true) + } + } + + /** + * Writes the elements of a class, object, or polymorphic value as a map. + * + * If [isRoot] is true, uses the sink's already-open root map. + */ + private class ClassEncoder( + sink: SensitiveKeyFilter, + nesting: SerializerNesting, + private val isRoot: Boolean = false, + ) : ValueEncoder(sink, nesting) { + + override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean { + sink.key(descriptor.getElementName(index)) + if (sink.isNextValueSensitive) { + // Skipping the element keeps a sensitive value's own serializers from running. + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + return false + } + return true + } + + override fun endStructure(descriptor: SerialDescriptor) { + if (!isRoot) { + sink.end() + } + } + } + + /** Writes the elements of a list or set. */ + private class ListEncoder(sink: SensitiveKeyFilter, nesting: SerializerNesting) : + ValueEncoder(sink, nesting) { + + override fun endStructure(descriptor: SerialDescriptor) { + sink.end() + } + } + + /** + * Writes alternating map keys and values. If [isRoot] is true, uses the sink's already-open root + * map. + * + * Keys must be scalars and are recorded as strings, matching kotlinx-serialization-json's + * defaults. Stringifying structured keys could exhaust memory before the sink checks their size. + * + * Sensitive key text causes the value to be filtered. If the key itself was filtered because of a + * sensitive value-class property, its original text is unavailable, so the value is filtered too. + * Every such entry records the same substitute key and value, so only the first is written. + * + * Skipped entries write nothing, so the sink's limits can't bound how many are visited. A map + * that skips more than [MAX_ARGUMENT_VALUES] entries drops the arguments as over the value limit, + * which its entries would have broken unfiltered too. + */ + private class MapEncoder( + sink: SensitiveKeyFilter, + nesting: SerializerNesting, + private val isRoot: Boolean = false, + ) : ValueEncoder(sink, nesting) { + + private var isKey = true + private var isCurrentValueSensitive = false + private var hasFilteredKey = false + private var isCurrentEntrySkipped = false + private var skippedEntries = 0 + + override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean { + isKey = index % 2 == 0 + // Each key is encoded before its value, so the flags a key sets already apply to its value. + return when { + isKey -> { + isCurrentValueSensitive = false + isCurrentEntrySkipped = false + true + } + isCurrentEntrySkipped -> false + isCurrentValueSensitive -> { + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + false + } + else -> true + } + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { + if (isKey) { + throw SerializationException( + "Back stack entry has a map key that's a structure (${descriptor.serialName}). Only " + + "scalar map keys are supported.", + ) + } + return super.beginStructure(descriptor) + } + + override fun put(value: Any?) { + if (isKey) { + // The filter lets the sink reject oversized keys before its denylist scan allocates a + // lowercase copy. + sink.key(value.toString()) + isCurrentValueSensitive = sink.isNextValueSensitive + } else { + sink.scalar(value) + } + } + + override fun putFiltered() { + if (!isKey) { + super.putFiltered() + } else if (hasFilteredKey) { + if (++skippedEntries > MAX_ARGUMENT_VALUES) { + sink.reject(ArgumentDropReason.MAX_COUNT, DropArgumentsException.MAX_COUNT_WARNING) + } + isCurrentEntrySkipped = true + } else { + sink.key(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + hasFilteredKey = true + isCurrentValueSensitive = true + } + } + + override fun endStructure(descriptor: SerialDescriptor) { + if (!isRoot) { + sink.end() + } + } + } + + /** + * Maximum nested [Encoder.encodeSerializableValue] calls per entry. + * + * Allows room for property serializers and polymorphic or value-class wrappers within + * [MAX_ARGUMENT_DEPTH]. Guards against stack overflow when serializers recurse without nesting + * properties, which the argument depth limit can't detect. + */ + const val MAX_SERIALIZER_NESTING: Int = 64 + + /** + * Serial names of the unsigned number types, whose serializers encode them inline as their + * same-width signed storage value (e.g. `UInt.MAX_VALUE` as `-1`). + * + * Read from kotlinx.serialization's own serializers, so that the names can't drift from the + * library's. + */ + private val UNSIGNED_SERIAL_NAMES: Set = + listOf(UByte.serializer(), UShort.serializer(), UInt.serializer(), ULong.serializer()).mapTo( + HashSet(), + ) { + it.descriptor.serialName + } + + /** Whether this describes a value class whose underlying property's name is sensitive. */ + private fun SerialDescriptor.hasSensitiveUnderlyingProperty(): Boolean = + isInline && elementsCount == 1 && isSensitive(getElementName(0)) + + /** + * Discards a value class's underlying value after its filtered substitute has been recorded. + * + * Skips nested serializers, matching the handling of sensitive properties. + */ + private object DiscardingEncoder : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + override fun encodeValue(value: Any) = Unit + + override fun encodeNull() = Unit + + override fun encodeSerializableValue(serializer: SerializationStrategy, value: T) = Unit + + override fun encodeNullableSerializableValue( + serializer: SerializationStrategy, + value: T?, + ) = Unit + } + + /** + * Converts the signed storage value of an unsigned number back to its unsigned value and hands it + * to [put]. `ULong`s beyond `Long.MAX_VALUE` become [BigInteger]s. + */ + private class UnsignedEncoder(private val put: (Any?) -> Unit) : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + override fun encodeValue(value: Any) { + put( + when (value) { + is Byte -> value.toUByte().toInt() + is Short -> value.toUShort().toInt() + is Int -> value.toUInt().toLong() + is Long -> if (value >= 0) value else BigInteger(value.toULong().toString()) + else -> value + }, + ) + } + } + + /** + * Limits nested [Encoder.encodeSerializableValue] calls for one entry, rejecting it through + * [sink] when nesting exceeds [MAX_SERIALIZER_NESTING]. + * + * After any sink failure, [enter] rethrows that failure to prevent further serializer calls, even + * if a serializer catches the original exception. + */ + private class SerializerNesting(private val sink: ArgumentSink) { + + private var calls = 0 + + fun enter() { + sink.checkNotDropped() + if (++calls > MAX_SERIALIZER_NESTING) { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArgumentsException.STRUCTURE_WARNING) + } + } + + fun exit() { + calls-- + } + } + + /** + * Replaces scalar values under sensitive keys with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE] before + * forwarding them to [sink]. + * + * All encoders write through this filter to keep sensitive values out of the output. They read + * [isNextValueSensitive] after writing a key to skip the serializers of values that will be + * filtered, avoiding work and potential failures. As a result, no map or list starts under a + * sensitive key; one that does throws an [ArgumentProtocolException], which drops the entry's + * arguments rather than recording what's under the key. + * + * The encoders write values only through [scalar]. The inherited [computedScalar] computes a + * value before filtering it. + */ + internal class SensitiveKeyFilter(private val sink: ArgumentSink) : ArgumentSink { + + /** Whether the value written next is filtered, because the last key written is sensitive. */ + var isNextValueSensitive = false + private set + + override fun checkNotDropped() { + sink.checkNotDropped() + } + + override fun beginMap() { + begin { sink.beginMap() } + } + + override fun beginList() { + begin { sink.beginList() } + } + + override fun key(name: String, describeDuplicate: () -> String) { + sink.key(name, describeDuplicate) + isNextValueSensitive = isSensitive(name) + } + + override fun scalar(value: Any?) { + sink.scalar(if (isNextValueSensitive) UrlUtils.SENSITIVE_DATA_SUBSTITUTE else value) + isNextValueSensitive = false + } + + override fun end() { + sink.end() + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing = + sink.reject(reason, warning) + + override fun checkComplete() { + sink.checkComplete() + } + + private inline fun begin(beginInSink: () -> Unit) { + if (isNextValueSensitive) { + throw ArgumentProtocolException("A map or list was started under a sensitive key.") + } + beginInSink() + } + } + + /** Whether [key] is sensitive and its value should be filtered. */ + private fun isSensitive(key: String): Boolean = HttpUtils.containsSensitiveDataKey(key) +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt index 919c915535c..47f42db1bb4 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -5,12 +5,13 @@ import kotlinx.serialization.KSerializer import kotlinx.serialization.serializerOrNull /** - * Returns [type]'s serializer, or `null` if unavailable, including when type arguments are needed. - * Extends [serializerOrNull] to support private `@Serializable` objects. Also supports built-in - * types and unannotated enums. + * Returns [type]'s serializer, or `null` if it has no serializer or if `type` is generic. * - * May execute serializer code and throw. What that code throws through reflection, including fatal - * errors such as [OutOfMemoryError], arrives wrapped in an [InvocationTargetException]. + * Like [serializerOrNull], which it extends, it returns serializers for built-in types and enums + * that aren't `@Serializable`; unlike it, it also supports private `@Serializable` objects. + * + * May execute serializer code and throw. Whatever that code throws via reflection, including fatal + * errors such as [OutOfMemoryError], will arrive wrapped in an [InvocationTargetException]. */ @Suppress("SwallowedException") internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = @@ -23,9 +24,9 @@ internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = } /** - * Uses reflection to look up the serializer of a private `@Serializable object` through the members - * the serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules - * keep both members.) kotlinx.serialization's own object lookup reads the same two members, so this + * Uses reflection to look up the serializer of a private `@Serializable object` via the members the + * serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules keep + * both members.) kotlinx.serialization's own object lookup reads the same two members, so this * fallback can break only if that lookup breaks too. * * Propagates any exception thrown by the reflective lookup. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md index ba524b283c2..c68defa962f 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -42,7 +42,8 @@ Recommended rules for raising the floor: - Raise it in a reviewed change of its own, with a CHANGELOG entry and a corresponding update to the [Sentry Nav3 docs](https://docs.sentry.io/platforms/android/integrations/navigation/#navigation-3). -- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `internal/common/KotlinxSerializationSupport.kt` to match. A unit test will fail if the two differ. +- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `internal/common/KotlinxSerializationSupport.kt` to match. A unit test will fail if the two + differ. ## Minification diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt new file mode 100644 index 00000000000..b98fe151fd9 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt @@ -0,0 +1,244 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason + +/** + * The core protocol for the subsystem that converts properties of back stack entries into Sentry + * arguments. + * + * An [ArgumentSource] pushes information about one back stack entry's properties into a sink as the + * source produces them. Sink implementations are expected to materialize the provided info into a + * tree of arguments, where the tree has a bounded size and height. + * + * Sinks must throw a [DropArgumentsException] if a write violates a constraint or [reject] is + * called. Every write thereafter will throw the same exception. [TreeArgumentSink.write] runs a + * source and returns an [ArgumentWriteResult], so that callers needn't work out which failure + * decides the outcome. + * + * **The argument conversion subsystem** + * + * With Nav3, host apps manage their own nav back stack, which they implement as a list of + * arbitrarily typed entries. In order to be displayed in Sentry, each of those entries has to be + * mapped to a Sentry name (e.g., ProductDetailScreen) and zero or more arguments (e.g., + * productId="123abc"). There are two ways for host apps to provide us with those mappings: + * + * 1. via a custom `BackStackEntryMapper`; or + * + * 2. via one of our own built-in mappers (viz., `BackStackEntryMapper.SerialName` or + * `BackStackEntryMapper.SerialNameAndProperties`). + * + * `ArgumentSink` and `ArgumentSource` create the seam that lets us support differentiated + * processing on the source side (the host app's logic vs built-in logic) but uniform processing on + * the sink side (argument pruning, protecting against constraint violation, and tree + * materialization). + * + * Here are the moving parts: + * ```text + * ArgumentSource + * Custom mapper Built-in mappers + * ┌────────────────────┐ ┌───────────────────────┐ + * │ HostArgumentSource │ │ KotlinxArgumentSource │ + * │ (plain host map) │ │ (drives encoder) │ + * └────────┬───────────┘ └────────┬──────────────┘ + * │ │ via + * │ KotlinxPropertiesEncoder + SensitiveKeyFilter + * │ │ + * └──────────────┬──────────────┘ + * ▼ + * ┌───────────────────────────────┐ + * │ ArgumentSink │ + * └───────────────────────────────┘ + * ▲ implements + * ┌───────────────┴───────────────┐ + * │ TreeArgumentSink │ + * │ │ ┌────────────────────────┐ + * │ Enforce + materialize: │ spends ──▶│ ArgumentBudget │ + * │ • builds the argument tree │ └────────────────────────┘ + * │ • prevents constraint │ ┌────────────────────────┐ + * │ violation (e.g., depth) │ throws ──▶│ DropArgumentsException │ + * └───────────────────────────────┘ └────────────────────────┘ + * + * Note: BackStackConverter.ArgumentSanitizer owns the ArgumentBudget. It + * selects the ArgumentSource based on the mapper the host app provides. + * ``` + */ +internal interface ArgumentSink { + + /** + * Throws the first [DropArgumentsException] that a write or [reject] threw, if any, even if a + * source caught it. Lets a source stop before running more host app code for an entry whose + * arguments will be dropped. + */ + fun checkNotDropped() + + /** Starts a map as the next value. Call [end] when finished. */ + fun beginMap() + + /** Starts a list as the next value. Call [end] when finished. */ + fun beginList() + + /** + * Names the next value in the current map. + * + * Throws [DropArgumentsException] if the map already has a value named [name], as recording only + * one of them would show Sentry a partial map as if it were complete. [describeDuplicate] returns + * the warning to log in that case. + */ + fun key( + name: String, + describeDuplicate: () -> String = { DropArgumentsException.DUPLICATE_KEY_WARNING }, + ) + + /** + * Writes [value] as the next value. Supports `null`, [Boolean], [Number], [CharSequence], and + * [Char]; text is recorded as a [String]. + */ + fun scalar(value: Any?) + + /** + * Writes the value [compute] returns as the next value, as for [scalar]. A sink that enforces + * limits checks that the value can be written before calling [compute], so that host app code + * (e.g., a `toString()`) doesn't run for a value that won't be recorded, and can't replace the + * limit's drop reason with its own failure. + */ + fun computedScalar(compute: () -> Any?) { + scalar(compute()) + } + + /** Ends the most recently started map or list. */ + fun end() + + /** + * Reports the violation of a constraint that a source enforces itself, rather than one broken via + * a write (e.g., a host app's map that contains itself, or how deeply serializers nest). Throws + * the resulting [DropArgumentsException]. + * + * If a constraint was already violated, throws its `DropArgumentsException` instead. + */ + fun reject(reason: ArgumentDropReason, warning: String): Nothing + + /** + * Throws [ArgumentProtocolException] if a map or list is still open or a key has no value, so + * that a source that stops part-way doesn't record a partial tree as complete. Call after the + * last write. + */ + fun checkComplete() +} + +/** + * Something that knows how to write a back stack entry's properties or arguments to an + * [ArgumentSink]. + * + * Sources have the following responsibilities: + * + * - choose which data to expose to the sink; and + * + * - enforce constraints the sink can't address because they aren't reflected in the sink's + * materialized tree (e.g., prohibit cycles in a custom mapper's arguments). + * + * Sources may implement additional functionality as needed, e.g., the source backing + * `SerialNameAndProperties` filters sensitive values to comply with Sentry's + * [sensitive denylist policy](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist). + */ +internal fun interface ArgumentSource { + fun writeTo(sink: ArgumentSink) +} + +/** The outcome of writing one back stack entry's arguments with [TreeArgumentSink.write]. */ +internal sealed interface ArgumentWriteResult { + + /** The source wrote [arguments] without violating a constraint. */ + class Written(val arguments: Map) : ArgumentWriteResult + + /** + * A constraint was violated, so the entry's arguments are dropped for [drop]'s reason. This is + * the first violation, even if the source caught it and threw something else. + */ + class Dropped(val drop: DropArgumentsException) : ArgumentWriteResult + + /** The source threw [cause] without violating a constraint, e.g., a host app `toString()`. */ + class Failed(val cause: Throwable) : ArgumentWriteResult +} + +/** + * The value and character budgets shared by the entries of one back stack update. + * + * Throws a [DropArgumentsException] if the remaining budget is insufficient. + */ +internal class ArgumentBudget { + + private var remainingValues = MAX_ARGUMENT_VALUES + private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + + /** Spends one value. */ + fun spendValue() { + if (--remainingValues < 0) { + throw DropArgumentsException( + ArgumentDropReason.MAX_COUNT, + DropArgumentsException.MAX_COUNT_WARNING, + ) + } + } + + /** + * Returns [text] as a [String] after spending its characters. + * + * Checks [text]'s length before converting it, so that host app text that doesn't fit isn't + * copied, and again after, in case a custom [CharSequence]'s length doesn't match its text. + */ + fun spendText(text: CharSequence): String { + checkFits(text.length) + val string = text.toString() + checkFits(string.length) + remainingCharacters -= string.length + return string + } + + private fun checkFits(characters: Int) { + if (characters > remainingCharacters) { + throw DropArgumentsException( + ArgumentDropReason.CHARACTER_LIMIT, + DropArgumentsException.MAX_CHARACTER_WARNING, + ) + } + } +} + +/** + * Thrown when an [ArgumentSink] is written to out of order or with a value it can't record, e.g., a + * map value without a key. + * + * Signals either a bug in the SDK or a custom serializer that writes values outside its elements, + * as opposed to a serializer that threw an exception of its own. + */ +internal class ArgumentProtocolException(message: String) : IllegalStateException(message) + +/** + * Control-flow signal to drop a back stack entry's arguments, logging [warning]. Overrides + * [fillInStackTrace] to skip stack-trace capture. + */ +internal class DropArgumentsException(val reason: ArgumentDropReason, val warning: String) : + RuntimeException() { + + override fun fillInStackTrace(): Throwable = this + + companion object { + + const val DUPLICATE_KEY_WARNING = + "Nav3 map keys stringify to the same string. Dropping this entry's arguments." + + const val MAX_CHARACTER_WARNING = + "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + + "this and older entries." + + const val MAX_COUNT_WARNING = + "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + + "and older entries." + + const val STRUCTURE_WARNING = + "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + + "entry's arguments." + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSource.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSource.kt new file mode 100644 index 00000000000..1756795a8d1 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSource.kt @@ -0,0 +1,124 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import java.util.Collections +import java.util.IdentityHashMap + +/** + * An [ArgumentSource] for writing [the argument map][arguments] produced by a host app to an + * [ArgumentSink]. + * + * Nested maps are traversed recursively, collections and arrays become lists, and enums use their + * names. Map keys and unsupported values are stringified; unsupported types are reported to + * [onUnsupportedValue]. + * + * Traversal and string conversion may invoke host app code. + * + * **Rejects cycles** + * + * A map, collection, or array that contains itself, directly or through nested values, is a cycle, + * which this source [rejects][ArgumentSink.reject] as `INVALID_STRUCTURE` rather than writing the + * same object again until the depth limit is reached. + * + * An object that appears more than once without containing itself is written each time. + */ +internal class HostArgumentSource( + private val arguments: Map<*, *>, + private val onUnsupportedValue: (typeName: String?) -> Unit, +) : ArgumentSource { + + override fun writeTo(sink: ArgumentSink) { + Traversal(sink).writeEntries(arguments) + } + + /** Writes [arguments] to [sink] once, tracking the containers being written. */ + private inner class Traversal(private val sink: ArgumentSink) { + + /** The maps, collections, and arrays being written, by identity, starting with [arguments]. */ + private val open: MutableSet = + Collections.newSetFromMap(IdentityHashMap()).apply { add(arguments) } + + fun writeEntries(map: Map<*, *>) { + for ((key, value) in map) { + val name = key.toString() + sink.key(name) { duplicateKeyWarning(map, key, name) } + write(value) + } + } + + private fun write(value: Any?) { + val collection = value?.asCollectionOrNull() + when { + value is Map<*, *> -> writeContainer(value, sink::beginMap) { writeEntries(value) } + collection != null -> + writeContainer(value, sink::beginList) { + // Iterated without reading the collection's size, which the host app controls. + for (element in collection) { + write(element) + } + } + // Computed only once the sink has checked the value fits, as it may run host app code. + else -> sink.computedScalar { scalarOf(value) } + } + } + + private inline fun writeContainer( + container: Any, + begin: () -> Unit, + writeContents: () -> Unit, + ) { + // Begun before the cycle check, so that the sink's depth and value limits take precedence: + // the values they spend come from a budget that later entries share. + begin() + if (!open.add(container)) { + sink.reject( + ArgumentDropReason.INVALID_STRUCTURE, + DropArgumentsException.STRUCTURE_WARNING, + ) + } + writeContents() + open.remove(container) + sink.end() + } + } + + private fun scalarOf(value: Any?): Any? = + when (value) { + null, + is Boolean, + is Number, + is CharSequence, + is Char -> value + is Enum<*> -> value.name + else -> { + onUnsupportedValue(value::class.simpleName) + value.toString() + } + } + + /** + * Names only the colliding keys' types, as the keys themselves may contain host data. Collisions + * are rare, so we re-scan [map] instead of tracking the original keys of every map. + */ + private fun duplicateKeyWarning(map: Map<*, *>, key: Any?, name: String): String { + val otherKey = map.keys.firstOrNull { it !== key && it.toString() == name } + return "A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same string " + + "as another key (${otherKey?.let { it::class.simpleName }}). Dropping this entry's arguments." + } +} + +/** Returns this collection, this array as a list, or `null` if it's neither. */ +private fun Any.asCollectionOrNull(): Collection<*>? = + when (this) { + is Collection<*> -> this + is Array<*> -> asList() + is BooleanArray -> asList() + is ByteArray -> asList() + is ShortArray -> asList() + is IntArray -> asList() + is LongArray -> asList() + is FloatArray -> asList() + is DoubleArray -> asList() + is CharArray -> asList() + else -> null + } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt new file mode 100644 index 00000000000..bf113f3eea8 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt @@ -0,0 +1,179 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.util.ExceptionUtils + +/** + * An [ArgumentSink] that materializes an argument tree for a single back stack entry and enforces + * argument constraints. + * + * **Argument constraints** + * + * Rejects excessive nesting, duplicate keys, and writes that exceed the value or character limits + * in [budget]. + * + * Once a constraint is violated or [reject] is called, a [DropArgumentsException] is thrown. Both + * subsequent writes and [argumentsOrThrow] rethrow the same failure to prevent an [ArgumentSource] + * from accidentally generating partial arguments. + * + * Use [write] to run a source and get its outcome. + */ +@Suppress("TooManyFunctions") +internal class TreeArgumentSink( + /** The argument budget shared across all back stack entries processed in one update. */ + private val budget: ArgumentBudget, +) : ArgumentSink { + + private val root = LinkedHashMap() + + /** The open containers, innermost last. */ + private val containers = ArrayList().apply { add(root) } + + private var pendingKey: String? = null + + /** The first [DropArgumentsException] a write or [reject] threw, or `null` if none has. */ + private var failure: DropArgumentsException? = null + + /** + * Has [source] write the entry's arguments to this sink and returns the outcome. + * + * A constraint violation this sink recorded decides the outcome over whatever [source] threw or + * returned, since a source that runs host app code may catch the violation and throw something + * else, or return normally. + */ + fun write(source: ArgumentSource): ArgumentWriteResult = + try { + source.writeTo(this) + ArgumentWriteResult.Written(argumentsOrThrow()) + } catch (drop: DropArgumentsException) { + ArgumentWriteResult.Dropped(failure ?: drop) + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because sources run host app code (e.g., serializers, toString()), which can throw + // anything. The entry's arguments are dropped; the caller logs the cause. + ExceptionUtils.rethrowIfFatal(t) + failure?.let { ArgumentWriteResult.Dropped(it) } ?: ArgumentWriteResult.Failed(t) + } + + override fun checkNotDropped() { + failure?.let { throw it } + } + + override fun beginMap() = guarded { begin(LinkedHashMap()) } + + override fun beginList() = guarded { begin(ArrayList()) } + + override fun key(name: String, describeDuplicate: () -> String) = guarded { + if (containers.last() !is Map<*, *>) { + throw ArgumentProtocolException("A key was written outside a map.") + } + if (pendingKey != null) { + throw ArgumentProtocolException("A key was written without a value.") + } + budget.spendText(name) + if ((containers.last() as? Map<*, *>)?.containsKey(name) == true) { + throw DropArgumentsException(ArgumentDropReason.DUPLICATE_KEY, describeDuplicate()) + } + pendingKey = name + } + + override fun scalar(value: Any?) = writeScalar { value } + + override fun computedScalar(compute: () -> Any?) = writeScalar(compute) + + override fun end() = guarded { + if (containers.size <= 1) { + throw ArgumentProtocolException("end() without an open map or list.") + } + containers.removeAt(containers.lastIndex) + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing { + checkNotDropped() + throw DropArgumentsException(reason, warning).also { failure = it } + } + + /** + * Returns the entry's arguments, or re-throws the [DropArgumentsException] a write threw, even if + * the source caught it. + * + * Should only be called after the [ArgumentSource] has completed all writes and closed every + * nested map and list. + */ + fun argumentsOrThrow(): Map { + checkNotDropped() + checkComplete() + return root + } + + override fun checkComplete() { + if (containers.size > 1) { + throw ArgumentProtocolException("A map or list was left open.") + } + if (pendingKey != null) { + throw ArgumentProtocolException("A key was written without a value.") + } + } + + private fun begin(container: Any) { + visitValue() + add(container) + containers += container + } + + /** Enforces the depth limit and spends one value for the value about to be added. */ + private fun visitValue() { + // A value added while n containers are open has a depth of n. + if (containers.size > MAX_ARGUMENT_DEPTH) { + throw DropArgumentsException( + ArgumentDropReason.INVALID_STRUCTURE, + DropArgumentsException.STRUCTURE_WARNING, + ) + } + budget.spendValue() + } + + @Suppress("UNCHECKED_CAST") + private fun add(value: Any?) { + when (val parent = containers.last()) { + is ArrayList<*> -> (parent as ArrayList) += value + else -> { + val key = + pendingKey ?: throw ArgumentProtocolException("A map value was written without a key.") + (parent as LinkedHashMap)[key] = value + pendingKey = null + } + } + } + + private inline fun writeScalar(compute: () -> Any?) = guarded { + visitValue() + add( + when (val value = compute()) { + null, + is Boolean -> value + // JSON has no NaN or infinity, and Sentry's JSON writer throws for them, which would drop + // the whole event these arguments are attached to. We record them as strings instead. + is Number -> if (value.isNonFinite()) budget.spendText(value.toString()) else value + is CharSequence -> budget.spendText(value) + is Char -> budget.spendText(value.toString()) + else -> + throw ArgumentProtocolException("Unsupported scalar of type ${value.javaClass.name}.") + }, + ) + } + + private inline fun guarded(write: () -> Unit) { + checkNotDropped() + try { + write() + } catch (e: DropArgumentsException) { + failure = e + throw e + } + } +} + +/** Whether this is a NaN or infinite `Double` or `Float`. */ +private fun Number.isNonFinite(): Boolean = + (this is Double && !isFinite()) || (this is Float && !isFinite()) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt index e9dbf053899..66e67d0f055 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt @@ -96,7 +96,7 @@ internal enum class UnknownEntryReason(val serializedValue: String) { } /** - * Why host-provided arguments were unavailable in emitted nav state. + * Why a back stack entry's arguments were unavailable in emitted nav state. * * Recorded under [ARGUMENT_DROP_REASON_KEY]. */ @@ -107,6 +107,7 @@ internal enum class ArgumentDropReason( CHARACTER_LIMIT("max_character_limit_exceeded", exhaustsUpdateBudget = true), DUPLICATE_KEY("duplicate_key"), + ENCODING_FAILED("encoding_failed"), INVALID_STRUCTURE("invalid_structure"), MAX_COUNT("max_argument_count_exceeded", exhaustsUpdateBudget = true), SANITIZATION_FAILED("sanitization_failed"); diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt index 6722f66584d..6ef8bff6973 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt @@ -14,4 +14,11 @@ class BackStackEntryMapperTest { assertThat(homeMapper).isSameInstanceAs(BuiltInBackStackEntryMappers.serialName) } + + @Test + fun `SerialNameAndProperties - returns the built-in properties mapper as a mapper for any entry type`() { + val homeMapper: BackStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties + + assertThat(homeMapper).isSameInstanceAs(BuiltInBackStackEntryMappers.serialNameAndProperties) + } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt index f75f7063b92..15b42808c5f 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt @@ -19,11 +19,13 @@ import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import io.sentry.Breadcrumb +import io.sentry.DataCollection import io.sentry.Hint import io.sentry.IScope import io.sentry.IScopes import io.sentry.ISentryClient import io.sentry.ITransaction +import io.sentry.KeyValueCollectionBehavior import io.sentry.PropagationContext import io.sentry.Scope import io.sentry.ScopeCallback @@ -34,8 +36,14 @@ import io.sentry.SentryTracer import io.sentry.TransactionContext import io.sentry.TransactionOptions import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator +import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import org.junit.Rule import org.junit.Test import org.junit.rules.TestWatcher @@ -81,6 +89,28 @@ class SentryNavEffectTest { @Serializable private data class SerializableProfileRoute(val userId: String) + @Serializable + @SerialName("Checkout") + private data class CheckoutRoute(val cartId: String, val authToken: String) + + @Serializable @SerialName("Cart") private data class CartRoute(val cartId: String) + + @Serializable + @SerialName("Account") + private data class AccountRoute(val accountId: String, val email: String) + + @Serializable(with = BrokenRouteSerializer::class) private class BrokenRoute + + /** Names [BrokenRoute] "Broken", but throws when encoding it. */ + private object BrokenRouteSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("Broken", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: BrokenRoute): Unit = error("can't encode") + + override fun deserialize(decoder: Decoder): BrokenRoute = BrokenRoute() + } + private class Fixture { val options = SentryOptions().apply { @@ -396,6 +426,113 @@ class SentryNavEffectTest { .inOrder() } + @Test + fun `SerialNameAndProperties records serial names with properties as arguments, filtering sensitive values`() { + val fixture = Fixture() + val backStack = mutableStateListOf(CheckoutRoute(cartId = "c-1", authToken = "secret")) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + assertThat(fixture.breadcrumbs.single().data["to"]).isEqualTo("/Checkout") + assertThat(fixture.breadcrumbs.single().data["to_arguments"]) + .isEqualTo(mapOf("cartId" to "c-1", "authToken" to "[Filtered]")) + assertThat(fixture.transactions.single().getData("arguments")) + .isEqualTo(mapOf("cartId" to "c-1", "authToken" to "[Filtered]")) + } + + @Test + fun `SerialNameAndProperties records PII properties without sendDefaultPii and with all data collection off`() { + val fixture = Fixture() + fixture.options.isSendDefaultPii = false + fixture.options.dataCollection = dataCollectionOff() + val backStack = mutableStateListOf(AccountRoute(accountId = "a-1", email = "a@b.c")) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + val arguments = mapOf("accountId" to "a-1", "email" to "a@b.c") + assertThat(fixture.breadcrumbs.single().data["to_arguments"]).isEqualTo(arguments) + assertThat(fixture.transactions.single().getData("arguments")).isEqualTo(arguments) + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo(listOf(mapOf("entry" to "/Account", "entry_arguments" to arguments))) + } + + @Test + fun `a mapper that wraps SerialNameAndProperties records the properties it doesn't remove`() { + val fixture = Fixture() + val backStack = mutableStateListOf(AccountRoute(accountId = "a-1", email = "a@b.c")) + val mapper = + BackStackEntryMapper { entry -> + BackStackEntryMapper.SerialNameAndProperties.map(entry)?.let { mapped -> + SentryBackStackEntry(mapped.name, mapped.arguments?.filterKeys { it != "email" }) + } + } + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = mapper, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + assertThat(fixture.breadcrumbs.single().data["to"]).isEqualTo("/Account") + assertThat(fixture.breadcrumbs.single().data["to_arguments"]) + .isEqualTo(mapOf("accountId" to "a-1")) + assertThat(fixture.transactions.single().getData("arguments")) + .isEqualTo(mapOf("accountId" to "a-1")) + } + + @Test + fun `SerialNameAndProperties drops only an unencodable route's properties, recording why`() { + val fixture = Fixture() + val backStack = mutableStateListOf(CartRoute(cartId = "c-1"), BrokenRoute()) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + val dropped = mapOf("dropped_by_sentry" to "encoding_failed") + assertThat(fixture.breadcrumbs.single().data["to"]).isEqualTo("/Broken") + assertThat(fixture.breadcrumbs.single().data["to_arguments"]).isEqualTo(dropped) + assertThat(fixture.transactions.single().name).isEqualTo("/Broken") + assertThat(fixture.transactions.single().getData("arguments")).isEqualTo(dropped) + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("entry" to "/Broken", "entry_arguments" to dropped), + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")), + ), + ) + } + @Test fun `updated entry mapper is used for later navigation changes`() { val fixture = Fixture() @@ -854,6 +991,21 @@ class SentryNavEffectTest { ) } + /** Turns off every data collection option. */ + private fun dataCollectionOff(): DataCollection = + DataCollection().apply { + userInfo = false + cookies = KeyValueCollectionBehavior.off() + urlQueryParams = KeyValueCollectionBehavior.off() + httpBodies = emptySet() + databaseQueryData = false + filePaths = false + httpHeaders.request = KeyValueCollectionBehavior.off() + httpHeaders.response = KeyValueCollectionBehavior.off() + graphql.document = false + graphql.variables = false + } + private fun IScope.navigationBackStack(): List>? { val navigationContext = contexts[NAVIGATION_CONTEXT_KEY] as? Map<*, *> ?: return null diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt index 15e30b16f49..e956f090b61 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt @@ -28,6 +28,20 @@ class SentryNavOptionsTest { assertThat(options.maxCapturedBackStackEntries).isEqualTo(0) } + @Test + fun `accepts 25 max captured backstack entries`() { + val options = SentryNavOptions { maxCapturedBackStackEntries = 25 } + + assertThat(options.maxCapturedBackStackEntries).isEqualTo(25) + } + + @Test + fun `captures at most 25 back stack entries when more are requested`() { + val options = SentryNavOptions { maxCapturedBackStackEntries = 26 } + + assertThat(options.maxCapturedBackStackEntries).isEqualTo(25) + } + @Test fun `rejects negative max captured backstack entries`() { val exception = 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 index d1b4a185615..170796764ff 100644 --- 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 @@ -6,17 +6,14 @@ import io.sentry.SentryLevel.WARNING 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 io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS -import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason -import java.math.BigDecimal -import java.util.AbstractCollection import kotlin.test.assertFailsWith import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq -import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -28,39 +25,6 @@ class ArgumentSanitizerTest { override fun toString(): String = "opaque-value" } - private enum class PrivacyMode { - PUBLIC, - PRIVATE; - - override fun toString(): String = name.lowercase() - } - - private class UserId(private val value: String) { - override fun toString(): String = value - } - - private class OpaqueIterable : Iterable { - override fun iterator(): Iterator = listOf("a").iterator() - - override fun toString(): String = "opaque-iterable" - } - - private class OpaqueSequence : Sequence { - override fun iterator(): Iterator = listOf("a").iterator() - - override fun toString(): String = "opaque-sequence" - } - - private class CountingValue { - var toStringCalls = 0 - private set - - override fun toString(): String { - toStringCalls++ - return "counting-value" - } - } - private class ThrowingValue(val failure: IllegalStateException = IllegalStateException("boom")) { @Suppress("ExceptionRaisedInUnexpectedLocation") override fun toString(): String = throw failure } @@ -70,28 +34,6 @@ class ArgumentSanitizerTest { private val laterArguments = mapOf("id" to "123") - /** Sanitizes an entry that leaves only [remaining] values of the shared budget. */ - private fun spendValuesExcept(remaining: Int) { - // A list and its elements. - val spent = - sanitizer.sanitizeEntry(mapOf("v" to List(MAX_ARGUMENT_VALUES - remaining - 1) { 0 })) - check(spent.dropReason == null) - } - - /** Sanitizes an entry that leaves only [remaining] characters of the shared budget. */ - private fun spendCharactersExcept(remaining: Int) { - val spent = - sanitizer.sanitizeEntry(mapOf("" to "x".repeat(MAX_ARGUMENT_CHARACTERS - remaining))) - check(spent.dropReason == null) - } - - /** Returns a root map whose [leaf] is nested in [levels] more maps, i.e., at depth levels + 1. */ - private fun nested(levels: Int, leaf: Any?): Map { - var value: Any? = leaf - repeat(levels) { value = mapOf("n" to value) } - return mapOf("n" to value) - } - private companion object { private const val UNSUPPORTED_VALUE_WARNING = "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + @@ -117,199 +59,8 @@ class ArgumentSanitizerTest { assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), dropReason = null)) } - @Test - fun `sanitizeEntry() - keeps arguments in the order of the map`() { - val arguments = linkedMapOf("b" to 1, "a" to 2, "c" to 3) - - val sanitized = sanitizer.sanitizeEntry(arguments) - - assertThat(sanitized.values.keys).containsExactly("b", "a", "c").inOrder() - } - - @Test - fun `sanitizeEntry() - records map keys by toString()`() { - val sanitized = sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", UserId("u") to "b"))) - - assertThat(sanitized.values).isEqualTo(mapOf("nested" to mapOf("1" to "a", "u" to "b"))) - } - - // Containers - - @Test - fun `sanitizeEntry() - records collections and object arrays as lists`() { - val sanitized = - sanitizer.sanitizeEntry( - mapOf("set" to linkedSetOf("a", "b"), "array" to arrayOf(1, "x", null)), - ) - - assertThat(sanitized.values) - .isEqualTo(mapOf("set" to listOf("a", "b"), "array" to listOf(1, "x", null))) - } - - @Test - fun `sanitizeEntry() - records primitive arrays as lists of their elements`() { - val sanitized = - sanitizer.sanitizeEntry( - mapOf( - "booleans" to booleanArrayOf(true), - "bytes" to byteArrayOf(1), - "shorts" to shortArrayOf(2), - "ints" to intArrayOf(3), - "longs" to longArrayOf(4), - "floats" to floatArrayOf(5f), - "doubles" to doubleArrayOf(6.0), - "chars" to charArrayOf('c'), - ), - ) - - assertThat(sanitized.values) - .isEqualTo( - mapOf( - "booleans" to listOf(true), - "bytes" to listOf(1.toByte()), - "shorts" to listOf(2.toShort()), - "ints" to listOf(3), - "longs" to listOf(4L), - "floats" to listOf(5f), - "doubles" to listOf(6.0), - "chars" to listOf("c"), - ), - ) - } - - @Test - fun `sanitizeEntry() - records a map inside a list`() { - val sanitized = sanitizer.sanitizeEntry(mapOf("items" to listOf(mapOf(1 to "a")))) - - assertThat(sanitized.values).isEqualTo(mapOf("items" to listOf(mapOf("1" to "a")))) - } - - @Test - fun `sanitizeEntry() - doesn't read the size of a collection`() { - val values = - object : AbstractCollection() { - var wasSizeRead = false - - override val size: Int - get() { - wasSizeRead = true - return Int.MAX_VALUE - } - - override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() - } - - val sanitized = sanitizer.sanitizeEntry(mapOf("values" to values)) - - assertThat(sanitized.values).isEqualTo(mapOf("values" to listOf(1, 2))) - assertThat(values.wasSizeRead).isFalse() - } - - @Test - fun `sanitizeEntry() - records the same container in sibling positions twice`() { - val shared = listOf(1) - - val sanitized = sanitizer.sanitizeEntry(mapOf("a" to shared, "b" to shared)) - - assertThat(sanitized.values).isEqualTo(mapOf("a" to listOf(1), "b" to listOf(1))) - } - - @Test - fun `sanitizeEntry() - records the same key in a nested map and its parent`() { - val sanitized = sanitizer.sanitizeEntry(mapOf("id" to 1, "nested" to mapOf("id" to 2))) - - assertThat(sanitized.values).isEqualTo(mapOf("id" to 1, "nested" to mapOf("id" to 2))) - } - - // Scalars - - @Test - fun `sanitizeEntry() - records null, Boolean, and finite Number values unchanged`() { - val bigDecimal = BigDecimal("1.25") - - val sanitized = - sanitizer.sanitizeEntry(mapOf("null" to null, "boolean" to true, "big" to bigDecimal)) - - assertThat(sanitized.values) - .isEqualTo(mapOf("null" to null, "boolean" to true, "big" to bigDecimal)) - } - - @Test - fun `sanitizeEntry() - records CharSequence and Char values as Strings`() { - val sanitized = - sanitizer.sanitizeEntry(mapOf("builder" to StringBuilder("text"), "char" to 'c')) - - assertThat(sanitized.values).isEqualTo(mapOf("builder" to "text", "char" to "c")) - } - - @Test - fun `sanitizeEntry() - records non-finite Double and Float values as Strings`() { - val sanitized = - sanitizer.sanitizeEntry( - mapOf( - "nan" to Double.NaN, - "infinity" to Double.POSITIVE_INFINITY, - "negativeInfinity" to Float.NEGATIVE_INFINITY, - ), - ) - - assertThat(sanitized.values) - .isEqualTo(mapOf("nan" to "NaN", "infinity" to "Infinity", "negativeInfinity" to "-Infinity")) - } - - @Test - fun `sanitizeEntry() - records enums by name rather than toString()`() { - val sanitized = sanitizer.sanitizeEntry(mapOf("mode" to PrivacyMode.PRIVATE)) - - assertThat(sanitized.values).isEqualTo(mapOf("mode" to "PRIVATE")) - } - // Unsupported values - @Test - fun `sanitizeEntry() - records an unsupported value by toString()`() { - val sanitized = sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) - - assertThat(sanitized.values).isEqualTo(mapOf("opaque" to "opaque-value")) - } - - @Test - fun `sanitizeEntry() - records an Iterable that isn't a Collection and a Sequence as unsupported values`() { - val sanitized = - sanitizer.sanitizeEntry(mapOf("iterable" to OpaqueIterable(), "sequence" to OpaqueSequence())) - - assertThat(sanitized.values) - .isEqualTo(mapOf("iterable" to "opaque-iterable", "sequence" to "opaque-sequence")) - } - - @Test - fun `sanitizeEntry() - doesn't log supported values as unsupported`() { - sanitizer.sanitizeEntry( - mapOf( - "string" to "s", - "number" to 1, - "enum" to PrivacyMode.PUBLIC, - "list" to listOf(1), - "array" to intArrayOf(1), - "map" to mapOf("k" to "v"), - ), - ) - - verify(logger, never()).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), any()) - } - - @Test - fun `sanitizeEntry() - logs an unsupported value of an anonymous type with a null type name`() { - val anonymous = - object { - override fun toString(): String = "anonymous" - } - - sanitizer.sanitizeEntry(mapOf("anonymous" to anonymous)) - - verify(logger).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), isNull()) - } - @Test fun `sanitizeEntry() - logs the unsupported value warning with the value type`() { sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) @@ -333,7 +84,7 @@ class ArgumentSanitizerTest { 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)) + verify(logger).log(eq(WARNING), eq(DropArgumentsException.MAX_COUNT_WARNING)) } @Test @@ -343,7 +94,7 @@ class ArgumentSanitizerTest { assertThat(sanitized) .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArgumentsException.MAX_CHARACTER_WARNING)) } @Test @@ -355,7 +106,7 @@ class ArgumentSanitizerTest { assertThat(sanitized) .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArgumentsException.STRUCTURE_WARNING)) } @Test @@ -374,269 +125,6 @@ class ArgumentSanitizerTest { ) } - @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)) - } - - @Test - fun `sanitizeEntry() - describes a duplicate key by the types of the colliding keys rather than their values`() { - sanitizer.sanitizeEntry( - mapOf("nested" to linkedMapOf(UserId("ada@example.com") to "a", "ada@example.com" to "b")), - ) - - verify(logger) - .log( - eq(WARNING), - eq( - "A Nav3 map key (String) stringifies to the same string as another key (UserId). " + - "Dropping this entry's arguments.", - ), - ) - } - - @Test - fun `sanitizeEntry() - describes a null or anonymous map key that collides with another key as null`() { - val anonymous = - object { - override fun toString(): String = "id" - } - - sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf("null" to "a", null to "b"))) - sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf("id" to "a", anonymous to "b"))) - - verify(logger, times(2)) - .log( - eq(WARNING), - eq( - "A Nav3 map key (null) stringifies to the same string as another key (String). " + - "Dropping this entry's arguments.", - ), - ) - } - - @Test - fun `sanitizeEntry() - drops arguments for a duplicate key whose value is a container`() { - val withMap = - sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to mapOf("k" to "v")))) - val withList = - sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to listOf(1)))) - - assertThat(withMap.dropReason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) - assertThat(withList.dropReason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) - } - - @Test - fun `sanitizeEntry() - drops arguments for a duplicate key, not the value limit, with no values left`() { - // Enough for the nested map and "a" only. - spendValuesExcept(remaining = 2) - - val sanitized = sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to "b"))) - - assertThat(sanitized.dropReason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) - } - - @Test - fun `sanitizeEntry() - doesn't spend a value for a duplicate key`() { - // Enough for the nested map, "a", and the later entry's value. - spendValuesExcept(remaining = 3) - sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to "b"))) - - val later = sanitizer.sanitizeEntry(mapOf("one" to 1)) - - assertThat(later).isEqualTo(SanitizedArguments(mapOf("one" to 1))) - } - - @Test - fun `sanitizeEntry() - doesn't convert a value under a duplicate key`() { - val value = CountingValue() - - sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to value))) - - assertThat(value.toStringCalls).isEqualTo(0) - } - - // Depth - - @Test - fun `sanitizeEntry() - records a scalar and a container at the maximum depth`() { - val scalarAtMax = nested(MAX_ARGUMENT_DEPTH - 1, leaf = 1) - val containerAtMax = nested(MAX_ARGUMENT_DEPTH - 1, leaf = emptyList()) - - val scalar = sanitizer.sanitizeEntry(scalarAtMax) - val container = sanitizer.sanitizeEntry(containerAtMax) - - assertThat(scalar).isEqualTo(SanitizedArguments(scalarAtMax)) - assertThat(container).isEqualTo(SanitizedArguments(containerAtMax)) - } - - @Test - fun `sanitizeEntry() - drops arguments for invalid structure past the maximum depth`() { - val sanitized = sanitizer.sanitizeEntry(nested(MAX_ARGUMENT_DEPTH, leaf = 1)) - - assertThat(sanitized) - .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) - } - - @Test - fun `sanitizeEntry() - doesn't convert a value past the maximum depth`() { - val value = CountingValue() - - sanitizer.sanitizeEntry(nested(MAX_ARGUMENT_DEPTH, leaf = value)) - - assertThat(value.toStringCalls).isEqualTo(0) - } - - @Test - fun `sanitizeEntry() - counts depth only through containers a value is nested in`() { - // Each sibling reaches the maximum depth on its own, which together they'd exceed. - val arguments = - mapOf( - "first" to nested(MAX_ARGUMENT_DEPTH - 2, leaf = 1), - "second" to nested(MAX_ARGUMENT_DEPTH - 2, leaf = 2), - ) - - val sanitized = sanitizer.sanitizeEntry(arguments) - - assertThat(sanitized).isEqualTo(SanitizedArguments(arguments)) - } - - // Cycles - - @Test - fun `sanitizeEntry() - drops arguments for invalid structure when a map contains itself`() { - val cyclic = mutableMapOf() - cyclic["self"] = cyclic - - val sanitized = sanitizer.sanitizeEntry(mapOf("cyclic" to cyclic)) - - assertThat(sanitized) - .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) - } - - @Test - fun `sanitizeEntry() - drops arguments for invalid structure when an array contains itself`() { - val cyclic = arrayOfNulls(1) - cyclic[0] = cyclic - - val sanitized = sanitizer.sanitizeEntry(mapOf("cyclic" to cyclic)) - - assertThat(sanitized) - .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) - } - - // Value and character budgets - - @Test - fun `sanitizeEntry() - spends one value per scalar and container but none for the root map or keys`() { - // "list" and its 2 elements, and "scalar": 4 values. - sanitizer.sanitizeEntry(mapOf("list" to listOf(1, 2), "scalar" to 3)) - val rest = mapOf("values" to List(MAX_ARGUMENT_VALUES - 4 - 1) { it }) - - val later = sanitizer.sanitizeEntry(rest) - - assertThat(later).isEqualTo(SanitizedArguments(rest)) - } - - @Test - fun `sanitizeEntry() - doesn't convert a value over the value budget`() { - spendValuesExcept(remaining = 0) - val value = CountingValue() - - // A fresh sanitizer would record it, so the shared budget is what stops it. - val sanitized = sanitizer.sanitizeEntry(mapOf("counting" to value)) - - assertThat(sanitized.dropReason).isEqualTo(ArgumentDropReason.MAX_COUNT) - assertThat(value.toStringCalls).isEqualTo(0) - verify(logger, never()).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), any()) - } - - @Test - fun `sanitizeEntry() - records text exactly as long as the remaining characters`() { - val sanitized = sanitizer.sanitizeEntry(mapOf("" to "x".repeat(MAX_ARGUMENT_CHARACTERS))) - - assertThat(sanitized.dropReason).isNull() - } - - @Test - fun `sanitizeEntry() - spends the characters of keys and of every text value`() { - // The values spend "cd" + "NaN" + "PUBLIC" + "e" + "opaque-value" = 2 + 3 + 6 + 1 + 12 = 24 - // characters, and the keys 2 + 0 + 1 + 2 + 3 = 8, for 32 in all. - sanitizer.sanitizeEntry( - linkedMapOf( - "ab" to "cd", - "" to Double.NaN, - " " to PrivacyMode.PUBLIC, - " " to 'e', - " " to OpaqueValue(), - ), - ) - val rest = mapOf("" to "x".repeat(MAX_ARGUMENT_CHARACTERS - 32)) - - val later = sanitizer.sanitizeEntry(rest) - val overflowing = sanitizer.sanitizeEntry(mapOf("" to "y")) - - assertThat(later).isEqualTo(SanitizedArguments(rest)) - assertThat(overflowing.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - - @Test - fun `sanitizeEntry() - doesn't spend characters for finite numbers, Booleans, or null`() { - sanitizer.sanitizeEntry(mapOf("" to 12345, " " to true, " " to null)) - // The keys above spend 0 + 1 + 2 = 3 characters. - val rest = mapOf("" to "x".repeat(MAX_ARGUMENT_CHARACTERS - 3)) - - val later = sanitizer.sanitizeEntry(rest) - val overflowing = sanitizer.sanitizeEntry(mapOf("" to "y")) - - assertThat(later).isEqualTo(SanitizedArguments(rest)) - assertThat(overflowing.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - - @Test - fun `sanitizeEntry() - doesn't convert text whose reported length doesn't fit`() { - spendCharactersExcept(remaining = 1) - val text = CountingText(length = 2, text = "ab") - - val sanitized = sanitizer.sanitizeEntry(mapOf("" to text)) - - assertThat(sanitized.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - assertThat(text.toStringCalls).isEqualTo(0) - } - - @Test - fun `sanitizeEntry() - drops text longer than its reported length when its text doesn't fit`() { - spendCharactersExcept(remaining = 1) - - val sanitized = sanitizer.sanitizeEntry(mapOf("" to CountingText(length = 1, text = "ab"))) - - assertThat(sanitized.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - - @Test - fun `sanitizeEntry() - spends the characters of text rather than its reported length`() { - spendCharactersExcept(remaining = 2) - sanitizer.sanitizeEntry(mapOf("" to CountingText(length = 0, text = "ab"))) - - val later = sanitizer.sanitizeEntry(mapOf("" to "c")) - - assertThat(later.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - // Budgets shared across entries @Test @@ -681,7 +169,8 @@ class ArgumentSanitizerTest { sanitizer.sanitizeEntry(mapOf("throwing" to throwing)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), eq(throwing.failure)) + verify(logger) + .log(eq(WARNING), eq(DropArgumentsException.STRUCTURE_WARNING), eq(throwing.failure)) } @Test @@ -695,18 +184,7 @@ class ArgumentSanitizerTest { 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()))) + .log(eq(WARNING), eq(DropArgumentsException.STRUCTURE_WARNING), any()) } // Later entries after a drop @@ -718,7 +196,7 @@ class ArgumentSanitizerTest { 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)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArgumentsException.MAX_COUNT_WARNING)) } @Test @@ -728,7 +206,7 @@ class ArgumentSanitizerTest { 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)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArgumentsException.MAX_CHARACTER_WARNING)) } @Test @@ -760,22 +238,3 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) } } - -/** - * Host app text that reports [length], which may differ from [text]'s, and counts its conversions - * to a `String` in [toStringCalls]. - */ -internal class CountingText(override val length: Int, private val text: String) : CharSequence { - var toStringCalls = 0 - private set - - override fun get(index: Int): Char = text[index] - - override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = - text.subSequence(startIndex, endIndex) - - override fun toString(): String { - toStringCalls++ - return text - } -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt index 92a433e38d6..c2fc9aad8cf 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -35,6 +35,8 @@ class BuiltInBackStackEntryMappersTest { @Serializable @SerialName("Home") data object Home + @Serializable @SerialName("Detail") data class Detail(val id: String) + data class NotSerializable(val id: String) private val kotlinxMapper = BackStackEntryMapper { SentryBackStackEntry("Kotlinx") } @@ -93,6 +95,65 @@ class BuiltInBackStackEntryMappersTest { assertThat(race.unavailableTypeWarnings).isEqualTo(1) } + // serialNameAndProperties + + @Test + fun `serialNameAndProperties - records properties as arguments`() { + val mapper = BuiltInBackStackEntryMappers.serialNameAndProperties + + val mapped = listOf(Home, Detail("1")).map(mapper::map) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("Home"), + SentryBackStackEntry("Detail", mapOf("id" to "1")), + ) + .inOrder() + } + + @Test + fun `serialNameAndProperties - returns the same mapper on every access`() { + assertThat(BuiltInBackStackEntryMappers.serialNameAndProperties) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialNameAndProperties) + } + + @Test + fun `serialNameAndProperties - is a different mapper from serialName`() { + assertThat(BuiltInBackStackEntryMappers.serialNameAndProperties) + .isNotSameInstanceAs(BuiltInBackStackEntryMappers.serialName) + } + + @Test + fun `serialNameAndProperties - doesn't create the kotlinx mapper when read`() { + val classLoader = KotlinxMapperHidingClassLoader() + + classLoader.companionMapper("getSerialNameAndProperties") + + assertThat(classLoader.wasKotlinxMapperRequested).isFalse() + } + + @Test + fun `serialNameAndProperties - maps entries to null when the kotlinx mapper can't be loaded`() { + val classLoader = KotlinxMapperHidingClassLoader() + + val mapper = classLoader.companionMapper("getSerialNameAndProperties") + + assertThat(mapper.map(Home)).isNull() + assertThat(classLoader.wasKotlinxMapperRequested).isTrue() + } + + @Test + fun `serialNameAndProperties - maps entries to null when kotlinx serialization is missing`() { + val classLoader = KotlinxMapperHidingClassLoader(hidesKotlinx = true) + val entry = classLoader.notSerializableEntry("1") + + val mapper = classLoader.companionMapper("getSerialNameAndProperties") + + assertThat(mapper.map("home")).isNull() + assertThat(mapper.map(entry)).isNull() + assertThat(classLoader.wasKotlinxRequested).isTrue() + } + // create() @Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesArgumentLimitsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesArgumentLimitsTest.kt new file mode 100644 index 00000000000..36df6f70456 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesArgumentLimitsTest.kt @@ -0,0 +1,125 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy +import io.sentry.compose.navigation3.internal.backstack.kotlinx.droppedBy +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.descriptors.element +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.junit.Test +import org.mockito.kotlin.mock + +/** + * Converts back stacks with [BackStackEntryMapper.SerialNameAndProperties] whose entries' host app + * serializers interfere with how the argument limits are enforced, checking the drop reasons + * recorded across the kotlinx encoding and argument sanitization layers. + * + * Each back stack is ordered top first, as [BackStackObserver] converts it. + */ +class SerialNameAndPropertiesArgumentLimitsTest { + + @Serializable(with = ReportSerializer::class) private class ReportRoute(val body: String) + + /** + * Encodes a [ReportRoute] as a class with its body, but replaces any exception with a + * [SerializationException] of its own, without the original as the cause, as a host app + * serializer might. + */ + private object ReportSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("Report") { element("body") } + + override fun serialize(encoder: Encoder, value: ReportRoute) { + try { + encoder.encodeStructure(descriptor) { encodeStringElement(descriptor, 0, value.body) } + } catch (@Suppress("SwallowedException", "TooGenericExceptionCaught") e: Exception) { + throw SerializationException("Couldn't encode the report") + } + } + + override fun deserialize(decoder: Decoder): ReportRoute = throw UnsupportedOperationException() + } + + @Serializable(with = DraftSerializer::class) private class DraftRoute(val lineIds: List) + + /** + * Encodes a [DraftRoute] as a class with its line ids, then throws, as a host app serializer that + * fails after writing part of an entry's properties might. + */ + private object DraftSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("Draft") { element>("lineIds") } + + override fun serialize(encoder: Encoder, value: DraftRoute) { + encoder.encodeStructure(descriptor) { + encodeSerializableElement(descriptor, 0, ListSerializer(Int.serializer()), value.lineIds) + } + throw SerializationException("Couldn't encode the draft") + } + + override fun deserialize(decoder: Decoder): DraftRoute = throw UnsupportedOperationException() + } + + @Serializable @SerialName("Catalog") private data class CatalogRoute(val itemIds: List) + + @Serializable @SerialName("Cart") private data class CartRoute(val cartId: String) + + private val logger = mock() + + @Test + fun `an entry whose serializer replaces the character limit failure drops only its own arguments`() { + // The body alone is one character over the limit of MAX_ARGUMENT_CHARACTERS per entry. + val report = ReportRoute(body = "b".repeat(MAX_ARGUMENT_CHARACTERS + 1)) + val backStack = listOf(report, CartRoute(cartId = "c-1")) + + val converted = convert(backStack, BackStackEntryMapper.SerialNameAndProperties) + + assertThat(converted) + .containsExactly( + NormalizedSentryBackStackEntry("/Report", droppedBy(ArgumentDropReason.CHARACTER_LIMIT)), + NormalizedSentryBackStackEntry("/Cart", mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + @Test + fun `a serializer throwing after writing part of an entry drops only that entry's arguments`() { + // The catalog spends 151 of the MAX_ARGUMENT_VALUES = 200 values per update: its list and 150 + // items. The draft's list and 59 items are 60 more, which would overflow what the catalog + // left, but each entry is encoded with a budget of its own, so the draft's serializer throws + // first and only the draft's arguments are dropped. + val catalog = CatalogRoute(itemIds = List(150) { it }) + val draft = DraftRoute(lineIds = List(59) { it }) + val backStack = listOf(catalog, draft, CartRoute(cartId = "c-1")) + + val converted = convert(backStack, BackStackEntryMapper.SerialNameAndProperties) + + assertThat(converted) + .containsExactly( + NormalizedSentryBackStackEntry("/Catalog", mapOf("itemIds" to List(150) { it })), + NormalizedSentryBackStackEntry("/Draft", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + NormalizedSentryBackStackEntry("/Cart", mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + private fun convert( + backStack: List, + entryMapper: BackStackEntryMapper, + ): List = + BackStackConverter(ForwardingBackStackEntryMapper { entryMapper }, logger) + .convert(backStack, RetentionPolicy.KEEP_FIRST) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesParityTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesParityTest.kt new file mode 100644 index 00000000000..6822fd12603 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesParityTest.kt @@ -0,0 +1,382 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertWithMessage +import io.sentry.ILogger +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.util.UrlUtils.SENSITIVE_DATA_SUBSTITUTE +import kotlin.jvm.JvmInline +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.descriptors.element +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test +import org.mockito.kotlin.mock + +/** + * Converts each scenario's back stack along every [ArgumentPath] by which a host app can hand + * `SerialNameAndProperties`' arguments to Sentry, and checks that all of them record the same + * arguments and drop reasons. + * + * The paths differ in how they spend the update's argument budget: the built-in mapper encodes each + * entry with a budget of its own, so its arguments and a wrapper's copy of them hold only a drop + * reason for an entry over a limit, while a plain map spends the update's budget directly. Each + * scenario runs along all of them, so a new scenario can't cover one path and miss another. The + * intended difference is stated in the scenario: an entry over an update-wide limit given as a + * plain map, as [Scenario.expectedPlain]. + * + * Limits are covered by one that drops older entries' arguments and one that doesn't. Their + * enforcement is covered by `TreeArgumentSinkTest` and the encoder suites. + * + * Each back stack is ordered top first, as [BackStackObserver] converts it. + */ +class SerialNameAndPropertiesParityTest { + + @Serializable @SerialName("Cart") private data class CartRoute(val cartId: String) + + @Serializable private data class Address(val city: String, val zip: Int) + + private enum class Delivery { + STANDARD, + EXPRESS, + } + + @Serializable + @SerialName("Order") + private data class OrderRoute( + val orderId: Long, + val gift: Boolean, + val note: String?, + val delivery: Delivery, + val address: Address, + val tags: List, + val quantities: Map, + ) + + @Serializable @SerialName("Catalog") private data class CatalogRoute(val prices: Map) + + @Serializable @SerialName("Nested") private data class NestedRoute(val child: NestedRoute?) + + @Serializable(with = UnencodableSerializer::class) private class UnencodableRoute + + @Serializable private data class LateFailingProperties(val values: List) + + @Serializable(with = LateFailingSerializer::class) + private class LateFailingRoute(val values: List) + + /** + * Encodes a [LateFailingRoute]'s properties, then throws, as a serializer that fails late might. + */ + private object LateFailingSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("LateFailing") { element>("values") } + + override fun serialize(encoder: Encoder, value: LateFailingRoute) { + LateFailingProperties.serializer().serialize(encoder, LateFailingProperties(value.values)) + error("Failed after encoding") + } + + override fun deserialize(decoder: Decoder): LateFailingRoute = + throw UnsupportedOperationException() + } + + /** A map key whose underlying property's name (`token`) is sensitive. */ + @Serializable @JvmInline private value class SecretKey(val token: String) + + @Serializable + @SerialName("Headers") + private data class HeadersRoute(val headers: Map) + + /** Throws when encoding an [UnencodableRoute], as a broken host app serializer might. */ + private object UnencodableSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("Unencodable") { element("email") } + + override fun serialize(encoder: Encoder, value: UnencodableRoute) { + error("Can't encode") + } + + override fun deserialize(decoder: Decoder): UnencodableRoute = + throw UnsupportedOperationException() + } + + /** One way a host app can hand `SerialNameAndProperties`' arguments to Sentry. */ + private enum class ArgumentPath { + /** Returns the built-in mapper's entry. */ + BUILT_IN, + + /** Returns a copy of the built-in mapper's arguments, with one key filtered out. */ + WRAPPED, + + /** Returns a plain map equal to what the built-in mapper encodes. */ + PLAIN, + } + + /** + * A back stack and what every [ArgumentPath] should record for it, in serialized form. + * + * [plainEntries] pairs each entry with an equivalent plain-map entry for [ArgumentPath.PLAIN], or + * is `null` if some entry has none, e.g., because it can't be encoded. + */ + private class Scenario( + val backStack: List, + val plainEntries: Map?, + val expected: List>, + val expectedPlain: List> = expected, + ) + + private val cart = CartRoute(cartId = "c-1") + private val plainCart = SentryBackStackEntry("Cart", mapOf("cartId" to "c-1")) + private val recordedCart = + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")) + + private val logger = mock() + + @Test + fun `every path records the same arguments for entries within the argument limits`() { + val order = + OrderRoute( + orderId = 42L, + gift = true, + note = null, + delivery = Delivery.EXPRESS, + address = Address(city = "Vienna", zip = 1010), + tags = listOf("new", "sale"), + quantities = mapOf("apple" to 2, "pear" to 3), + ) + val plainOrder = + SentryBackStackEntry( + "Order", + mapOf( + "orderId" to 42L, + "gift" to true, + "note" to null, + "delivery" to Delivery.EXPRESS, + "address" to mapOf("city" to "Vienna", "zip" to 1010), + "tags" to listOf("new", "sale"), + "quantities" to mapOf("apple" to 2, "pear" to 3), + ), + ) + + assertEveryPathRecords( + Scenario( + backStack = listOf(order, cart), + plainEntries = mapOf(order to plainOrder, cart to plainCart), + expected = + listOf( + mapOf( + "entry" to "/Order", + "entry_arguments" to + mapOf( + "orderId" to 42L, + "gift" to true, + "note" to null, + "delivery" to "EXPRESS", + "address" to mapOf("city" to "Vienna", "zip" to 1010), + "tags" to listOf("new", "sale"), + "quantities" to mapOf("apple" to 2, "pear" to 3), + ), + ), + recordedCart, + ), + ), + ) + } + + @Test + fun `every path drops an entry's arguments over the value limit, and only a plain map drops older entries'`() { + // The prices map and its MAX_ARGUMENT_VALUES + 1 entries are MAX_ARGUMENT_VALUES + 2 values, + // over the limit of MAX_ARGUMENT_VALUES per update. + val prices = (0..MAX_ARGUMENT_VALUES).associate { "item$it" to it } + val catalog = CatalogRoute(prices = prices) + val droppedCatalog = + mapOf( + "entry" to "/Catalog", + "entry_arguments" to mapOf("dropped_by_sentry" to "max_argument_count_exceeded"), + ) + + assertEveryPathRecords( + Scenario( + backStack = listOf(catalog, cart), + plainEntries = + mapOf( + catalog to SentryBackStackEntry("Catalog", mapOf("prices" to prices)), + cart to plainCart, + ), + // The built-in mapper encodes each entry with its own budget, so Sentry receives the drop + // reason as an ordinary argument and older entries keep theirs. + expected = listOf(droppedCatalog, recordedCart), + // A plain map spends the update's budget, which it exhausts for older entries too. + expectedPlain = + listOf( + droppedCatalog, + mapOf( + "entry" to "/Cart", + "entry_arguments" to mapOf("dropped_by_sentry" to "max_argument_count_exceeded"), + ), + ), + ), + ) + } + + @Test + fun `every path drops the arguments of an entry nested past the depth limit, but not of older entries`() { + // The innermost child is nested one level past the depth limit of MAX_ARGUMENT_DEPTH. + val nested = nestedRoute(levels = MAX_ARGUMENT_DEPTH + 1) + + assertEveryPathRecords( + Scenario( + backStack = listOf(nested, cart), + plainEntries = + mapOf( + nested to + SentryBackStackEntry("Nested", plainNestedArguments(levels = MAX_ARGUMENT_DEPTH + 1)), + cart to plainCart, + ), + expected = + listOf( + mapOf( + "entry" to "/Nested", + "entry_arguments" to mapOf("dropped_by_sentry" to "invalid_structure"), + ), + recordedCart, + ), + ), + ) + } + + @Test + fun `every path records the same encoding failure for an entry that can't be encoded`() { + assertEveryPathRecords( + Scenario( + backStack = listOf(UnencodableRoute(), cart), + plainEntries = null, + expected = + listOf( + mapOf( + "entry" to "/Unencodable", + "entry_arguments" to mapOf("dropped_by_sentry" to "encoding_failed"), + ), + recordedCart, + ), + ), + ) + } + + @Test + fun `no path spends the budget an entry wrote before its encoding failed`() { + // The late-failing entry writes its list and MAX_ARGUMENT_VALUES - 2 elements before it throws, + // which leaves one value, too few for the catalog's map and its one price. + val lateFailing = LateFailingRoute(values = List(MAX_ARGUMENT_VALUES - 2) { it }) + val catalog = CatalogRoute(prices = mapOf("item" to 1)) + val failedLateFailing = + mapOf( + "entry" to "/LateFailing", + "entry_arguments" to mapOf("dropped_by_sentry" to "encoding_failed"), + ) + val catalogKeepsItsPrices = + listOf( + failedLateFailing, + mapOf("entry" to "/Catalog", "entry_arguments" to mapOf("prices" to mapOf("item" to 1))), + ) + + assertEveryPathRecords( + Scenario( + backStack = listOf(lateFailing, catalog), + plainEntries = null, + // The entry was encoded with its own budget, so Sentry receives only the drop reason, as an + // ordinary argument. + expected = catalogKeepsItsPrices, + ), + ) + } + + @Test + fun `every path spends the budget of one entry for map entries whose keys are filtered`() { + // The headers map and its single filtered entry are 2 values, which leaves exactly enough for + // the catalog's map and its MAX_ARGUMENT_VALUES - 3 prices. Charging for every filtered entry + // would push the catalog over the limit. + val headers = + HeadersRoute( + mapOf(SecretKey("a") to "secret-a", SecretKey("b") to "secret-b", SecretKey("c") to "x"), + ) + val prices = (0 until MAX_ARGUMENT_VALUES - 3).associate { "item$it" to it } + val catalog = CatalogRoute(prices = prices) + val filteredHeaders = mapOf(SENSITIVE_DATA_SUBSTITUTE to SENSITIVE_DATA_SUBSTITUTE) + + assertEveryPathRecords( + Scenario( + backStack = listOf(headers, catalog), + plainEntries = + mapOf( + headers to SentryBackStackEntry("Headers", mapOf("headers" to filteredHeaders)), + catalog to SentryBackStackEntry("Catalog", mapOf("prices" to prices)), + ), + expected = + listOf( + mapOf("entry" to "/Headers", "entry_arguments" to mapOf("headers" to filteredHeaders)), + mapOf("entry" to "/Catalog", "entry_arguments" to mapOf("prices" to prices)), + ), + ), + ) + } + + /** Converts [scenario]'s back stack along every [ArgumentPath] and checks what each records. */ + private fun assertEveryPathRecords(scenario: Scenario) { + for (path in ArgumentPath.entries) { + val mapper = mapperFor(path, scenario) ?: continue + val expected = if (path == ArgumentPath.PLAIN) scenario.expectedPlain else scenario.expected + + val recorded = convert(scenario.backStack, mapper).serialize() + + assertWithMessage("arguments recorded along $path").that(recorded).isEqualTo(expected) + } + } + + /** Returns the mapper for [path], or `null` if [scenario] can't run along it. */ + private fun mapperFor(path: ArgumentPath, scenario: Scenario): BackStackEntryMapper? { + val builtIn = BackStackEntryMapper.SerialNameAndProperties + return when (path) { + ArgumentPath.BUILT_IN -> builtIn + // Removes the `email` argument, as the mapper's KDoc documents. + ArgumentPath.WRAPPED -> + BackStackEntryMapper { entry -> + builtIn.map(entry)?.let { mapped -> + SentryBackStackEntry(mapped.name, mapped.arguments?.filterKeys { it != "email" }) + } + } + ArgumentPath.PLAIN -> + scenario.plainEntries?.let { plainEntries -> + BackStackEntryMapper { entry -> plainEntries.getValue(entry) } + } + } + } + + private fun convert( + backStack: List, + entryMapper: BackStackEntryMapper, + ): List = + BackStackConverter(ForwardingBackStackEntryMapper { entryMapper }, logger) + .convert(backStack, RetentionPolicy.KEEP_FIRST) + + /** A [NestedRoute] wrapping [levels] more of them, the innermost with no child. */ + private fun nestedRoute(levels: Int): NestedRoute { + var route = NestedRoute(child = null) + repeat(levels) { route = NestedRoute(child = route) } + return route + } + + /** The plain map equivalent of [nestedRoute]'s arguments. */ + private fun plainNestedArguments(levels: Int): Map { + var arguments = mapOf("child" to null) + repeat(levels) { arguments = mapOf("child" to arguments) } + return arguments + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt new file mode 100644 index 00000000000..59289ca5c2c --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt @@ -0,0 +1,200 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.descriptors.element +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.junit.Test + +class KotlinxArgumentsTest { + + @Serializable data class Values(val values: List) + + /** + * Delegates to [delegate], but replaces a [DropArgumentsException] it throws with an exception of + * its own, as a serializer that catches and rethrows everything might. + */ + private class ReplacingSerializer( + private val delegate: KSerializer, + private val replace: () -> Throwable, + ) : KSerializer by delegate { + override fun serialize(encoder: Encoder, value: T) { + try { + delegate.serialize(encoder, value) + } catch (_: DropArgumentsException) { + throw replace() + } + } + } + + /** Writes a [Detail]'s id into a list it begins but never ends. */ + private object UnclosedListSerializer : KSerializer { + override val descriptor: SerialDescriptor = ListSerializer(String.serializer()).descriptor + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.beginStructure(descriptor).encodeStringElement(descriptor, 0, value.id) + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + /** Writes nothing, leaving the key written for its value without one. */ + private object WritesNothingSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.WritesNothing", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: String) = Unit + + override fun deserialize(decoder: Decoder): String = throw UnsupportedOperationException() + } + + /** Writes a [Detail] as a class whose only property has no value. */ + private object ValuelessKeySerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("test.ValuelessKey") { element("first") } + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { + encodeSerializableElement(descriptor, 0, WritesNothingSerializer, value.id) + } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + private val failures = mutableListOf() + + private val detailSerializer = RecordingSerializer(Detail.serializer()) + + /** A value over the argument character limit. */ + private val overLimitId = "x".repeat(MAX_ARGUMENT_CHARACTERS + 1) + + private val encodingFailed = droppedBy(ArgumentDropReason.ENCODING_FAILED) + + // Encoding + + @Test + fun `encode() - returns the entry's encoded properties`() { + val arguments = encode(detailSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `encode() - encodes each entry with a budget of its own`() { + // Each entry has 151 values, so two entries wouldn't fit in one budget. + val first = encode(Values.serializer(), Values(List(150) { it })) + val second = encode(Values.serializer(), Values(List(150) { it })) + + assertThat(first).isEqualTo(mapOf("values" to List(150) { it })) + assertThat(second).isEqualTo(mapOf("values" to List(150) { it })) + } + + @Test + fun `encode() - runs the entry's serializer once, and no more when the arguments are read or compared`() { + val arguments = encode(detailSerializer, Detail("1")) + + arguments.hashCode() + arguments == mapOf("id" to "1") + arguments.entries.toList() + + assertThat(detailSerializer.serialized).containsExactly(Detail("1")) + } + + // Failures + + @Test + fun `encode() - returns only the broken limit and reports it when the entry breaks an argument limit`() { + val arguments = encode(detailSerializer, Detail(overLimitId)) + + assertThat(arguments).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + assertThat((failures.single() as DropArgumentsException).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `encode() - returns only the broken limit and reports it when a serializer replaced it with its own exception`() { + val serializer = ReplacingSerializer(Detail.serializer()) { SerializationException("replaced") } + + val arguments = encode(serializer, Detail(overLimitId)) + + assertThat(arguments).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + assertThat((failures.single() as DropArgumentsException).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `encode() - returns only the encoding failure and reports a serializer's exception`() { + val error = IllegalStateException("boom") + detailSerializer.error = error + + val arguments = encode(detailSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(encodingFailed) + assertThat(failures).containsExactly(error) + } + + @Test + fun `encode() - returns only the encoding failure and reports a serializer's LinkageError`() { + val error = NoClassDefFoundError("missing") + detailSerializer.error = error + + val arguments = encode(detailSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(encodingFailed) + assertThat(failures).containsExactly(error) + } + + @Test + fun `encode() - propagates fatal errors without reporting them`() { + val error = OutOfMemoryError() + detailSerializer.error = error + + val thrown = assertFailsWith { encode(detailSerializer, Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(failures).isEmpty() + } + + @Test + fun `encode() - returns only the encoding failure when a serializer leaves a list open`() { + val arguments = encode(UnclosedListSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(encodingFailed) + assertThat(failures.single()).isInstanceOf(ArgumentProtocolException::class.java) + } + + @Test + fun `encode() - returns only the encoding failure when a serializer's last key has no value`() { + val arguments = encode(ValuelessKeySerializer, Detail("1")) + + assertThat(arguments).isEqualTo(encodingFailed) + assertThat(failures.single()).isInstanceOf(ArgumentProtocolException::class.java) + } + + // Unencodable entries + + @Test + fun `UNENCODABLE - is only the encoding failure`() { + assertThat(KotlinxArguments.UNENCODABLE).isEqualTo(encodingFailed) + } + + @Suppress("UNCHECKED_CAST") + private fun encode(serializer: KSerializer, entry: T): Map = + KotlinxArguments.encode(entry, serializer as KSerializer) { failures += it } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperEncoderCheckTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperEncoderCheckTest.kt new file mode 100644 index 00000000000..7d12842d53b --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperEncoderCheckTest.kt @@ -0,0 +1,138 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions + +/** How [KotlinxBackStackEntryMapper] acts on what its properties encoder check finds. */ +class KotlinxBackStackEntryMapperEncoderCheckTest { + + @Test + fun `logs nothing when created with properties included for a kotlinx version its encoder check finds compatible`() { + val fixture = + KotlinxMapperFixture.create(includeProperties = true, encoderCheck = FakeEncoderCheck()) + + fixture.mapper + + verifyNoInteractions(fixture.logger) + } + + @Test + fun `checks the properties encoder once when created with properties included`() { + val encoderCheck = FakeEncoderCheck() + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(encoderCheck.checks).isEqualTo(1) + } + + @Test + fun `never checks the properties encoder when properties are excluded`() { + // No incompatible check is logged, as the encoder check isn't run when properties are excluded. + val encoderCheck = FakeEncoderCheck(NoSuchMethodError()) + val fixture = + KotlinxMapperFixture.create(includeProperties = false, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(encoderCheck.checks).isEqualTo(0) + verifyNoInteractions(fixture.logger) + } + + @Test + fun `keeps the name and records only the encoding failure when the properties encoder is incompatible`() { + val encoderCheck = FakeEncoderCheck(NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Search("shoes"))) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + SentryBackStackEntry("Search", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + ) + .inOrder() + } + + @Test + fun `keeps the name and records only the encoding failure when the properties encoder can't link`() { + // Runs the LinkageError through the real check's failure handling instead of returning it. + val mapper = + KotlinxBackStackEntryMapper( + includeProperties = true, + lookUpSerializer = { Detail.serializer() }, + checkCompatibility = {}, + checkEncoderCompatibility = { kotlinxEncoderIncompatibility { throw NoSuchMethodError() } }, + logger = { mock() }, + ) + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `records no arguments for objects when the properties encoder is incompatible`() { + val encoderCheck = FakeEncoderCheck(NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + val mapped = mapper.map(Home) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Home", arguments = null)) + } + + @Test + fun `doesn't encode properties when the properties encoder is incompatible`() { + val encoderCheck = FakeEncoderCheck(NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + mapper.map(Detail("1")) + mapper.map(Detail("2")) + + assertThat(fixture.detailSerializer.serialized).isEmpty() + } + + @Test + fun `logs the incompatible encoder warning with the error when created for an incompatible properties encoder`() { + val error = NoSuchMethodError("encodeStructure") + val encoderCheck = FakeEncoderCheck(error) + + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + + verify(fixture.logger, times(1)).log(eq(SentryLevel.WARNING), any(), eq(error)) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `logs nothing more for entries mapped when the properties encoder is incompatible`() { + val error = NoSuchMethodError() + val encoderCheck = FakeEncoderCheck(error) + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail("$it")) + mapper.map(Search("$it")) + } + + verify(fixture.logger, times(1)).log(eq(SentryLevel.WARNING), any(), eq(error)) + verifyNoMoreInteractions(fixture.logger) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt new file mode 100644 index 00000000000..8af18ca54e2 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt @@ -0,0 +1,476 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlin.test.assertFailsWith +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.junit.Test +import org.mockito.AdditionalAnswers.delegatesTo +import org.mockito.Mockito +import org.mockito.kotlin.any +import org.mockito.kotlin.argThat +import org.mockito.kotlin.doThrow +import org.mockito.kotlin.eq +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions +import org.mockito.kotlin.whenever + +class KotlinxBackStackEntryMapperPropertiesTest { + + @Serializable @SerialName("PropertyLess") class PropertyLess + + /** Encodes to its code alone, a string rather than a structure. */ + @Serializable(with = CodeSerializer::class) class Code(val code: String) + + object CodeSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("Code", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Code) { + encoder.encodeString(value.code) + } + + override fun deserialize(decoder: Decoder): Code = Code(decoder.decodeString()) + } + + /** Serializes [PropertyLess] with its own descriptor, except that reading its `kind` throws. */ + @OptIn(ExperimentalSerializationApi::class) + object KindThrowingPropertyLessSerializer : KSerializer { + private val delegate = PropertyLess.serializer().descriptor + + override val descriptor: SerialDescriptor = + Mockito.mock(SerialDescriptor::class.java, delegatesTo(delegate)).apply { + doThrow(IllegalStateException("no kind")).whenever(this).kind + } + + override fun serialize(encoder: Encoder, value: PropertyLess) { + encoder.encodeStructure(descriptor) {} + } + + override fun deserialize(decoder: Decoder): PropertyLess = throw UnsupportedOperationException() + } + + /** Writes [Detail]'s id inside its structure without naming the element it belongs to. */ + private object KeylessDetailSerializer : KSerializer { + override val descriptor: SerialDescriptor = Detail.serializer().descriptor + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { (this as Encoder).encodeString(value.id) } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + /** An id over the argument character limit. */ + private val overLimitId = "x".repeat(MAX_ARGUMENT_CHARACTERS + 1) + + // Properties + + @Test + fun `records encoded properties as arguments when properties are included`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Detail("2"))) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("Detail", mapOf("id" to "1")), + SentryBackStackEntry("Detail", mapOf("id" to "2")), + ) + .inOrder() + } + + @Test + fun `doesn't encode properties when properties are excluded`() { + val fixture = KotlinxMapperFixture.create(includeProperties = false) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(fixture.detailSerializer.serialized).isEmpty() + } + + @Test + fun `records no arguments for objects`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + val mapped = mapper.map(Home) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Home", arguments = null)) + } + + @Test + fun `records no arguments for classes without properties`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { PropertyLess.serializer() } + val mapper = fixture.mapper + + val mapped = mapper.map(PropertyLess()) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("PropertyLess", arguments = null)) + } + + @Test + fun `records the value of entries whose serializer doesn't encode a class`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { CodeSerializer } + val mapper = fixture.mapper + + val mapped = mapper.map(Code("abc")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Code", mapOf("value" to "abc"))) + } + + @Test + fun `doesn't encode properties of entries that can't be named`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { null } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + assertThat(fixture.detailSerializer.serialized).isEmpty() + } + + @Test + fun `keeps recording arguments for other types after a type's name lookup throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { + if (it == Detail::class.java) throw NoSuchMethodError() else fixture.serializers[it] + } + val mapper = fixture.mapper + mapper.map(Detail("1")) + + val mapped = mapper.map(Search("shoes")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Search", mapOf("query" to "shoes"))) + } + + // Properties that can't be encoded + + @Test + fun `keeps the name and records only the encoding failure when a type's properties can't be encoded`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + val mapped = mapper.map(WithContextual("1", Unregistered("2"))) + + assertThat(mapped) + .isEqualTo( + SentryBackStackEntry("WithContextual", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + ) + } + + @Test + fun `keeps encoding a type's properties after they couldn't be encoded once`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = SerializationException("unencodable") + val mapper = fixture.mapper + mapper.map(Detail("1")) + fixture.detailSerializer.error = null + + val mapped = mapper.map(Detail("2")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail", mapOf("id" to "2"))) + } + + @Test + fun `logs an unsupported-properties warning once per type whose properties can't be encoded`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = SerializationException("detail unencodable") + fixture.searchSerializer.error = SerializationException("search unencodable") + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail("$it")) + mapper.map(Search("$it")) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(Detail::class.java.name), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(Search::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `encodes an entry's properties once, when it's mapped`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + + val mapped = fixture.mapper.map(Detail("1")) + + assertThat(fixture.detailSerializer.serialized).containsExactly(Detail("1")) + assertThat(mapped?.arguments).isEqualTo(mapOf("id" to "1")) + assertThat(fixture.detailSerializer.serialized).containsExactly(Detail("1")) + } + + // Properties over the argument limits + + @Test + fun `logs a warning with the drop reason once per type whose properties exceed the argument limits`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail(overLimitId)) + mapper.map(Search(overLimitId)) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + eq(Detail::class.java.name), + eq(ArgumentDropReason.CHARACTER_LIMIT.serializedValue), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + eq(Search::class.java.name), + eq(ArgumentDropReason.CHARACTER_LIMIT.serializedValue), + ) + } + + // Property encoding that throws a LinkageError + + @Test + fun `keeps encoding a type's properties after one entry's encoding throws a LinkageError`() { + // A serializer may only reach a class that fails to link for some values (e.g., one subtype of + // a sealed property), so a LinkageError only drops the arguments of the entry whose encoding + // threw it, and leaves other types alone. + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = NoClassDefFoundError() + fixture.detailSerializer.failsFor = { it.id == "unlinkable" } + val mapper = fixture.mapper + + val mapped = + listOf( + mapper.map(Detail("unlinkable")), + mapper.map(Search("shoes")), + mapper.map(Detail("2")), + ) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + SentryBackStackEntry("Search", mapOf("query" to "shoes")), + SentryBackStackEntry("Detail", mapOf("id" to "2")), + ) + .inOrder() + } + + @Test + fun `logs a warning once per type whose property encoding throws a LinkageError`() { + val error = AbstractMethodError() + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = error + fixture.searchSerializer.error = error + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail("$it")) + mapper.map(Search("$it")) + } + + // Each entry's encoding threw, yet each type's warning was logged once. + assertThat(fixture.detailSerializer.serialized) + .containsExactly(Detail("0"), Detail("1"), Detail("2")) + assertThat(fixture.searchSerializer.serialized) + .containsExactly(Search("0"), Search("1"), Search("2")) + verify(fixture.logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(Detail::class.java.name)) + verify(fixture.logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(Search::class.java.name)) + verifyNoMoreInteractions(fixture.logger) + } + + // Property encoding that throws other exceptions + + @Test + fun `logs a serializer-threw warning once per type whose property encoding throws an exception`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = IllegalArgumentException("invalid id") + fixture.searchSerializer.error = IllegalArgumentException("invalid query") + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail("$it")) + mapper.map(Search("$it")) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(SERIALIZER_THREW) }, + eq(Detail::class.java.name), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(SERIALIZER_THREW) }, + eq(Search::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + // Serializers that write outside the encoder's protocol + + @Test + fun `drops the arguments of an entry whose serializer writes a value outside its elements`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { KeylessDetailSerializer } + + val mapped = fixture.mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `logs a protocol-violation warning for a serializer that writes outside its elements`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { KeylessDetailSerializer } + + fixture.mapper.map(Detail("1")) + + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(PROTOCOL_VIOLATION) }, + eq(Detail::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + // Serializer descriptors whose shape throws + + @Test + fun `keeps the name and records the properties when an entry's descriptor's elementsCount throws`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { + ShapeThrowingDetailSerializer(elementsCountError = IllegalStateException("no count")) + } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail", mapOf("id" to "1"))) + } + + @Test + fun `keeps the name and records only the encoding failure when an entry's descriptor's kind throws`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(kindError = IllegalStateException("no kind")) } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `keeps the name and records only the encoding failure when a property-less entry's descriptor's kind throws`() { + // Without properties, whether the entry may still have arguments depends on its kind. + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { KindThrowingPropertyLessSerializer } + val mapper = fixture.mapper + + val mapped = mapper.map(PropertyLess()) + + assertThat(mapped) + .isEqualTo( + SentryBackStackEntry("PropertyLess", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + ) + } + + @Test + fun `logs a warning once for a type whose descriptor's kind throws`() { + val error = IllegalStateException("no kind") + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(kindError = error) } + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + verify(fixture.logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(Detail::class.java.name)) + } + + @Test + fun `keeps the name and records the properties when an entry's descriptor's elementsCount throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(elementsCountError = NoClassDefFoundError()) } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail", mapOf("id" to "1"))) + } + + @Test + fun `keeps the name and records only the encoding failure when an entry's descriptor's kind throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(kindError = NoClassDefFoundError()) } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `propagates fatal errors thrown by an entry's descriptor's elementsCount`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(elementsCountError = error) } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + private companion object { + const val UNSUPPORTED_PROPERTIES = + "Contextual and open polymorphic properties and structured map keys aren't supported" + + const val SERIALIZER_THREW = "because a serializer threw" + + const val PROTOCOL_VIOLATION = "because a value was written outside the encoder's protocol" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt index 7a71d52b043..269ec658238 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt @@ -860,16 +860,16 @@ class KotlinxBackStackEntryMapperTest { mapper = if (isAnnotatedSerializable == null) { KotlinxBackStackEntryMapper( - recordingLookUp, + lookUpSerializer = recordingLookUp, checkCompatibility = checkLinkage, logger = { logger }, ) } else { KotlinxBackStackEntryMapper( - recordingLookUp, - isAnnotatedSerializable, - checkLinkage, - { logger }, + lookUpSerializer = recordingLookUp, + isAnnotatedSerializable = isAnnotatedSerializable, + checkCompatibility = checkLinkage, + logger = { logger }, ) } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt index 5e64aeefd3b..9819eea93ee 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt @@ -1,6 +1,8 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink import kotlin.test.assertFailsWith import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.builtins.serializer @@ -60,4 +62,77 @@ class KotlinxCompatibilityCheckTest { fun `checkKotlinxCompatibility() - succeeds without reading a serial name when no serializer is found`() { checkKotlinxCompatibility { null } } + + // kotlinxEncoderIncompatibility() + + @Test + fun `kotlinxEncoderIncompatibility() - returns null for the kotlinx serialization version on the classpath`() { + val error = kotlinxEncoderIncompatibility() + + assertThat(error).isNull() + } + + @Test + fun `encodeCompatibilityCheckValue() - encodes a null and an unsigned value beyond the signed range`() { + val sink = TreeArgumentSink(ArgumentBudget()) + + encodeCompatibilityCheckValue(sink) + + assertThat(sink.argumentsOrThrow()) + .isEqualTo( + mapOf( + "first" to "check", + "second" to listOf(1, null), + "third" to mapOf("count" to 4_294_967_295L), + ), + ) + } + + @Test + fun `kotlinxEncoderIncompatibility() - returns EncoderProducedUnexpectedOutput when the encoding differs`() { + val error = kotlinxEncoderIncompatibility { sink -> + sink.key("first") + sink.scalar("other") + } + + assertThat(error).isInstanceOf(EncoderProducedUnexpectedOutput::class.java) + } + + @Test + fun `kotlinxEncoderIncompatibility() - returns a LinkageError the encoder throws instead of rethrowing it`() { + // Rethrown, the error would fail the mapper's creation and disable names too. + val errors = listOf(NoSuchMethodError(), NoClassDefFoundError(), VerifyError()) + + val failures = errors.map { error -> kotlinxEncoderIncompatibility { throw error } } + + assertThat(failures).containsExactlyElementsIn(errors).inOrder() + } + + @Test + fun `kotlinxEncoderIncompatibility() - returns a non-fatal exception the encoder throws`() { + val error = NullPointerException() + + val failure = kotlinxEncoderIncompatibility { throw error } + + assertThat(failure).isSameInstanceAs(error) + } + + @Test + fun `kotlinxEncoderIncompatibility() - rethrows a fatal error the encoder throws that isn't a LinkageError`() { + val error = OutOfMemoryError() + + val thrown = assertFailsWith { kotlinxEncoderIncompatibility { throw error } } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `EncoderProducedUnexpectedOutput is a RuntimeException with a fixed message`() { + val error = EncoderProducedUnexpectedOutput() + + assertThat(error).isInstanceOf(RuntimeException::class.java) + assertThat(error) + .hasMessageThat() + .isEqualTo("The kotlinx.serialization properties encoder produced unexpected output.") + } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt new file mode 100644 index 00000000000..5bc3032c564 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt @@ -0,0 +1,22 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import kotlinx.serialization.KSerializer + +/** + * Encodes the properties of [value] with [serializer] into a map, with a budget of its own. Throws + * as [KotlinxPropertiesEncoder.encode] does. + */ +internal fun encodeToMap(serializer: KSerializer, value: T): Map { + val sink = TreeArgumentSink(ArgumentBudget()) + encodeInto(serializer, value, sink) + return sink.argumentsOrThrow() +} + +/** Encodes the properties of [value] with [serializer] into [sink]. */ +@Suppress("UNCHECKED_CAST") +internal fun encodeInto(serializer: KSerializer, value: T, sink: ArgumentSink) { + KotlinxPropertiesEncoder.encode(serializer as KSerializer, value, sink) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt index b500c609c3c..7a0e8d05148 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt @@ -5,13 +5,21 @@ import io.sentry.ILogger import io.sentry.SentryLevel import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.common.MIN_KOTLINX_SERIALIZATION_VERSION +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlinx.serialization.SerializationException import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.times import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions class KotlinxMapperDiagnosticsTest { @@ -19,6 +27,7 @@ class KotlinxMapperDiagnosticsTest { private val diagnostics = KotlinxMapperDiagnostics { logger } private val type = Detail::class.java + private val otherType = Search::class.java // notSerializable() @@ -58,6 +67,152 @@ class KotlinxMapperDiagnosticsTest { .startsWith("Nav3 couldn't verify kotlinx.serialization compatibility") } + // incompatibleEncoder() + + @Test + fun `incompatibleEncoder() - logs a warning with the error and compatibility advice`() { + val error = NoSuchMethodError("encodeStructure") + + diagnostics.incompatibleEncoder(error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), message.capture(), eq(error)) + assertThat(message.firstValue) + .startsWith( + "Nav3 SerialNameAndProperties is incompatible with this app's kotlinx.serialization " + + "version.", + ) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + // propertyFailure() + + @Test + fun `propertyFailure() - logs an over-limits warning with the type and drop reason for a DropArgumentsException`() { + val error = + DropArgumentsException( + ArgumentDropReason.CHARACTER_LIMIT, + DropArgumentsException.MAX_CHARACTER_WARNING, + ) + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger) + .log( + eq(SentryLevel.WARNING), + message.capture(), + eq(type.name), + eq(ArgumentDropReason.CHARACTER_LIMIT.serializedValue), + ) + assertThat(message.firstValue).startsWith("Nav3 dropped arguments for type") + } + + @Test + fun `propertyFailure() - logs a SerializationException attached to an unsupported-properties warning`() { + val error = SerializationException("unencodable") + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains(UNSUPPORTED_PROPERTIES) + } + + @Test + fun `propertyFailure() - logs a LinkageError attached to a warning with compatibility advice`() { + val error = NoClassDefFoundError("kotlinx/serialization/internal/Missing") + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + verifyNoMoreInteractions(logger) + } + + @Test + fun `propertyFailure() - logs an ArgumentProtocolException attached to a protocol-violation warning`() { + val error = ArgumentProtocolException("A map value was written without a key.") + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains(PROTOCOL_VIOLATION) + assertThat(message.firstValue).doesNotContain(SERIALIZER_THREW) + verifyNoMoreInteractions(logger) + } + + @Test + fun `propertyFailure() - logs a serializer's exception attached to a serializer-threw warning`() { + val error = IllegalArgumentException("invalid id") + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains(SERIALIZER_THREW) + verifyNoMoreInteractions(logger) + } + + @Test + fun `propertyFailure() - logs each kind of failure once per type`() { + val failures = + listOf( + DropArgumentsException( + ArgumentDropReason.MAX_COUNT, + DropArgumentsException.MAX_COUNT_WARNING, + ), + SerializationException("unencodable"), + AbstractMethodError(), + IllegalStateException("thrown"), + ArgumentProtocolException("A map value was written without a key."), + ) + + repeat(2) { failures.forEach { diagnostics.propertyFailure(type, it) } } + + verify(logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + eq(type.name), + eq(ArgumentDropReason.MAX_COUNT.serializedValue), + ) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(failures[1]), any(), eq(type.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(failures[2]), any(), eq(type.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(failures[3]), any(), eq(type.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(failures[4]), any(), eq(type.name)) + verifyNoMoreInteractions(logger) + } + + @Test + fun `propertyFailure() - logs the same kind of failure again for another type`() { + val error = SerializationException("unencodable") + + diagnostics.propertyFailure(type, error) + diagnostics.propertyFailure(otherType, error) + + verify(logger) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(type.name), + ) + verify(logger) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(otherType.name), + ) + } + // unresolved() @Test @@ -128,5 +283,12 @@ class KotlinxMapperDiagnosticsTest { private companion object { const val KOTLINX_SERIALIZATION_FLOOR_PROPERTY = "nav3.kotlinxSerializationFloor" + + const val UNSUPPORTED_PROPERTIES = + "Contextual and open polymorphic properties and structured map keys aren't supported" + + const val SERIALIZER_THREW = "because a serializer threw" + + const val PROTOCOL_VIOLATION = "because a value was written outside the encoder's protocol" } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt new file mode 100644 index 00000000000..43c9a16ddad --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt @@ -0,0 +1,126 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.ILogger +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.mockito.AdditionalAnswers.delegatesTo +import org.mockito.Mockito +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +/** + * Serializes [Detail] with a descriptor whose shape, its `elementsCount` and `kind`, throws + * [elementsCountError] and [kindError] when set. Counts every read of the shape in [shapeReads]. + * Encoding reads the descriptor's `kind`, so it throws [kindError] too. + */ +@OptIn(ExperimentalSerializationApi::class) +internal class ShapeThrowingDetailSerializer( + private val elementsCountError: Throwable? = null, + private val kindError: Throwable? = null, +) : KSerializer { + var shapeReads = 0 + + private val delegate = Detail.serializer().descriptor + + override val descriptor: SerialDescriptor = + Mockito.mock(SerialDescriptor::class.java, delegatesTo(delegate)).apply { + doAnswer { + shapeReads++ + elementsCountError?.let { error -> throw error } + delegate.elementsCount + } + .whenever(this) + .elementsCount + doAnswer { + shapeReads++ + kindError?.let { error -> throw error } + delegate.kind + } + .whenever(this) + .kind + } + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { encodeStringElement(descriptor, 0, value.id) } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() +} + +/** + * Stands in for the properties encoder's compatibility check, reporting [error] (or `null` if the + * encoder is compatible), so that mapper tests don't depend on the real check. Counts its runs in + * [checks]. + */ +internal class FakeEncoderCheck(private val error: Throwable? = null) { + var checks = 0 + + fun check(): Throwable? { + checks++ + return error + } +} + +/** + * A [KotlinxBackStackEntryMapper] whose serializer lookup returns [serializers] by default. The + * mapper only looks up `@Serializable` types, so [lookUp] never sees any others. Its compatibility + * checks find the app's kotlinx.serialization version compatible by default. + * + * With `useDefaultLookUp = true`, the mapper uses its real serializer lookup, so [lookUp] and + * [lookedUpTypes] are unused. + */ +internal class KotlinxMapperFixture +private constructor( + includeProperties: Boolean, + useDefaultLookUp: Boolean, + val encoderCheck: FakeEncoderCheck, +) { + val logger = mock() + + val detailSerializer = RecordingSerializer(Detail.serializer()) + val searchSerializer = RecordingSerializer(Search.serializer()) + val serializers: Map, KSerializer<*>> = + mapOf( + Home::class.java to Home.serializer(), + Detail::class.java to detailSerializer, + Search::class.java to searchSerializer, + WithContextual::class.java to WithContextual.serializer(), + ) + + val lookedUpTypes = mutableListOf>() + var lookUp: (Class<*>) -> KSerializer<*>? = { serializers[it] } + + val mapper = + if (useDefaultLookUp) { + KotlinxBackStackEntryMapper( + includeProperties = includeProperties, + checkCompatibility = {}, + checkEncoderCompatibility = encoderCheck::check, + logger = { logger }, + ) + } else { + KotlinxBackStackEntryMapper( + includeProperties = includeProperties, + lookUpSerializer = { + lookedUpTypes += it + lookUp(it) + }, + checkCompatibility = {}, + checkEncoderCompatibility = encoderCheck::check, + logger = { logger }, + ) + } + + companion object { + fun create( + includeProperties: Boolean = false, + useDefaultLookUp: Boolean = false, + encoderCheck: FakeEncoderCheck = FakeEncoderCheck(), + ) = KotlinxMapperFixture(includeProperties, useDefaultLookUp, encoderCheck) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt new file mode 100644 index 00000000000..06c18f9b3dc --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt @@ -0,0 +1,568 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.util.UrlUtils +import kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderFilteringTest { + + @Serializable + enum class Sort { + @SerialName("price_asc") PRICE_ASC, + NEWEST, + } + + @Serializable @JvmInline value class ProductId(val value: String) + + @Serializable data class WithSensitiveProperty(val query: String, val password: String) + + @Serializable data class WithNullableSecret(val id: String, val password: String?) + + @Serializable data class WithSensitiveMapKey(val params: Map) + + @Serializable + data class WithSensitiveKeysInList(val nested: Map>>) + + @Serializable @JvmInline value class HeaderName(val name: String) + + @Serializable data class WithHeaderNameMapKeys(val headers: Map) + + /** A value class whose underlying property's name (`key`) is sensitive. */ + @Serializable @JvmInline value class SensitiveHeaderName(val key: String) + + @Serializable + data class WithSensitiveValueClassMapKeys(val headers: Map) + + @Serializable data class WithSensitiveValueClassMapValues(val params: Map) + + /** A map key that encodes as a [SensitiveHeaderName] when [isSecret], or else as its [name]. */ + @Serializable(with = MixedHeaderSerializer::class) + data class MixedHeader(val name: String, val isSecret: Boolean) + + object MixedHeaderSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.MixedHeader", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: MixedHeader) { + if (value.isSecret) { + encoder.encodeSerializableValue( + SensitiveHeaderName.serializer(), + SensitiveHeaderName(value.name), + ) + } else { + encoder.encodeString(value.name) + } + } + + override fun deserialize(decoder: Decoder): MixedHeader = + MixedHeader(decoder.decodeString(), isSecret = false) + } + + @Serializable data class WithMixedHeaderMapKeys(val headers: Map) + + @Serializable + data class WithSerialNames( + @SerialName("position") val side: String, + @SerialName("apiKey") val label: String, + ) + + @Serializable @JvmInline value class TokenRef(val token: String) + + @Serializable + data class WithSensitiveValueClassPropertyName( + val productId: ProductId, + val sessionRef: ProductId, + ) + + @Serializable + data class WithSensitiveUnderlyingPropertyName(val productId: ProductId, val reference: TokenRef) + + @Serializable data class WithValueClassList(val references: List) + + @Serializable data class Credentials(val user: String) + + @Serializable @JvmInline value class CredentialsRef(val credentials: Credentials) + + @Serializable data class WithStructuredValueClass(val owner: CredentialsRef) + + @Serializable data class WithLargeSecret(val id: String, val refreshTokens: List) + + @Serializable data class WithLargeSecretMapValue(val params: Map>) + + @Serializable + data class WithUnencodableSecret( + val id: String, + @Serializable(with = ThrowingSerializer::class) val authToken: String, + ) + + @Serializable + data class WithUnencodableSecretMapValue( + val params: Map, + ) + + /** A value class whose underlying property's name (`token`) is sensitive. */ + @Serializable + @JvmInline + value class UnencodableSecretRef( + @Serializable(with = ThrowingSerializer::class) val token: String, + ) + + @Serializable data class WithUnencodableSecretRef(val id: String, val ref: UnencodableSecretRef) + + object ThrowingSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.Throwing", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: String): Unit = error("serializer ran") + + override fun deserialize(decoder: Decoder): String = decoder.decodeString() + } + + @Serializable @JvmInline value class Wrapped(val raw: String) + + @Serializable + data class SecretsProfile(val name: String, @SerialName("PASSWORD") val password: String) + + @Serializable data class SecretsItem(val sku: String, val apiKey: String) + + @Serializable + sealed interface SecretsOrigin { + @Serializable + @SerialName("login") + data class Login(val user: String, val authToken: String) : SecretsOrigin + } + + /** Places sensitive keys at every structural position the encoder supports. */ + @Serializable + data class SecretsEverywhere( + val query: String, + val authToken: String, + val password: String?, + val sort: Sort, + val profile: SecretsProfile, + val items: List, + val headers: Map, + val filters: Map>, + val rows: List>, + val grid: List>>, + val label: Wrapped, + val sessionSecret: Wrapped, + val origin: SecretsOrigin, + val authOrigin: SecretsOrigin, + val refreshTokens: List, + val credentials: Map, + val reference: TokenRef, + ) + + // Sensitive values + + @Test + fun `encode() - replaces the values of sensitive properties with the Filtered substitute`() { + val entry = WithSensitiveProperty(query = "shoes", password = "secret") + + val encoded = encodeToMap(WithSensitiveProperty.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("query" to "shoes", "password" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces a null sensitive property with the Filtered substitute`() { + val entry = WithNullableSecret(id = "1", password = null) + + val encoded = encodeToMap(WithNullableSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "password" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces the values of sensitive map keys with the Filtered substitute`() { + val entry = WithSensitiveMapKey(mapOf("query" to "shoes", "authToken" to "secret")) + + val encoded = encodeToMap(WithSensitiveMapKey.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "params" to mapOf("query" to "shoes", "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces the values of sensitive map keys in maps nested in lists with the Filtered substitute`() { + val entry = + WithSensitiveKeysInList( + nested = mapOf("items" to listOf(mapOf("authToken" to "secret", "query" to "shoes"))), + ) + + val encoded = encodeToMap(WithSensitiveKeysInList.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "nested" to + mapOf( + "items" to + listOf( + mapOf("authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE, "query" to "shoes"), + ), + ), + ), + ) + } + + @Test + fun `encode() - replaces the values of value class map keys whose text is sensitive with the Filtered substitute`() { + val entry = + WithHeaderNameMapKeys( + mapOf(HeaderName("Accept") to "json", HeaderName("Authorization") to "Bearer abc123"), + ) + + val encoded = encodeToMap(WithHeaderNameMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf("Accept" to "json", "Authorization" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces map entries with the Filtered substitute if their key's underlying property is sensitive`() { + val entry = + WithSensitiveValueClassMapKeys( + mapOf( + SensitiveHeaderName("Authorization") to "Bearer LEAKED-SECRET-1", + SensitiveHeaderName("X-Api-Key") to "LEAKED-SECRET-2", + // Filtered by its underlying property name even though its text isn't sensitive. + SensitiveHeaderName("Accept") to "LEAKED-SECRET-3", + ), + ) + + val encoded = encodeToMap(WithSensitiveValueClassMapKeys.serializer(), entry) + + // The filtered keys share one text, so they collapse to a single entry. + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf(UrlUtils.SENSITIVE_DATA_SUBSTITUTE to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + assertThat(leavesOf(encoded).values.filter { it.contains("LEAKED-SECRET") }).isEmpty() + } + + @Test + fun `encode() - replaces a map value with the Filtered substitute based only on its own key`() { + val entry = + WithMixedHeaderMapKeys( + mapOf( + MixedHeader("Accept", isSecret = false) to "VISIBLE-1", + MixedHeader("Authorization", isSecret = true) to "LEAKED-SECRET-1", + MixedHeader("Accept-Language", isSecret = false) to "VISIBLE-2", + ), + ) + + val encoded = encodeToMap(WithMixedHeaderMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf( + "Accept" to "VISIBLE-1", + UrlUtils.SENSITIVE_DATA_SUBSTITUTE to UrlUtils.SENSITIVE_DATA_SUBSTITUTE, + "Accept-Language" to "VISIBLE-2", + ), + ), + ) + } + + // Security regression test: a filtered key must not overwrite or merge with a visible entry. + @Test + fun `encode() - drops the arguments for a duplicate key when a filtered map key matches an unfiltered key's text`() { + val entry = + WithMixedHeaderMapKeys( + mapOf( + MixedHeader(UrlUtils.SENSITIVE_DATA_SUBSTITUTE, isSecret = false) to "VISIBLE", + MixedHeader("Authorization", isSecret = true) to "LEAKED-SECRET", + ), + ) + + val exception = + assertFailsWith { + encodeToMap(WithMixedHeaderMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + // Security regression test: a visible entry must not merge with an earlier filtered key. + @Test + fun `encode() - drops the arguments for a duplicate key when an unfiltered key matches an earlier filtered one`() { + val entry = + WithMixedHeaderMapKeys( + mapOf( + MixedHeader("Authorization", isSecret = true) to "LEAKED-SECRET", + MixedHeader(UrlUtils.SENSITIVE_DATA_SUBSTITUTE, isSecret = false) to "VISIBLE", + ), + ) + + val exception = + assertFailsWith { + encodeToMap(WithMixedHeaderMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - replaces map values with the Filtered substitute when their underlying property is sensitive`() { + val entry = WithSensitiveValueClassMapValues(mapOf("reference" to TokenRef("abc123"))) + + val encoded = encodeToMap(WithSensitiveValueClassMapValues.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("params" to mapOf("reference" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE))) + } + + @Test + fun `encode() - replaces the values of properties whose serial name is sensitive with the Filtered substitute`() { + val entry = WithSerialNames(side = "left", label = "secret") + + val encoded = encodeToMap(WithSerialNames.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("position" to "left", "apiKey" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces value class properties whose property name is sensitive with the Filtered substitute`() { + val entry = + WithSensitiveValueClassPropertyName( + productId = ProductId("p-1"), + sessionRef = ProductId("secret"), + ) + + val encoded = encodeToMap(WithSensitiveValueClassPropertyName.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("productId" to "p-1", "sessionRef" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces properties with the Filtered substitute when their underlying property is sensitive`() { + val entry = + WithSensitiveUnderlyingPropertyName(productId = ProductId("p-1"), reference = TokenRef("abc")) + + val encoded = encodeToMap(WithSensitiveUnderlyingPropertyName.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("productId" to "p-1", "reference" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces a top-level value with the Filtered substitute when its underlying property is sensitive`() { + val encoded = encodeToMap(TokenRef.serializer(), TokenRef("abc123")) + + assertThat(encoded) + .isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces list elements with the Filtered substitute when their underlying property is sensitive`() { + val entry = WithValueClassList(listOf(TokenRef("abc"), TokenRef("def"))) + + val encoded = encodeToMap(WithValueClassList.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "references" to + listOf(UrlUtils.SENSITIVE_DATA_SUBSTITUTE, UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces a wrapped structure with the Filtered substitute if its underlying property is sensitive`() { + val entry = WithStructuredValueClass(CredentialsRef(Credentials(user = "jane"))) + + val encoded = encodeToMap(WithStructuredValueClass.serializer(), entry) + + assertThat(encoded).isEqualTo(mapOf("owner" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - counts a sensitive property as one value regardless of its size`() { + val entry = + WithLargeSecret(id = "1", refreshTokens = List(MAX_ARGUMENT_VALUES + 1) { "token$it" }) + + val encoded = encodeToMap(WithLargeSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "refreshTokens" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - counts a sensitive map value as one value regardless of its size`() { + val entry = + WithLargeSecretMapValue( + params = mapOf("query" to listOf(1), "authToken" to List(MAX_ARGUMENT_VALUES + 1) { it }), + ) + + val encoded = encodeToMap(WithLargeSecretMapValue.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "params" to + mapOf("query" to listOf(1), "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - counts map entries with filtered keys as one value however many there are`() { + val entry = + WithSensitiveValueClassMapKeys( + (0..MAX_ARGUMENT_VALUES).associate { SensitiveHeaderName("header$it") to "secret$it" }, + ) + + val encoded = encodeToMap(WithSensitiveValueClassMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf(UrlUtils.SENSITIVE_DATA_SUBSTITUTE to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - drops the arguments when a map skips more filtered keys than the value limit`() { + val entry = + WithSensitiveValueClassMapKeys( + (0..MAX_ARGUMENT_VALUES + 1).associate { SensitiveHeaderName("header$it") to "secret$it" }, + ) + + val thrown = + assertFailsWith { + encodeToMap(WithSensitiveValueClassMapKeys.serializer(), entry) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + } + + @Test + fun `encode() - doesn't run the serializers of sensitive properties`() { + val entry = WithUnencodableSecret(id = "1", authToken = "secret") + + val encoded = encodeToMap(WithUnencodableSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - doesn't run the serializers of sensitive map values`() { + val entry = WithUnencodableSecretMapValue(mapOf("authToken" to "secret")) + + val encoded = encodeToMap(WithUnencodableSecretMapValue.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("params" to mapOf("authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE))) + } + + @Test + fun `encode() - doesn't run the serializers wrapped by a value class with a sensitive underlying property`() { + val entry = WithUnencodableSecretRef(id = "1", ref = UnencodableSecretRef("secret")) + + val encoded = encodeToMap(WithUnencodableSecretRef.serializer(), entry) + + assertThat(encoded).isEqualTo(mapOf("id" to "1", "ref" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + /** + * Deliberately structure-agnostic: rather than asserting the encoded shape, this walks the whole + * output looking for any secret at the structural positions [SecretsEverywhere] covers. It checks + * the end result only, so it passes whether the encoders' own checks or `SensitiveKeyFilter` + * filter each value; it can't tell whether an encoding path bypasses the encoders' checks. + */ + @Test + fun `encode() - doesn't record the values of sensitive keys anywhere in the encoded tree`() { + val entry = + SecretsEverywhere( + query = "VISIBLE-1", + authToken = "LEAKED-SECRET-1", + password = "LEAKED-SECRET-2", + sort = Sort.NEWEST, + profile = SecretsProfile(name = "VISIBLE-2", password = "LEAKED-SECRET-3"), + items = + listOf( + SecretsItem(sku = "VISIBLE-3", apiKey = "LEAKED-SECRET-4"), + SecretsItem(sku = "VISIBLE-4", apiKey = "LEAKED-SECRET-5"), + ), + headers = mapOf("accept" to "VISIBLE-5", "X-Api-Key" to "LEAKED-SECRET-6"), + filters = mapOf("color" to mapOf("shade" to "VISIBLE-6", "sessionId" to "LEAKED-SECRET-7")), + rows = listOf(mapOf("note" to "VISIBLE-7", "Bearer" to "LEAKED-SECRET-8")), + grid = listOf(listOf(mapOf("cell" to "VISIBLE-8", "jwt" to "LEAKED-SECRET-9"))), + label = Wrapped("VISIBLE-9"), + sessionSecret = Wrapped("LEAKED-SECRET-10"), + origin = SecretsOrigin.Login(user = "VISIBLE-10", authToken = "LEAKED-SECRET-11"), + authOrigin = SecretsOrigin.Login(user = "LEAKED-SECRET-12", authToken = "LEAKED-SECRET-13"), + refreshTokens = listOf("LEAKED-SECRET-14", "LEAKED-SECRET-15"), + credentials = mapOf("user" to "LEAKED-SECRET-16"), + reference = TokenRef("LEAKED-SECRET-17"), + ) + + val leaves = leavesOf(encodeToMap(SecretsEverywhere.serializer(), entry)) + + assertThat(leaves.filterValues { it.contains("LEAKED-SECRET") }).isEmpty() + assertThat(leaves.values).containsAtLeastElementsIn((1..10).map { "VISIBLE-$it" } + "NEWEST") + // authToken, password, PASSWORD, apiKey (x2), X-Api-Key, sessionId, Bearer, jwt, + // sessionSecret, origin's authToken, authOrigin, refreshTokens, credentials, and reference + // (whose value class wraps a token). + assertThat(leaves.values.count { it == UrlUtils.SENSITIVE_DATA_SUBSTITUTE }).isEqualTo(15) + } + + /** + * Flattens [value] into its map keys and scalar values, stringified and keyed by their path, so + * that a failing assertion names where each one sits. + */ + private fun leavesOf( + value: Any?, + path: String = "", + leaves: MutableMap = LinkedHashMap(), + ): Map { + when (value) { + is Map<*, *> -> + value.forEach { (key, child) -> + leaves["$path.$key (key)"] = key.toString() + leavesOf(child, "$path.$key", leaves) + } + is Iterable<*> -> + value.forEachIndexed { index, child -> leavesOf(child, "$path[$index]", leaves) } + else -> leaves[path] = value.toString() + } + return leaves + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt new file mode 100644 index 00000000000..dd50ce462ce --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt @@ -0,0 +1,426 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.common.budgetWithValuesRemaining +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderLimitsTest { + + @Serializable + class SelfReferencing { + var next: SelfReferencing? = null + } + + /** Nests a polymorphic and a value class serializer at every other level. */ + @Serializable @JvmInline value class LayerRef(val layer: Layer) + + @Serializable + sealed interface Layer { + @Serializable @SerialName("node") data class Node(val child: LayerRef) : Layer + + @Serializable @SerialName("leaf") data class Leaf(val value: String) : Layer + } + + /** + * Encodes a link with [LinkSerializer], and if that throws [DropArgumentsException], records it + * and encodes a fallback with [recover] instead. + */ + internal class RecoveringLinkSerializer(private val recover: (Encoder) -> Unit) : + KSerializer { + var caught: DropArgumentsException? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.RecoveringLink", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + try { + encoder.encodeSerializableValue(LinkSerializer, value) + } catch (e: DropArgumentsException) { + caught = e + recover(encoder) + } + } + + override fun deserialize(decoder: Decoder): Link = Link(decoder.decodeString()) + } + + /** A value that [CatchingWriteSerializer] encodes. */ + private class Code(val code: String) + + /** Writes nothing, counting its calls in [calls]. */ + private class WritesNothingSerializer : KSerializer { + var calls = 0 + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.WritesNothing", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: String) { + calls++ + } + + override fun deserialize(decoder: Decoder): String = throw UnsupportedOperationException() + } + + /** + * Writes the code, recording a [DropArgumentsException] that throws in [caught], then encodes a + * fallback with [fallback]. + */ + private class CatchingWriteSerializer(private val fallback: KSerializer) : + KSerializer { + var caught: DropArgumentsException? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.CatchingWrite", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Code) { + try { + encoder.encodeString(value.code) + } catch (e: DropArgumentsException) { + caught = e + } + encoder.encodeSerializableValue(fallback, "fallback") + } + + override fun deserialize(decoder: Decoder): Code = throw UnsupportedOperationException() + } + + // Character limit + + @Test + fun `encode() - encodes an entry with the maximum number of characters, counting property names`() { + // The Box's property name and its value together are the maximum. + val value = "x".repeat(MAX_ARGUMENT_CHARACTERS - "value".length) + val (serializer, entry) = boxed(depth = 1, value = value, String.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to value)) + } + + @Test + fun `encode() - drops the arguments for the character limit when property names put an entry one character over`() { + val value = "x".repeat(MAX_ARGUMENT_CHARACTERS - "value".length + 1) + val (serializer, entry) = boxed(depth = 1, value = value, String.serializer()) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(exception.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) + } + + @Test + fun `encode() - encodes a map key of the maximum number of characters`() { + // A top-level map has no property names, and Int values, so the key is the only text counted. + val value = mapOf("k".repeat(MAX_ARGUMENT_CHARACTERS) to 1) + val (serializer, entry) = + boxed(depth = 0, value = value, MapSerializer(String.serializer(), Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(value) + } + + @Test + fun `encode() - drops the arguments for the character limit when a map key is too long`() { + val (serializer, entry) = + boxed( + depth = 0, + value = mapOf("k".repeat(MAX_ARGUMENT_CHARACTERS + 1) to 1), + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(exception.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) + } + + // Depth limit + + @Test + fun `encode() - encodes a value at the maximum depth`() { + val (serializer, entry) = boxed(depth = MAX_ARGUMENT_DEPTH, value = "leaf", String.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = "leaf")) + } + + @Test + fun `encode() - encodes polymorphic and value class properties at the maximum depth`() { + // The leaf's value sits at depth 2, and each node nests its child two levels deeper. + val nodes = (MAX_ARGUMENT_DEPTH - 2) / 2 + var layer: Layer = Layer.Leaf("leaf") + repeat(nodes) { layer = Layer.Node(LayerRef(layer)) } + + val encoded = encodeToMap(LayerRef.serializer(), LayerRef(layer)) + + var expected: Map = mapOf("type" to "leaf", "value" to mapOf("value" to "leaf")) + repeat(nodes) { expected = mapOf("type" to "node", "value" to mapOf("child" to expected)) } + assertThat(encoded).isEqualTo(expected) + } + + @Test + fun `encode() - drops the arguments for invalid structure when a value is nested past the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH + 1, value = "leaf", String.serializer()) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for a list, so an empty list fits at the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH, value = emptyList(), ListSerializer(String.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded) + .isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = emptyList())) + } + + @Test + fun `encode() - adds one level of depth for a list, so a list's elements can't be past the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH, value = listOf("a"), ListSerializer(String.serializer())) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for a map, so a map's values can't be past the maximum depth`() { + val (serializer, entry) = + boxed( + depth = MAX_ARGUMENT_DEPTH, + value = mapOf("a" to 1), + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for an object, so an object without properties fits at the maximum depth`() { + val (serializer, entry) = boxed(depth = MAX_ARGUMENT_DEPTH, value = Home, Home.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded) + .isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = emptyMap())) + } + + @Test + fun `encode() - stops at the depth limit when an entry references itself`() { + val entry = SelfReferencing().apply { next = this } + + val exception = + assertFailsWith { encodeToMap(SelfReferencing.serializer(), entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + // Value limit + + @Test + fun `encode() - encodes an entry with the maximum number of values`() { + // The list property and its elements are the maximum. + val values = List(MAX_ARGUMENT_VALUES - 1) { it } + val (serializer, entry) = boxed(depth = 1, value = values, ListSerializer(Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to values)) + } + + @Test + fun `encode() - drops the arguments for count when an entry has one value too many`() { + val (serializer, entry) = + boxed(depth = 1, value = List(MAX_ARGUMENT_VALUES) { it }, ListSerializer(Int.serializer())) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(exception.warning).isEqualTo(DropArgumentsException.MAX_COUNT_WARNING) + } + + @Test + fun `encode() - doesn't count map keys as values`() { + // The map property and its values are the maximum; counting the keys would exceed it. + val values = (0 until MAX_ARGUMENT_VALUES - 1).associate { "item$it" to it } + val (serializer, entry) = + boxed(depth = 1, value = values, MapSerializer(String.serializer(), Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to values)) + } + + @Test + fun `encode() - drops the arguments for count when a map has one value too many`() { + val (serializer, entry) = + boxed( + depth = 1, + value = (0 until MAX_ARGUMENT_VALUES).associate { "item$it" to it }, + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(exception.warning).isEqualTo(DropArgumentsException.MAX_COUNT_WARNING) + } + + // Serializer nesting limit + + @Test + fun `encode() - encodes custom serializers nested up to the maximum number of calls`() { + // The top-level serializer is the first call, and each next link nests one more. + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val encoded = encodeToMap(LinkSerializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to "leaf")) + } + + @Test + fun `encode() - counts only nested serializer calls toward the nesting limit`() { + // Each element's serializer call returns before the next element's begins. + val values = List(KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) { it } + + val encoded = encodeToMap(ListSerializer(Int.serializer()), values) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to values)) + } + + @Test + fun `encode() - drops the arguments for invalid structure when custom serializers nest too many calls deep`() { + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) + + val exception = assertFailsWith { encodeToMap(LinkSerializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - drops the arguments for invalid structure when a custom serializer recurses through a cycle`() { + val entry = Link("leaf").apply { next = this } + + val exception = assertFailsWith { encodeToMap(LinkSerializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - records the nesting failure on the sink`() { + val sink = TreeArgumentSink(ArgumentBudget()) + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) + + val exception = + assertFailsWith { encodeInto(LinkSerializer, entry, sink) } + + assertThat(assertFailsWith { sink.checkNotDropped() }) + .isSameInstanceAs(exception) + } + + @Test + fun `encode() - keeps failing when a serializer catches the nesting failure and calls another serializer`() { + // The recovering serializer is the first call, so its link chain nests one call too many. + val serializer = RecoveringLinkSerializer { + it.encodeSerializableValue(String.serializer(), "fallback") + } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - throws the caught nesting failure when a serializer catches it and writes a value directly`() { + val serializer = RecoveringLinkSerializer { it.encodeString("fallback") } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - keeps the nesting failure on the sink when a serializer catches it and returns`() { + val sink = TreeArgumentSink(ArgumentBudget()) + val serializer = RecoveringLinkSerializer {} + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + encodeInto(serializer, entry, sink) + + val exception = assertFailsWith { sink.argumentsOrThrow() } + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `encode() - propagates a serializer's exception in place of the nesting failure, which the sink keeps`() { + val error = SerializationException("replaced") + val sink = TreeArgumentSink(ArgumentBudget()) + val serializer = RecoveringLinkSerializer { throw error } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val thrown = assertFailsWith { encodeInto(serializer, entry, sink) } + + assertThat(thrown).isSameInstanceAs(error) + val recorded = assertFailsWith { sink.checkNotDropped() } + assertThat(recorded).isSameInstanceAs(serializer.caught) + assertThat(recorded.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `encode() - doesn't run another serializer after a serializer catches the sink's broken limit`() { + val fallback = WritesNothingSerializer() + val serializer = CatchingWriteSerializer(fallback) + val sink = TreeArgumentSink(budgetWithValuesRemaining(0)) + + val exception = + assertFailsWith { encodeInto(serializer, Code("x"), sink) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(fallback.calls).isEqualTo(0) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt new file mode 100644 index 00000000000..a6a49bd24f2 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt @@ -0,0 +1,508 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import java.math.BigInteger +import kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Polymorphic +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.Transient +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderTest { + + @Serializable + data class Product( + val name: String, + val inStock: Boolean, + val price: Double, + val grade: Char, + val quantity: Long, + val note: String?, + ) + + @Serializable data class Filters(val minPrice: Int, val brands: List) + + @Serializable data class WithNestedClass(val query: String, val filters: Filters) + + @Serializable data class WithCollections(val names: List, val tags: Set) + + @Serializable + enum class Sort { + @SerialName("price_asc") PRICE_ASC, + NEWEST, + } + + @Serializable data class WithEnums(val primary: Sort, val secondary: Sort) + + @Serializable @JvmInline value class ProductId(val value: String) + + @Serializable data class WithValueClass(val productId: ProductId) + + @Serializable data class WithDefault(val query: String, val page: Int = 1) + + @Serializable + data class WithTransient(val query: String, @Transient val cached: String = "not recorded") + + @Serializable + sealed interface Origin { + @Serializable @SerialName("search") data class Search(val query: String) : Origin + + @Serializable @SerialName("deeplink") data object DeepLink : Origin + } + + @Serializable data class WithOrigin(val productId: String, val origin: Origin) + + @Serializable(with = CustomSerializer::class) data class CustomSerialized(val id: String) + + object CustomSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: CustomSerialized) { + encoder.encodeString(value.id) + } + + override fun deserialize(decoder: Decoder): CustomSerialized = + CustomSerialized(decoder.decodeString()) + } + + @Serializable + data class WithUnsignedNumbers( + val uByte: UByte, + val uShort: UShort, + val uInt: UInt, + val uLong: ULong, + ) + + @Serializable data class WithULong(val uLong: ULong) + + @Serializable + data class WithSignedNumbers(val byte: Byte, val short: Short, val int: Int, val long: Long) + + @Serializable data class WithIntMapKeys(val counts: Map) + + @Serializable + data class WithEncodedMapKeys(val bySort: Map, val byRank: Map) + + @Serializable data class WithNullableMapKeys(val counts: Map) + + @Serializable + data class WithWrappedMapKeys( + val byProduct: Map, + val byCustom: Map, + ) + + /** A key that's recorded by its [name] alone, so keys that differ only in [version] collide. */ + @Serializable(with = VersionedNameSerializer::class) + data class VersionedName(val name: String, val version: Int) + + object VersionedNameSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.VersionedName", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: VersionedName) { + encoder.encodeString(value.name) + } + + override fun deserialize(decoder: Decoder): VersionedName = + VersionedName(decoder.decodeString(), version = 0) + } + + @Serializable data class WithVersionedNameMapKeys(val byName: Map) + + @Serializable data class Point(val x: Int) + + @Serializable data class WithPointMapKeys(val byPoint: Map) + + @Serializable @JvmInline value class PointRef(val point: Point) + + @Serializable data class WithPointRefMapKeys(val byPointRef: Map) + + @Serializable data class WithListMapKeys(val byList: Map, Int>) + + @Serializable data class WithMapMapKeys(val byMap: Map, Int>) + + @Serializable data class WithOriginMapKeys(val byOrigin: Map) + + @Serializable data class WithNestedPointMapKeys(val groups: List>) + + interface OpenOrigin + + @Serializable data class WithOpenPolymorphic(val id: String, @Polymorphic val origin: OpenOrigin) + + // Encoded shapes + + @Test + fun `encode() - encodes a class as a map from property name to value`() { + val entry = + Product( + name = "shoes", + inStock = false, + price = 0.5, + grade = 'A', + quantity = 3L, + note = null, + ) + + val encoded = encodeToMap(Product.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "name" to "shoes", + "inStock" to false, + "price" to 0.5, + "grade" to "A", + "quantity" to 3L, + "note" to null, + ), + ) + } + + @Test + fun `encode() - encodes a nested class as a nested map`() { + val entry = WithNestedClass("shoes", Filters(minPrice = 10, brands = listOf("a"))) + + val encoded = encodeToMap(WithNestedClass.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("query" to "shoes", "filters" to mapOf("minPrice" to 10, "brands" to listOf("a"))), + ) + } + + @Test + fun `encode() - encodes lists and sets as lists`() { + val entry = WithCollections(names = listOf("a", null), tags = setOf("new", "sale")) + + val encoded = encodeToMap(WithCollections.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("names" to listOf("a", null), "tags" to listOf("new", "sale"))) + } + + @Test + fun `encode() - encodes enums by their serial name`() { + val encoded = encodeToMap(WithEnums.serializer(), WithEnums(Sort.PRICE_ASC, Sort.NEWEST)) + + assertThat(encoded).isEqualTo(mapOf("primary" to "price_asc", "secondary" to "NEWEST")) + } + + @Test + fun `encode() - encodes value classes by their underlying value`() { + val encoded = encodeToMap(WithValueClass.serializer(), WithValueClass(ProductId("p-1"))) + + assertThat(encoded).isEqualTo(mapOf("productId" to "p-1")) + } + + @Test + fun `encode() - encodes properties that have their default values`() { + val encoded = encodeToMap(WithDefault.serializer(), WithDefault(query = "shoes")) + + assertThat(encoded).isEqualTo(mapOf("query" to "shoes", "page" to 1)) + } + + @Test + fun `encode() - omits @Transient properties`() { + val encoded = encodeToMap(WithTransient.serializer(), WithTransient(query = "shoes")) + + assertThat(encoded).isEqualTo(mapOf("query" to "shoes")) + } + + @Test + fun `encode() - encodes polymorphic properties as their serial name and value`() { + val search = encodeToMap(WithOrigin.serializer(), WithOrigin("p-1", Origin.Search("shoes"))) + val deepLink = encodeToMap(WithOrigin.serializer(), WithOrigin("p-1", Origin.DeepLink)) + + assertThat(search) + .isEqualTo( + mapOf( + "productId" to "p-1", + "origin" to mapOf("type" to "search", "value" to mapOf("query" to "shoes")), + ), + ) + assertThat(deepLink) + .isEqualTo( + mapOf( + "productId" to "p-1", + "origin" to mapOf("type" to "deeplink", "value" to emptyMap()), + ), + ) + } + + @Test + fun `encode() - encodes an object without properties as an empty map`() { + val encoded = encodeToMap(Home.serializer(), Home) + + assertThat(encoded).isEmpty() + } + + @Test + fun `encode() - wraps a top-level value that doesn't encode to a structure under the value key`() { + val encoded = encodeToMap(CustomSerializer, CustomSerialized("abc")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "abc")) + } + + @Test + fun `encode() - wraps a top-level list under the value key`() { + val encoded = encodeToMap(ListSerializer(String.serializer()), listOf("a", "b")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to listOf("a", "b"))) + } + + @Test + fun `encode() - encodes a top-level map's entries as the arguments`() { + val encoded = + encodeToMap(MapSerializer(String.serializer(), Int.serializer()), mapOf("page" to 2)) + + assertThat(encoded).isEqualTo(mapOf("page" to 2)) + } + + @Test + fun `encode() - wraps a top-level value class's underlying value under the value key`() { + val encoded = encodeToMap(ProductId.serializer(), ProductId("p-1")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "p-1")) + } + + @Test + fun `encode() - wraps a top-level enum's serial name under the value key`() { + val encoded = encodeToMap(Sort.serializer(), Sort.PRICE_ASC) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "price_asc")) + } + + @Test + fun `encode() - encodes a top-level polymorphic value's serial name and value as the arguments`() { + val encoded = encodeToMap(Origin.serializer(), Origin.Search("shoes")) + + assertThat(encoded).isEqualTo(mapOf("type" to "search", "value" to mapOf("query" to "shoes"))) + } + + // Numbers + + @Test + fun `encode() - encodes unsigned numbers by their unsigned value`() { + val entry = + WithUnsignedNumbers( + uByte = UByte.MAX_VALUE, + uShort = UShort.MAX_VALUE, + uInt = UInt.MAX_VALUE, + uLong = Long.MAX_VALUE.toULong(), + ) + + val encoded = encodeToMap(WithUnsignedNumbers.serializer(), entry) + + val uByteMax: Int = 255 + val uShortMax: Int = 65_535 + val uIntMax: Long = 4_294_967_295L + assertThat(encoded) + .isEqualTo( + mapOf( + "uByte" to uByteMax, + "uShort" to uShortMax, + "uInt" to uIntMax, + "uLong" to Long.MAX_VALUE, + ), + ) + } + + @Test + fun `encode() - wraps a top-level unsigned number's unsigned value under the value key`() { + val encoded = encodeToMap(UInt.serializer(), UInt.MAX_VALUE) + + val uIntMax: Long = 4_294_967_295L + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to uIntMax)) + } + + @Test + fun `encode() - encodes a ULong above Long MAX_VALUE as a BigInteger`() { + val encoded = encodeToMap(WithULong.serializer(), WithULong(ULong.MAX_VALUE)) + + assertThat(encoded).isEqualTo(mapOf("uLong" to BigInteger("18446744073709551615"))) + } + + @Test + fun `encode() - encodes negative signed numbers as-is`() { + val entry = WithSignedNumbers(byte = -1, short = -1, int = -1, long = -1L) + + val encoded = encodeToMap(WithSignedNumbers.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("byte" to (-1).toByte(), "short" to (-1).toShort(), "int" to -1, "long" to -1L), + ) + } + + // Map keys + + @Test + fun `encode() - converts map keys to strings`() { + val encoded = encodeToMap(WithIntMapKeys.serializer(), WithIntMapKeys(mapOf(1 to 2L))) + + assertThat(encoded).isEqualTo(mapOf("counts" to mapOf("1" to 2L))) + } + + @Test + fun `encode() - converts enum and unsigned map keys to strings of their encoded values`() { + val entry = + WithEncodedMapKeys(bySort = mapOf(Sort.PRICE_ASC to 1), byRank = mapOf(UInt.MAX_VALUE to 2)) + + val encoded = encodeToMap(WithEncodedMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("bySort" to mapOf("price_asc" to 1), "byRank" to mapOf("4294967295" to 2)), + ) + } + + @Test + fun `encode() - converts a null map key to the string null`() { + val encoded = + encodeToMap(WithNullableMapKeys.serializer(), WithNullableMapKeys(mapOf(null to 1))) + + assertThat(encoded).isEqualTo(mapOf("counts" to mapOf("null" to 1))) + } + + @Test + fun `encode() - converts value class and custom serializer map keys to strings`() { + val entry = + WithWrappedMapKeys( + byProduct = mapOf(ProductId("p-1") to 1), + byCustom = mapOf(CustomSerialized("c-1") to 2), + ) + + val encoded = encodeToMap(WithWrappedMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("byProduct" to mapOf("p-1" to 1), "byCustom" to mapOf("c-1" to 2))) + } + + @Test + fun `encode() - drops the arguments for a duplicate key when a null map key and the string null are both keys`() { + val entry = WithNullableMapKeys(mapOf(null to 1, "null" to 2)) + + val exception = + assertFailsWith { + encodeToMap(WithNullableMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - drops the arguments for a duplicate key when a custom serializer encodes two keys as one string`() { + val entry = + WithVersionedNameMapKeys(mapOf(VersionedName("home", 1) to 1, VersionedName("home", 2) to 2)) + + val exception = + assertFailsWith { + encodeToMap(WithVersionedNameMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - throws for a class map key`() { + val entry = WithPointMapKeys(mapOf(Point(1) to 2)) + + assertFailsWith { + encodeToMap(WithPointMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a value class map key that wraps a class`() { + val entry = WithPointRefMapKeys(mapOf(PointRef(Point(1)) to 2)) + + assertFailsWith { + encodeToMap(WithPointRefMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a list map key`() { + // Converting this key to a string would copy the one 16 KiB string 4,000 times (~64 MiB). + val longString = "a".repeat(16 * 1024) + val entry = WithListMapKeys(mapOf(List(4_000) { longString } to 1)) + + assertFailsWith { + encodeToMap(WithListMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a map map key`() { + val entry = WithMapMapKeys(mapOf(mapOf("a" to 1) to 2)) + + assertFailsWith { + encodeToMap(WithMapMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a polymorphic map key`() { + val entry = WithOriginMapKeys(mapOf(Origin.Search("shoes") to 1)) + + assertFailsWith { + encodeToMap(WithOriginMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a class map key in a map nested in a list`() { + val entry = WithNestedPointMapKeys(listOf(mapOf(Point(1) to 2))) + + assertFailsWith { + encodeToMap(WithNestedPointMapKeys.serializer(), entry) + } + } + + // Unsupported properties + + @Test + fun `encode() - throws for a contextual property without a registered serializer`() { + val entry = WithContextual("1", Unregistered("2")) + + assertFailsWith { + encodeToMap(WithContextual.serializer(), entry) + } + } + + @Test + fun `encode() - throws for an open polymorphic property without a registered serializer`() { + val entry = WithOpenPolymorphic("1", object : OpenOrigin {}) + + assertFailsWith { + encodeToMap(WithOpenPolymorphic.serializer(), entry) + } + } + + // Serializer failures + + @Test + fun `encode() - propagates a serializer's exception unchanged`() { + val error = IllegalStateException("boom") + val serializer = RecordingSerializer(Detail.serializer()).apply { this.error = error } + + val thrown = assertFailsWith { encodeToMap(serializer, Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt index d06ebe92abb..42c8bbb3948 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -2,9 +2,14 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlinx.serialization.Contextual import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder @@ -14,9 +19,91 @@ import kotlinx.serialization.encoding.Encoder @Serializable @SerialName("Search") internal data class Search(val query: String) +internal class Unregistered(val id: String) + +@Serializable +@SerialName("WithContextual") +internal data class WithContextual(val id: String, @Contextual val other: Unregistered) + /** A serializer for tests that only read its descriptor, e.g., to name an entry. */ internal abstract class NamingOnlySerializer : KSerializer { override fun serialize(encoder: Encoder, value: T) = throw UnsupportedOperationException() override fun deserialize(decoder: Decoder): T = throw UnsupportedOperationException() } + +@Serializable internal data class Box(val value: T) + +/** Wraps [value] in [depth] nested [Box]es, so that [value] sits at [depth]. */ +internal fun boxed( + depth: Int, + value: T, + serializer: KSerializer, +): Pair, Any> { + var boxedSerializer: KSerializer<*> = serializer + var boxedValue: Any? = value + repeat(depth) { + @Suppress("UNCHECKED_CAST") + boxedSerializer = Box.serializer(boxedSerializer as KSerializer) + boxedValue = Box(boxedValue) + } + @Suppress("UNCHECKED_CAST") + return boxedSerializer as KSerializer to boxedValue!! +} + +/** The arguments the encoder produces for [boxed] when within its limits. */ +internal fun boxedArguments(depth: Int, value: Any?): Map { + var arguments: Any? = value + repeat(depth) { arguments = mapOf("value" to arguments) } + @Suppress("UNCHECKED_CAST") + return arguments as Map +} + +internal class Link(val id: String) { + var next: Link? = null +} + +/** + * Encodes a link as the id of the last link in its chain, encoding each next link in place of its + * own, so the recursion never begins a structure. + */ +internal object LinkSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.Link", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + val next = value.next + if (next != null) encoder.encodeSerializableValue(this, next) + else encoder.encodeString(value.id) + } + + override fun deserialize(decoder: Decoder): Link = Link(decoder.decodeString()) +} + +/** Chains [length] [Link]s, the last of which has the id `leaf`. */ +internal fun linked(length: Int): Link { + var link = Link("leaf") + repeat(length - 1) { index -> link = Link("link-$index").apply { next = link } } + return link +} + +/** + * Delegates to [delegate], recording each serialized value and throwing [error], if set, for the + * values [failsFor] accepts. + */ +internal class RecordingSerializer(private val delegate: KSerializer) : + KSerializer by delegate { + val serialized = mutableListOf() + var error: Throwable? = null + var failsFor: (T) -> Boolean = { true } + + override fun serialize(encoder: Encoder, value: T) { + serialized += value + error?.takeIf { failsFor(value) }?.let { throw it } + delegate.serialize(encoder, value) + } +} + +/** The arguments read from an entry whose arguments were dropped for [reason]. */ +internal fun droppedBy(reason: ArgumentDropReason): Map = + mapOf(ArgumentDropReason.ARGUMENT_DROP_REASON_KEY to reason.serializedValue) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt new file mode 100644 index 00000000000..f1f09f9ec2c --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt @@ -0,0 +1,199 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxPropertiesEncoder.SensitiveKeyFilter +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.util.UrlUtils.SENSITIVE_DATA_SUBSTITUTE +import kotlin.test.assertFailsWith +import org.junit.Test + +class SensitiveKeyFilterTest { + + private val sink = TreeArgumentSink(ArgumentBudget()) + private val filter = SensitiveKeyFilter(sink) + + // Keys, values, maps, and lists under non-sensitive keys + + @Test + fun `passes keys, scalars, maps, and lists under non-sensitive keys to the sink`() { + filter.key("query") + filter.scalar("shoes") + filter.key("filters") + filter.beginMap() + filter.key("brands") + filter.beginList() + filter.scalar("a") + filter.end() + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo(mapOf("query" to "shoes", "filters" to mapOf("brands" to listOf("a")))) + } + + // Next value sensitivity + + @Test + fun `isNextValueSensitive - is true after a sensitive key`() { + filter.key("authToken") + + assertThat(filter.isNextValueSensitive).isTrue() + } + + @Test + fun `isNextValueSensitive - is false after a non-sensitive key`() { + filter.key("query") + + assertThat(filter.isNextValueSensitive).isFalse() + } + + @Test + fun `isNextValueSensitive - is false once the sensitive key's value is written`() { + filter.key("authToken") + filter.scalar("secret") + + assertThat(filter.isNextValueSensitive).isFalse() + } + + // Scalars + + @Test + fun `scalar() - writes the substitute in place of a scalar under a sensitive key`() { + filter.key("password") + filter.scalar("hunter2") + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("password" to SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `scalar() - writes a scalar under a non-sensitive key that follows a sensitive key`() { + filter.key("password") + filter.scalar("hunter2") + filter.key("page") + filter.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("password" to SENSITIVE_DATA_SUBSTITUTE, "page" to 2)) + } + + @Test + fun `scalar() - writes list elements under a non-sensitive key, even if they look like sensitive keys`() { + filter.key("tags") + filter.beginList() + filter.scalar("password") + filter.scalar("token") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("tags" to listOf("password", "token"))) + } + + @Test + fun `scalar() - writes the substitute under the sensitive keys of maps in a list`() { + filter.key("rows") + filter.beginList() + filter.beginMap() + filter.key("jwt") + filter.scalar("t-1") + filter.key("note") + filter.scalar("visible") + filter.end() + filter.scalar("plain") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf( + "rows" to listOf(mapOf("jwt" to SENSITIVE_DATA_SUBSTITUTE, "note" to "visible"), "plain"), + ), + ) + } + + @Test + fun `beginMap() - throws without writing when a map starts under a sensitive key`() { + filter.key("credentials") + + assertFailsWith { filter.beginMap() } + sink.scalar(null) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("credentials" to null)) + } + + @Test + fun `beginList() - throws without writing when a list starts under a sensitive key`() { + filter.key("refreshTokens") + + assertFailsWith { filter.beginList() } + sink.scalar(null) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("refreshTokens" to null)) + } + + @Test + fun `beginMap() - writes a map under a non-sensitive key that follows a filtered scalar`() { + filter.key("password") + filter.scalar("hunter2") + filter.key("filters") + filter.beginMap() + filter.key("color") + filter.scalar("red") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf("password" to SENSITIVE_DATA_SUBSTITUTE, "filters" to mapOf("color" to "red")), + ) + } + + // Rejected limits + + @Test + fun `reject() - rejects the limit on the sink`() { + val drop = + assertFailsWith { + filter.reject( + ArgumentDropReason.INVALID_STRUCTURE, + DropArgumentsException.STRUCTURE_WARNING, + ) + } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(assertFailsWith { sink.checkNotDropped() }) + .isSameInstanceAs(drop) + } + + // Recorded drop + + @Test + fun `checkNotDropped() - doesn't throw while the sink has no drop`() { + filter.key("query") + filter.scalar("shoes") + + filter.checkNotDropped() + } + + @Test + fun `checkNotDropped() - throws the sink's drop`() { + val drop = + assertFailsWith { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArgumentsException.STRUCTURE_WARNING) + } + + val thrown = assertFailsWith { filter.checkNotDropped() } + + assertThat(thrown).isSameInstanceAs(drop) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgetTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgetTest.kt new file mode 100644 index 00000000000..63597a6ead3 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgetTest.kt @@ -0,0 +1,125 @@ +package io.sentry.compose.navigation3.internal.common + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlin.test.assertFailsWith +import org.junit.Test + +class ArgumentBudgetTest { + + /** Text whose reported [length] may differ from its text, counting its conversions. */ + private class MisreportedText(override val length: Int, private val text: String) : CharSequence { + var toStringCalls = 0 + + override fun get(index: Int): Char = text[index] + + override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = + text.subSequence(startIndex, endIndex) + + override fun toString(): String { + toStringCalls++ + return text + } + } + + private val budget = ArgumentBudget() + + // spendValue() + + @Test + fun `spendValue() - drops the arguments for the value limit once every value is spent`() { + repeat(MAX_ARGUMENT_VALUES) { budget.spendValue() } + + val drop = assertFailsWith { budget.spendValue() } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(drop.warning).isEqualTo(DropArgumentsException.MAX_COUNT_WARNING) + } + + @Test + fun `spendValue() - doesn't spend characters`() { + repeat(MAX_ARGUMENT_VALUES) { budget.spendValue() } + + val text = budget.spendText("x".repeat(MAX_ARGUMENT_CHARACTERS)) + + assertThat(text).hasLength(MAX_ARGUMENT_CHARACTERS) + } + + // spendText() + + @Test + fun `spendText() - returns the text as a String`() { + val text = budget.spendText(StringBuilder("hello")) + + assertThat(text).isEqualTo("hello") + } + + @Test + fun `spendText() - spends text exactly as long as the remaining characters`() { + val limited = budgetWithCharactersRemaining(2) + + val text = limited.spendText("ab") + + assertThat(text).isEqualTo("ab") + } + + @Test + fun `spendText() - drops the arguments for the character limit when text is longer than the remaining characters`() { + val limited = budgetWithCharactersRemaining(1) + + val drop = assertFailsWith { limited.spendText("ab") } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(drop.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) + } + + @Test + fun `spendText() - spends the characters of earlier text`() { + budget.spendText("x".repeat(MAX_ARGUMENT_CHARACTERS - 1)) + + val drop = assertFailsWith { budget.spendText("ab") } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `spendText() - doesn't convert text whose reported length doesn't fit`() { + val limited = budgetWithCharactersRemaining(1) + val text = MisreportedText(length = 2, text = "ab") + + assertFailsWith { limited.spendText(text) } + + assertThat(text.toStringCalls).isEqualTo(0) + } + + @Test + fun `spendText() - drops the arguments for text longer than its reported length when its text doesn't fit`() { + val limited = budgetWithCharactersRemaining(1) + + val drop = + assertFailsWith { + limited.spendText(MisreportedText(length = 1, text = "ab")) + } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `spendText() - spends the characters of the text rather than its reported length`() { + val limited = budgetWithCharactersRemaining(2) + limited.spendText(MisreportedText(length = 0, text = "ab")) + + val drop = assertFailsWith { limited.spendText("c") } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `spendText() - doesn't spend values`() { + budget.spendText("x".repeat(MAX_ARGUMENT_CHARACTERS)) + + repeat(MAX_ARGUMENT_VALUES) { budget.spendValue() } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgets.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgets.kt new file mode 100644 index 00000000000..4b3f76bb7ca --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgets.kt @@ -0,0 +1,12 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES + +/** Returns a budget with only [remaining] values left, as if other entries spent the rest. */ +internal fun budgetWithValuesRemaining(remaining: Int): ArgumentBudget = + ArgumentBudget().apply { repeat(MAX_ARGUMENT_VALUES - remaining) { spendValue() } } + +/** Returns a budget with only [remaining] characters left, as if other entries spent the rest. */ +internal fun budgetWithCharactersRemaining(remaining: Int): ArgumentBudget = + ArgumentBudget().apply { spendText("x".repeat(MAX_ARGUMENT_CHARACTERS - remaining)) } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt new file mode 100644 index 00000000000..6bd86d08fc7 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt @@ -0,0 +1,593 @@ +package io.sentry.compose.navigation3.internal.common + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.BeginList +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.BeginMap +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.End +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.Key +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.Reject +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.Scalar +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.UncomputedScalar +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import java.math.BigDecimal +import java.util.AbstractCollection +import kotlin.test.assertFailsWith +import org.junit.Test + +class HostArgumentSourceTest { + + private enum class PrivacyMode { + PUBLIC, + PRIVATE, + } + + private class OpaqueValue { + override fun toString(): String = "opaque-value" + } + + private class OpaqueIterable : Iterable { + override fun iterator(): Iterator = listOf("a").iterator() + + override fun toString(): String = "opaque-iterable" + } + + private class OpaqueSequence : Sequence { + override fun iterator(): Iterator = listOf("a").iterator() + + override fun toString(): String = "opaque-sequence" + } + + private data class UserId(val email: String) { + override fun toString(): String = email + } + + private class CountingValue { + var toStringCalls = 0 + + override fun toString(): String { + toStringCalls++ + return "counting-value" + } + } + + private val unsupportedTypeNames = mutableListOf() + private val sink = RecordingArgumentSink() + + // Arguments + + @Test + fun `writeTo() - writes each argument as its key followed by its value`() { + val source = hostArgumentSource(mapOf("id" to "123", "page" to 2)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("id"), Scalar("123"), Key("page"), Scalar(2)) + .inOrder() + } + + @Test + fun `writeTo() - writes nothing for empty arguments`() { + val source = hostArgumentSource(emptyMap()) + + source.writeTo(sink) + + assertThat(sink.events).isEmpty() + } + + @Test + fun `writeTo() - writes map keys by toString`() { + val key = + object { + override fun toString(): String = "custom-key" + } + val source = + hostArgumentSource(mapOf(1 to "a", PrivacyMode.PUBLIC to "b", key to "c", null to "d")) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly(Key("1"), Key("PUBLIC"), Key("custom-key"), Key("null")) + .inOrder() + } + + @Test + fun `writeTo() - describes a duplicate key by the types of the colliding keys rather than their values`() { + val source = + hostArgumentSource(linkedMapOf(UserId("ada@example.com") to "a", "ada@example.com" to "b")) + + val drop = + assertFailsWith { + source.writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + assertThat(drop.warning) + .isEqualTo( + "A Nav3 map key (String) stringifies to the same string as another key (UserId). " + + "Dropping this entry's arguments.", + ) + } + + @Test + fun `writeTo() - describes a null or anonymous map key that collides with another key as null`() { + val anonymous = + object { + override fun toString(): String = "id" + } + val sources = + listOf( + hostArgumentSource(linkedMapOf("null" to "a", null to "b")), + hostArgumentSource(linkedMapOf("id" to "a", anonymous to "b")), + ) + + val warnings = sources.map { source -> + assertFailsWith { + source.writeTo(TreeArgumentSink(ArgumentBudget())) + } + .warning + } + + val expected = + "A Nav3 map key (null) stringifies to the same string as another key (String). " + + "Dropping this entry's arguments." + assertThat(warnings).containsExactly(expected, expected) + } + + // Containers + + @Test + fun `writeTo() - writes a nested map between beginMap() and end()`() { + val nested = mapOf(1 to "a") + val source = hostArgumentSource(mapOf("nested" to nested)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("nested"), BeginMap, Key("1"), Scalar("a"), End) + .inOrder() + } + + @Test + fun `writeTo() - writes a collection as a list`() { + val set = linkedSetOf("a", "b") + val source = hostArgumentSource(mapOf("set" to set)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("set"), BeginList, Scalar("a"), Scalar("b"), End) + .inOrder() + } + + @Test + fun `writeTo() - writes an object array as a list`() { + val array = arrayOf("a", 1) + val source = hostArgumentSource(mapOf("array" to array)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("array"), BeginList, Scalar("a"), Scalar(1), End) + .inOrder() + } + + @Test + fun `writeTo() - writes primitive arrays as lists of their elements`() { + val source = + hostArgumentSource( + mapOf( + "booleans" to booleanArrayOf(true), + "bytes" to byteArrayOf(1), + "shorts" to shortArrayOf(2), + "ints" to intArrayOf(3), + "longs" to longArrayOf(4L), + "floats" to floatArrayOf(5f), + "doubles" to doubleArrayOf(6.0), + "chars" to charArrayOf('7'), + ), + ) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly( + Scalar(true), + Scalar(1.toByte()), + Scalar(2.toShort()), + Scalar(3), + Scalar(4L), + Scalar(5f), + Scalar(6.0), + Scalar('7'), + ) + .inOrder() + assertThat(sink.events.count { it is BeginList }).isEqualTo(8) + } + + @Test + fun `writeTo() - writes containers nested in containers recursively`() { + val inner = listOf(1) + val outer = mapOf("inner" to inner) + val source = hostArgumentSource(mapOf("outer" to listOf(outer))) + + source.writeTo(sink) + + assertThat(sink.events.drop(1)) + .containsExactly( + BeginList, + BeginMap, + Key("inner"), + BeginList, + Scalar(1), + End, + End, + End, + ) + .inOrder() + } + + @Test + fun `writeTo() - doesn't read the size of a collection`() { + val values = + object : AbstractCollection() { + var wasSizeRead = false + + override val size: Int + get() { + wasSizeRead = true + return Int.MAX_VALUE + } + + override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() + } + val source = hostArgumentSource(mapOf("values" to values)) + + source.writeTo(sink) + + assertThat(values.wasSizeRead).isFalse() + } + + // Cycles + + @Test + fun `writeTo() - rejects a map that contains itself as invalid structure`() { + val cyclic = mutableMapOf() + cyclic["self"] = cyclic + val source = hostArgumentSource(mapOf("cyclic" to cyclic)) + + val drop = assertFailsWith { source.writeTo(sink) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(drop.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + assertThat(sink.events.last()).isEqualTo(Reject(ArgumentDropReason.INVALID_STRUCTURE)) + } + + @Test + fun `writeTo() - rejects a nested value that contains the argument map as invalid structure`() { + val arguments = mutableMapOf() + arguments["children"] = listOf(arguments) + val source = hostArgumentSource(arguments) + + val drop = assertFailsWith { source.writeTo(sink) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(sink.events) + .containsExactly( + Key("children"), + BeginList, + BeginMap, + Reject(ArgumentDropReason.INVALID_STRUCTURE), + ) + .inOrder() + } + + @Test + fun `writeTo() - rejects a collection that contains itself as invalid structure`() { + val cyclic = mutableListOf() + cyclic.add(cyclic) + val source = hostArgumentSource(mapOf("cyclic" to cyclic)) + + val drop = assertFailsWith { source.writeTo(sink) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `writeTo() - rejects an array that contains itself as invalid structure`() { + val cyclic = arrayOfNulls(1) + cyclic[0] = cyclic + val source = hostArgumentSource(mapOf("cyclic" to cyclic)) + + val drop = assertFailsWith { source.writeTo(sink) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `writeTo() - starts a container that contains itself on the sink before rejecting it`() { + val cyclic = mutableListOf() + cyclic.add(cyclic) + val source = hostArgumentSource(mapOf("cyclic" to cyclic)) + + assertFailsWith { source.writeTo(sink) } + + assertThat(sink.events) + .containsExactly( + Key("cyclic"), + BeginList, + BeginList, + Reject(ArgumentDropReason.INVALID_STRUCTURE), + ) + .inOrder() + } + + @Test + fun `writeTo() - writes a container that appears more than once without containing itself`() { + val shared = listOf("a") + val source = hostArgumentSource(mapOf("first" to shared, "second" to listOf(shared))) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly( + Key("first"), + BeginList, + Scalar("a"), + End, + Key("second"), + BeginList, + BeginList, + Scalar("a"), + End, + End, + ) + .inOrder() + } + + @Test + fun `writeTo() - writes the same arguments again on a later call`() { + val nested = mapOf("k" to "v") + val source = hostArgumentSource(mapOf("nested" to nested)) + source.writeTo(RecordingArgumentSink()) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("nested"), BeginMap, Key("k"), Scalar("v"), End) + .inOrder() + } + + @Test + fun `writeTo() - writes a container again on a later call after an earlier call stopped inside it`() { + val failure = + DropArgumentsException(ArgumentDropReason.MAX_COUNT, DropArgumentsException.MAX_COUNT_WARNING) + val nested = mapOf("k" to "v") + val source = hostArgumentSource(mapOf("nested" to nested)) + assertFailsWith { + source.writeTo(RecordingArgumentSink(failOnKey = "k", keyFailure = failure)) + } + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("nested"), BeginMap, Key("k"), Scalar("v"), End) + .inOrder() + } + + // Scalars + + @Test + fun `writeTo() - passes null, Boolean, and Number values unchanged`() { + val bigDecimal = BigDecimal("1.25") + val source = + hostArgumentSource( + mapOf("null" to null, "boolean" to true, "nan" to Double.NaN, "bigDecimal" to bigDecimal), + ) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly(Scalar(null), Scalar(true), Scalar(Double.NaN), Scalar(bigDecimal)) + .inOrder() + } + + @Test + fun `writeTo() - passes CharSequence and Char values unchanged`() { + val text = StringBuilder("hello") + val source = hostArgumentSource(mapOf("text" to text, "char" to 'x')) + + source.writeTo(sink) + + val scalars = sink.events.filterIsInstance() + assertThat(scalars[0].value).isSameInstanceAs(text) + assertThat(scalars[1].value).isEqualTo('x') + } + + @Test + fun `writeTo() - writes enums by name`() { + val source = hostArgumentSource(mapOf("mode" to PrivacyMode.PRIVATE)) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("mode"), Scalar("PRIVATE")).inOrder() + } + + @Test + fun `writeTo() - doesn't report supported values as unsupported`() { + val source = + hostArgumentSource( + mapOf( + "string" to "a", + "char" to 'b', + "number" to 1, + "boolean" to false, + "null" to null, + "enum" to PrivacyMode.PUBLIC, + "list" to listOf(1), + "map" to mapOf("k" to "v"), + "array" to intArrayOf(1), + ), + ) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).isEmpty() + } + + // Unsupported values + + @Test + fun `writeTo() - writes an unsupported value by toString`() { + val source = hostArgumentSource(mapOf("opaque" to OpaqueValue())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("opaque"), Scalar("opaque-value")).inOrder() + } + + @Test + fun `writeTo() - reports an unsupported value with its simple type name`() { + val source = hostArgumentSource(mapOf("opaque" to OpaqueValue())) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).containsExactly("OpaqueValue") + } + + @Test + fun `writeTo() - writes an Iterable that isn't a Collection as an unsupported value`() { + val source = hostArgumentSource(mapOf("iterable" to OpaqueIterable())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("iterable"), Scalar("opaque-iterable")).inOrder() + assertThat(unsupportedTypeNames).containsExactly("OpaqueIterable") + } + + @Test + fun `writeTo() - writes a Sequence as an unsupported value`() { + val source = hostArgumentSource(mapOf("sequence" to OpaqueSequence())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("sequence"), Scalar("opaque-sequence")).inOrder() + assertThat(unsupportedTypeNames).containsExactly("OpaqueSequence") + } + + @Test + fun `writeTo() - reports an unsupported value of an anonymous type with a null type name`() { + val anonymous = + object { + override fun toString(): String = "anonymous" + } + val source = hostArgumentSource(mapOf("anonymous" to anonymous)) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).containsExactly(null) + } + + @Test + fun `writeTo() - doesn't call an unsupported value's toString() or report it until the sink computes the value`() { + val value = CountingValue() + val sink = RecordingArgumentSink(computesScalars = false) + val source = hostArgumentSource(mapOf("counting" to value)) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("counting"), UncomputedScalar).inOrder() + assertThat(value.toStringCalls).isEqualTo(0) + assertThat(unsupportedTypeNames).isEmpty() + } + + // Failures + + @Test + fun `writeTo() - stops writing when the sink throws`() { + val failure = + DropArgumentsException(ArgumentDropReason.MAX_COUNT, DropArgumentsException.MAX_COUNT_WARNING) + val sink = RecordingArgumentSink(failOnKey = "second", keyFailure = failure) + val source = hostArgumentSource(mapOf("first" to 1, "second" to 2, "third" to 3)) + + val thrown = assertFailsWith { source.writeTo(sink) } + + assertThat(thrown).isSameInstanceAs(failure) + assertThat(sink.events).containsExactly(Key("first"), Scalar(1)).inOrder() + } + + private fun hostArgumentSource(arguments: Map<*, *>): HostArgumentSource = + HostArgumentSource(arguments) { unsupportedTypeNames += it } + + internal sealed interface Event { + data class Key(val name: String) : Event + + data class Scalar(val value: Any?) : Event + + object BeginMap : Event { + override fun toString(): String = "BeginMap" + } + + object BeginList : Event { + override fun toString(): String = "BeginList" + } + + data class Reject(val reason: ArgumentDropReason) : Event + + object End : Event { + override fun toString(): String = "End" + } + + /** A computed scalar the sink declined to compute. */ + object UncomputedScalar : Event { + override fun toString(): String = "UncomputedScalar" + } + } + + /** + * Records every call as an [Event], and throws [keyFailure] when asked for the key [failOnKey]. + * With `computesScalars = false`, records each computed scalar without computing it. + */ + private class RecordingArgumentSink( + private val failOnKey: String? = null, + private val keyFailure: RuntimeException? = null, + private val computesScalars: Boolean = true, + ) : ArgumentSink { + + val events = mutableListOf() + + override fun checkNotDropped() = Unit + + override fun beginMap() { + events += BeginMap + } + + override fun beginList() { + events += BeginList + } + + override fun key(name: String, describeDuplicate: () -> String) { + if (name == failOnKey && keyFailure != null) throw keyFailure + events += Key(name) + } + + override fun scalar(value: Any?) { + events += Scalar(value) + } + + override fun computedScalar(compute: () -> Any?) { + if (computesScalars) scalar(compute()) else events += UncomputedScalar + } + + override fun end() { + events += End + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing { + events += Reject(reason) + throw DropArgumentsException(reason, warning) + } + + override fun checkComplete() = Unit + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt new file mode 100644 index 00000000000..5f0454d1273 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt @@ -0,0 +1,779 @@ +package io.sentry.compose.navigation3.internal.common + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.util.UrlUtils +import kotlin.test.assertFailsWith +import org.junit.Test + +class TreeArgumentSinkTest { + + private val sink = TreeArgumentSink(ArgumentBudget()) + + private val characterLimitDrop = + ArgumentDropReason.CHARACTER_LIMIT to DropArgumentsException.MAX_CHARACTER_WARNING + private val duplicateKeyDrop = + ArgumentDropReason.DUPLICATE_KEY to DropArgumentsException.DUPLICATE_KEY_WARNING + private val maxCountDrop = + ArgumentDropReason.MAX_COUNT to DropArgumentsException.MAX_COUNT_WARNING + private val structureDrop = + ArgumentDropReason.INVALID_STRUCTURE to DropArgumentsException.STRUCTURE_WARNING + + private val DropArgumentsException.signal: Pair + get() = reason to warning + + private companion object { + const val SUBSTITUTE = UrlUtils.SENSITIVE_DATA_SUBSTITUTE + } + + // Building the tree + + @Test + fun `argumentsOrThrow() - returns the arguments written as maps and lists`() { + sink.key("id") + sink.scalar("123") + sink.key("filters") + sink.beginMap() + sink.key("tags") + sink.beginList() + sink.scalar("a") + sink.scalar(true) + sink.end() + sink.key("limit") + sink.scalar(null) + sink.end() + sink.key("page") + sink.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf( + "id" to "123", + "filters" to mapOf("tags" to listOf("a", true), "limit" to null), + "page" to 2, + ), + ) + } + + @Test + fun `argumentsOrThrow() - keeps arguments in the order they were written`() { + sink.key("b") + sink.scalar(1) + sink.key("a") + sink.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments.keys).containsExactly("b", "a").inOrder() + } + + @Test + fun `argumentsOrThrow() - returns an empty map when nothing was written`() { + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEmpty() + } + + // Scalars + + @Test + fun `scalar() - records CharSequence and Char values as Strings`() { + sink.key("text") + sink.scalar(StringBuilder("hello")) + sink.key("char") + sink.scalar('x') + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("text" to "hello", "char" to "x")) + assertThat(arguments["text"]).isInstanceOf(String::class.java) + assertThat(arguments["char"]).isInstanceOf(String::class.java) + } + + @Test + fun `scalar() - spends one value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + limitedSink.key("id") + + val drop = assertFailsWith { limitedSink.scalar(1) } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `scalar() - spends characters for a CharSequence value`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar(StringBuilder("ab")) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - spends characters for a Char value`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(0)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar('x') } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - records non-finite Double and Float values as strings`() { + sink.key("double") + sink.scalar(Double.NEGATIVE_INFINITY) + sink.key("float") + sink.scalar(Float.NaN) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("double" to "-Infinity", "float" to "NaN")) + } + + @Test + fun `scalar() - spends characters for a non-finite number string`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining("NaN".length - 1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar(Double.NaN) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - doesn't spend characters for a finite number`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(0)) + limitedSink.key("") + + limitedSink.scalar(123.456) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to 123.456)) + } + + @Test + fun `scalar() - doesn't spend characters for a boolean or null`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(0)) + limitedSink.key("") + limitedSink.beginList() + + limitedSink.scalar(true) + limitedSink.scalar(null) + limitedSink.end() + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to listOf(true, null))) + } + + @Test + fun `scalar() - throws ArgumentProtocolException for an unsupported type`() { + sink.key("opaque") + + assertFailsWith { sink.scalar(Any()) } + } + + @Test + fun `scalar() - throws ArgumentProtocolException for a map value written without a key`() { + assertFailsWith { sink.scalar(1) } + } + + // Incomplete writes + + @Test + fun `key() - throws ArgumentProtocolException in a list`() { + sink.key("list") + sink.beginList() + + assertFailsWith { sink.key("id") } + } + + @Test + fun `key() - throws ArgumentProtocolException when the previous key has no value`() { + sink.key("first") + + assertFailsWith { sink.key("second") } + } + + @Test + fun `argumentsOrThrow() - throws ArgumentProtocolException while a map or list is open`() { + sink.key("list") + sink.beginList() + sink.scalar(1) + + assertFailsWith { sink.argumentsOrThrow() } + } + + @Test + fun `argumentsOrThrow() - throws ArgumentProtocolException when the last key has no value`() { + sink.key("id") + + assertFailsWith { sink.argumentsOrThrow() } + } + + // Computed scalars + + @Test + fun `computedScalar() - writes the computed value as scalar() would`() { + sink.key("text") + sink.computedScalar { StringBuilder("hello") } + sink.key("page") + sink.computedScalar { 2 } + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("text" to "hello", "page" to 2)) + assertThat(arguments["text"]).isInstanceOf(String::class.java) + } + + @Test + fun `computedScalar() - spends characters for computed text`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.computedScalar { "ab" } } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `computedScalar() - drops the arguments without computing the value when the value budget is spent`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + limitedSink.key("a") + var computations = 0 + + val drop = + assertFailsWith { limitedSink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - drops the arguments for invalid structure without computing a value nested too deeply`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + var computations = 0 + + val drop = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(structureDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - rethrows an earlier drop without computing the value`() { + val drop = exhaustValues() + var computations = 0 + + val thrown = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(thrown).isSameInstanceAs(drop) + assertThat(computations).isEqualTo(0) + } + + // Keys + + @Test + fun `key() - spends the characters of the key`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(1)) + + val drop = assertFailsWith { limitedSink.key("ab") } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `key() - doesn't spend a value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + + limitedSink.key("a") + + val drop = assertFailsWith { limitedSink.scalar(1) } + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + // Duplicate keys + + @Test + fun `key() - drops the arguments for a key already in its map before its value is written`() { + sink.key("id") + sink.scalar(1) + + val drop = assertFailsWith { sink.key("id") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `key() - drops the arguments for a key already in its map with the warning describeDuplicate returns`() { + sink.key("id") + sink.scalar(1) + + val drop = assertFailsWith { sink.key("id") { "described" } } + + assertThat(drop.signal).isEqualTo(ArgumentDropReason.DUPLICATE_KEY to "described") + } + + @Test + fun `key() - doesn't describe a key that isn't already in its map`() { + sink.key("id") { error("described a unique key") } + + sink.scalar(1) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to 1)) + } + + @Test + fun `key() - drops the arguments for a duplicate key, not the value limit, with no values left`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(1)) + limitedSink.key("id") + limitedSink.scalar(1) + + val drop = assertFailsWith { limitedSink.key("id") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `the same key in a nested map and its parent map is written to both`() { + sink.key("id") + sink.beginMap() + sink.key("id") + sink.scalar(1) + sink.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("id" to mapOf("id" to 1))) + } + + @Test + fun `the same key in sibling maps is written to both`() { + sink.key("first") + sink.beginMap() + sink.key("id") + sink.scalar(1) + sink.end() + sink.key("second") + sink.beginMap() + sink.key("id") + sink.scalar(2) + sink.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo(mapOf("first" to mapOf("id" to 1), "second" to mapOf("id" to 2))) + } + + @Test + fun `key() - drops the arguments for a duplicate substitute key, even when both values are the substitute`() { + sink.key(SUBSTITUTE) + sink.scalar(SUBSTITUTE) + + val drop = assertFailsWith { sink.key(SUBSTITUTE) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `another key holding the substitute drops the arguments for a duplicate key`() { + sink.key("token") + sink.scalar(SUBSTITUTE) + + val drop = assertFailsWith { sink.key("token") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + // Containers + + @Test + fun `beginMap() - spends one value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + limitedSink.key("map") + + val drop = assertFailsWith { limitedSink.beginMap() } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `beginList() - spends one value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + limitedSink.key("list") + + val drop = assertFailsWith { limitedSink.beginList() } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `the root map doesn't spend a value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(1)) + limitedSink.key("id") + + limitedSink.scalar(1) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("id" to 1)) + } + + @Test + fun `end() - throws ArgumentProtocolException when no map or list is open`() { + assertFailsWith { sink.end() } + } + + @Test + fun `end() - throws ArgumentProtocolException after every opened map and list was ended`() { + sink.key("list") + sink.beginList() + sink.end() + + assertFailsWith { sink.end() } + } + + // Depth + + @Test + fun `a scalar at the maximum depth is written`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.scalar("leaf") + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("nested" to nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf"))) + } + + @Test + fun `a scalar past the maximum depth drops the arguments for invalid structure`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + + val drop = assertFailsWith { sink.scalar("leaf") } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container at the maximum depth is written`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.beginMap() + sink.end() + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("nested" to nestedInLists(MAX_ARGUMENT_DEPTH - 1, emptyMap()))) + } + + @Test + fun `a container past the maximum depth drops the arguments for invalid structure`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + + val drop = assertFailsWith { sink.beginMap() } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `depth counts only containers that are still open`() { + sink.key("closed") + openLists(MAX_ARGUMENT_DEPTH - 1) + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.scalar("leaf") + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } + + assertThat(sink.argumentsOrThrow()["nested"]) + .isEqualTo(nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf")) + } + + // Sticky failure + + @Test + fun `every write after the arguments are dropped rethrows the same DropArgumentsException`() { + val drop = exhaustValues() + + assertThat(assertFailsWith { sink.key("a") }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.scalar(1) }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginMap() }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginList() }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.end() }).isSameInstanceAs(drop) + } + + @Test + fun `argumentsOrThrow() - rethrows the DropArgumentsException a source caught and swallowed`() { + val caught = exhaustValues() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(caught) + } + + // Recorded drop + + @Test + fun `checkNotDropped() - doesn't throw while every write is within the limits`() { + sink.key("id") + sink.scalar("123") + + sink.checkNotDropped() + } + + @Test + fun `checkNotDropped() - throws the DropArgumentsException thrown by the write that broke a limit`() { + val drop = exhaustValues() + + assertThat(recordedDrop()).isSameInstanceAs(drop) + } + + @Test + fun `checkNotDropped() - throws the first DropArgumentsException after later writes throw`() { + val drop = exhaustValues() + assertFailsWith { sink.key("after") } + assertFailsWith { sink.scalar("x".repeat(MAX_ARGUMENT_CHARACTERS)) } + + val recorded = recordedDrop() + + assertThat(recorded).isSameInstanceAs(drop) + } + + @Test + fun `checkNotDropped() - doesn't throw after a write throws for an unsupported value`() { + sink.key("opaque") + assertFailsWith { sink.scalar(Any()) } + + sink.checkNotDropped() + } + + // Limits a source enforces itself + + @Test + fun `reject() - throws DropArgumentsException with the given reason and warning`() { + val drop = rejectStructure() + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `reject() - records the DropArgumentsException it throws as the failure`() { + val drop = rejectStructure() + + assertThat(recordedDrop()).isSameInstanceAs(drop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArgumentsException when a write already broke a limit`() { + val writeDrop = exhaustValues() + + val drop = rejectStructure() + + assertThat(drop).isSameInstanceAs(writeDrop) + assertThat(recordedDrop()).isSameInstanceAs(writeDrop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArgumentsException when a limit was already rejected`() { + val firstDrop = rejectStructure() + + val drop = + assertFailsWith { + sink.reject(ArgumentDropReason.MAX_COUNT, DropArgumentsException.MAX_COUNT_WARNING) + } + + assertThat(drop).isSameInstanceAs(firstDrop) + assertThat(recordedDrop()).isSameInstanceAs(firstDrop) + } + + @Test + fun `every write after a rejected limit rethrows the rejected DropArgumentsException`() { + val drop = rejectStructure() + + assertThat(assertFailsWith { sink.key("a") }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.scalar(1) }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginMap() }).isSameInstanceAs(drop) + assertThat(recordedDrop()).isSameInstanceAs(drop) + } + + @Test + fun `argumentsOrThrow() - rethrows the rejected DropArgumentsException a source caught and swallowed`() { + sink.key("id") + sink.scalar("123") + val rejected = rejectStructure() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(rejected) + } + + // Running a source + + @Test + fun `write() - returns the arguments the source wrote`() { + val result = + sink.write( + source { + it.key("id") + it.scalar("123") + }, + ) + + assertThat(written(result)).isEqualTo(mapOf("id" to "123")) + } + + @Test + fun `write() - returns the drop the source threw`() { + val result = + sink.write( + source { + it.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArgumentsException.STRUCTURE_WARNING) + }, + ) + + assertThat(dropped(result).signal).isEqualTo(structureDrop) + } + + @Test + fun `write() - returns the first drop when the source catches it and throws another drop`() { + var caught: DropArgumentsException? = null + + val result = + sink.write( + source { + caught = + assertFailsWith { writeScalars(it, MAX_ARGUMENT_VALUES + 1) } + throw DropArgumentsException(ArgumentDropReason.MAX_COUNT, "replaced") + }, + ) + + assertThat(dropped(result)).isSameInstanceAs(caught) + } + + @Test + fun `write() - returns the first drop when the source catches it and throws something else`() { + var caught: DropArgumentsException? = null + + val result = + sink.write( + source { + caught = + assertFailsWith { writeScalars(it, MAX_ARGUMENT_VALUES + 1) } + throw IllegalArgumentException("replaced") + }, + ) + + assertThat(dropped(result)).isSameInstanceAs(caught) + } + + @Test + fun `write() - returns the first drop when the source catches it and returns`() { + var caught: DropArgumentsException? = null + + val result = + sink.write( + source { + caught = + assertFailsWith { writeScalars(it, MAX_ARGUMENT_VALUES + 1) } + }, + ) + + assertThat(dropped(result)).isSameInstanceAs(caught) + } + + @Test + fun `write() - returns the failure the source threw without breaking a limit`() { + val error = IllegalArgumentException("boom") + + val result = sink.write(source { throw error }) + + assertThat(failed(result)).isSameInstanceAs(error) + } + + @Test + fun `write() - returns a failure when the source leaves a map open`() { + val result = sink.write(source { it.beginMap() }) + + assertThat(failed(result)).isInstanceOf(ArgumentProtocolException::class.java) + } + + @Test + fun `write() - rethrows a fatal error the source threw`() { + val error = StackOverflowError() + + val thrown = assertFailsWith { sink.write(source { throw error }) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // DropArgumentsException + + @Test + fun `DropArgumentsException - has no stack trace`() { + val drop = exhaustValues() + + assertThat(drop.stackTrace).isEmpty() + } + + /** Returns the drop the sink recorded, which [ArgumentSink.checkNotDropped] throws. */ + private fun recordedDrop(): DropArgumentsException = + assertFailsWith { sink.checkNotDropped() } + + private fun source(write: (ArgumentSink) -> Unit): ArgumentSource = + object : ArgumentSource { + override fun writeTo(sink: ArgumentSink) = write(sink) + } + + private fun written(result: ArgumentWriteResult): Map { + assertThat(result).isInstanceOf(ArgumentWriteResult.Written::class.java) + return (result as ArgumentWriteResult.Written).arguments + } + + private fun dropped(result: ArgumentWriteResult): DropArgumentsException { + assertThat(result).isInstanceOf(ArgumentWriteResult.Dropped::class.java) + return (result as ArgumentWriteResult.Dropped).drop + } + + private fun failed(result: ArgumentWriteResult): Throwable { + assertThat(result).isInstanceOf(ArgumentWriteResult.Failed::class.java) + return (result as ArgumentWriteResult.Failed).cause + } + + /** Opens [count] nested lists, so the next value has a depth of `count + 1`. */ + private fun openLists(count: Int) { + repeat(count) { sink.beginList() } + } + + private fun writeScalars(target: ArgumentSink, count: Int) { + repeat(count) { + target.key("k$it") + target.scalar(it) + } + } + + /** Writes one value more than the value budget allows and returns the resulting drop. */ + private fun exhaustValues(): DropArgumentsException = + assertFailsWith { writeScalars(sink, count = MAX_ARGUMENT_VALUES + 1) } + + /** Rejects the entry for invalid structure, as a source would, and returns the resulting drop. */ + private fun rejectStructure(): DropArgumentsException = + assertFailsWith { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArgumentsException.STRUCTURE_WARNING) + } + + private fun nestedInLists(levels: Int, leaf: Any?): Any? { + var nested = leaf + repeat(levels) { nested = listOf(nested) } + return nested + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt index 8fd55c57caf..acbf841bb61 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt @@ -91,6 +91,8 @@ class NavDataContractTest { "max_character_limit_exceeded", ArgumentDropReason.DUPLICATE_KEY, "duplicate_key", + ArgumentDropReason.ENCODING_FAILED, + "encoding_failed", ArgumentDropReason.INVALID_STRUCTURE, "invalid_structure", ArgumentDropReason.MAX_COUNT, diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 3dc8ed74c4a..a7ee410a340 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -8011,6 +8011,7 @@ public abstract interface class io/sentry/util/HintUtils$SentryNullableConsumer public final class io/sentry/util/HttpUtils { public fun ()V + public static fun containsSensitiveDataKey (Ljava/lang/String;)Z public static fun containsSensitiveHeader (Ljava/lang/String;)Z public static fun filterHeaders (Ljava/util/Map;Lio/sentry/KeyValueCollectionBehavior;)Ljava/util/Map; public static fun filterQueryParams (Ljava/lang/String;Lio/sentry/KeyValueCollectionBehavior;)Ljava/lang/String; diff --git a/sentry/src/main/java/io/sentry/util/HttpUtils.java b/sentry/src/main/java/io/sentry/util/HttpUtils.java index 544cb18094e..4802d42760d 100644 --- a/sentry/src/main/java/io/sentry/util/HttpUtils.java +++ b/sentry/src/main/java/io/sentry/util/HttpUtils.java @@ -136,7 +136,11 @@ public static boolean containsSensitiveHeader(final @NotNull String header) { } } - static boolean containsSensitiveDataKey(final @NotNull String key) { + /** + * Returns whether {@code key} contains a term from the Data Collection spec's sensitive denylist, + * matched partially and case-insensitively. + */ + public static boolean containsSensitiveDataKey(final @NotNull String key) { final @NotNull String normalizedKey = key.toLowerCase(Locale.ROOT); for (final String term : SENSITIVE_DATA_KEYS) { if (normalizedKey.contains(term)) {