diff --git a/CHANGELOG.md b/CHANGELOG.md index f9851e542b4..a677f265758 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ ## Unreleased +### Features + +- Nav3: Add `BackStackEntryMapper.SerialName`, a convenience mapper that names back stack entries after their kotlinx.serialization serial names ([#6703](https://github.com/getsentry/sentry-java/pull/6703)) + ### Fixes - Profiling: No longer crash on API 35+ devices whose framework can't load `ProfilingManager`. Perfetto profiling is turned off on those devices instead ([#6742](https://github.com/getsentry/sentry-java/pull/6742)) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 4a4c2635bab..55fd256d054 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -70,6 +70,7 @@ kotlin-spring = { id = "org.jetbrains.kotlin.plugin.spring", version.ref = "kotl kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } buildconfig = { id = "com.github.gmazzo.buildconfig", version = "5.6.5" } dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } diff --git a/gradle/nav3.versions.toml b/gradle/nav3.versions.toml new file mode 100644 index 00000000000..1513888127a --- /dev/null +++ b/gradle/nav3.versions.toml @@ -0,0 +1,15 @@ +# Versions for sentry-android-navigation3's kotlinx.serialization compatibility checks, registered as +# the `nav3Libs` catalog. +# +# Kept apart from libs.versions.toml so that the Nav3 R8 check workflow can run on PRs that change +# them without also running on every unrelated dependency bump. + +[versions] +# The oldest kotlinx.serialization version sentry-android-navigation3 supports, which it compiles and +# tests against. Nav3 builds apply it explicitly rather than via version.ref to prevent Dependabot +# from modifying it. When updating, also update MIN_KOTLINX_SERIALIZATION_VERSION in +# KotlinxMapperDiagnostics (KotlinxBackStackEntryMapper.kt); a unit test fails if the two don't match. +kotlinxSerializationFloor = "1.7.3" + +[libraries] +kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core" } diff --git a/sentry-android-navigation3/README.md b/sentry-android-navigation3/README.md index 95bbbeb006b..2135233aefd 100644 --- a/sentry-android-navigation3/README.md +++ b/sentry-android-navigation3/README.md @@ -6,7 +6,7 @@ Use `SentryNavEffect` alongside your `NavDisplay` to record navigation transacti users move around your app. Configure the data you want captured via `SentryNavOptions`. 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`). +keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` mapper). 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 45f0482ed82..04c3349cd46 100644 --- a/sentry-android-navigation3/api/sentry-android-navigation3.api +++ b/sentry-android-navigation3/api/sentry-android-navigation3.api @@ -1,7 +1,12 @@ public abstract interface class io/sentry/compose/navigation3/BackStackEntryMapper { + public static final field Companion Lio/sentry/compose/navigation3/BackStackEntryMapper$Companion; public abstract fun map (Ljava/lang/Object;)Lio/sentry/compose/navigation3/SentryBackStackEntry; } +public final class io/sentry/compose/navigation3/BackStackEntryMapper$Companion { + public final fun getSerialName ()Lio/sentry/compose/navigation3/BackStackEntryMapper; +} + public final class io/sentry/compose/navigation3/BuildConfig { public static final field BUILD_TYPE Ljava/lang/String; public static final field DEBUG Z diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index 7a6cf51d181..86a2fa2beb4 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -7,6 +7,7 @@ plugins { alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.compose) alias(libs.plugins.gradle.versions) + alias(libs.plugins.kotlin.serialization) id("io.sentry.detekt") id("io.sentry.spotless") id("io.sentry.jdk-target") @@ -15,6 +16,8 @@ plugins { id("io.sentry.robolectric") } +val kotlinxSerializationFloor = nav3Libs.versions.kotlinxSerializationFloor.get() + android { compileSdk = libs.versions.compileSdk.get().toInt() namespace = "io.sentry.compose.navigation3" @@ -45,6 +48,8 @@ android { // AGP 9.5 can't create the Compose Preview task without it, which breaks any // build that creates every task, such as an LSP's Gradle import. isIncludeAndroidResources = true + // Lets tests check that MIN_KOTLINX_SERIALIZATION_VERSION matches the catalog's floor. + all { it.systemProperty("nav3.kotlinxSerializationFloor", kotlinxSerializationFloor) } } } @@ -72,12 +77,22 @@ android { kotlin { explicitApi() } +// Unit tests run against the kotlinx.serialization floor by default. CI also runs them against the +// latest version (-Pnav3TestKotlinxVersion=), as apps may ship a newer +// kotlinx.serialization dependency than sentry-android-navigation3 compiles against. +val testKotlinxVersion = + providers.gradleProperty("nav3TestKotlinxVersion").orNull ?: kotlinxSerializationFloor + dependencies { implementation(projects.sentry) compileOnly(libs.androidx.lifecycle.runtime.compose) compileOnly(libs.androidx.compose.runtime) compileOnly(libs.androidx.compose.ui) + // All Nav3 apps depend on kotlinx.serialization via navigation3-runtime. + compileOnly(nav3Libs.kotlinx.serialization.core) { + version { require(kotlinxSerializationFloor) } + } testImplementation(projects.sentryAndroidCore) testImplementation(projects.sentryTestSupport) @@ -88,6 +103,10 @@ dependencies { testImplementation(libs.androidx.viewpager2) testImplementation(libs.google.truth) testImplementation(libs.kotlin.test.junit) + testImplementation(nav3Libs.kotlinx.serialization.core) { + // Avoid using whatever version test deps happen to pull in transitively. + version { strictly(testKotlinxVersion) } + } testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) testImplementation(libs.roboelectric) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index b977c6fccc9..0ce6a4f534e 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 @@ -1,5 +1,6 @@ package io.sentry.compose.navigation3 +import io.sentry.compose.navigation3.internal.backstack.BuiltInBackStackEntryMappers import org.jetbrains.annotations.ApiStatus /** Info about a given back stack entry, suitable for display in Sentry. */ @@ -53,12 +54,16 @@ public class SentryBackStackEntry( /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * To be implemented by the host app. + * If you use kotlinx.serialization, see [SerialName] for convenient, out-of-the-box mappers. + * Otherwise, provide your own implementation. (Note: Custom implementations can always fall back to + * `SerialName` for any entries that don't have to be special-cased.) * * **Privacy / PII** * - * Values returned from [map] are ***not*** scrubbed by the Sentry SDK before being sent to Sentry. - * Only return names and arguments that are known to be safe or have been pre-scrubbed. + * Custom mappers are responsible for filtering their own arguments. + * + * Only return names and arguments that are known to be safe or have been pre-scrubbed. All + * arguments remain subject to size and structural limits. * * **Performance** * @@ -113,41 +118,76 @@ public class SentryBackStackEntry( * arguments are cyclic, too deeply nested, or too large, or contain a map with two keys that are * stringified the same way (e.g., `1` and `"1"`). If the SDK drops an entry's arguments, it adds a * `dropped_by_sentry` field and corresponding reason (e.g., `duplicate_key`) in the Sentry UI. - * - * **Using kotlinx.serialization** - * - * If your back stack contains `@Serializable` entry types, consider giving each entry an explicit - * `@SerialName` and using its `descriptor.serialName`. For performance reasons, don't serialize - * back stack keys in their entirety as `arguments` if they might be large, deeply nested, or - * contain PII or other sensitive information. - * - * For instance: - * ```kotlin - * @Serializable - * @SerialName("Home") - * data class Home(val userName: String) : NavKey - * - * @Serializable - * @SerialName("ProductDetail") - * data class ProductDetail(val userName: String, val productId: String) : NavKey - * - * ... - * - * val backStackItemMapper = BackStackEntryMapper { entry -> - * when (entry) { - * is Home -> SentryBackStackEntry(Home.serializer().descriptor.serialName) - * is ProductDetail -> SentryBackStackEntry( - * name = ProductDetail.serializer().descriptor.serialName, - * // Select a subset of diagnostic arguments when serialization is unsafe - * // or non-performant. - * arguments = mapOf("product_id" to entry.productId) - * ) - * ... - * } - * } - * ``` */ @ApiStatus.Experimental -public fun interface BackStackEntryMapper { +public fun interface BackStackEntryMapper { + public fun map(backStackEntry: T): SentryBackStackEntry? + + public companion object { + + /** + * A convenience [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). + * + * For instance, given: + * ``` + * @Serializable + * @SerialName("ProductDetail") + * data class ProductDetail( + * val userId: String, + * val productId: String + * ) : NavKey + * ``` + * + * when navigating to `ProductDetail(userId = "123abc", productId = "zyx987")`, this mapper + * would return `"ProductDetail"` as the destination's name, but would ***not*** return the + * destination's properties (`userId` and `productId`). + * + * **Name == SerialDescriptor.serialName** + * + * This mapper names each back stack entry after the entry's + * [`SerialDescriptor.serialName`][kotlinx.serialization.descriptors.SerialDescriptor.serialName], + * i.e.: + * + * - the entry's `@SerialName` if it has one; or else + * - the entry's fully qualified class name (e.g., "com.example.Home"). + * + * **Unknown names** + * + * This mapper returns `null` for an entry, which Sentry displays as `"/unknown"`, if: + * + * - the entry class isn't annotated with `@Serializable` itself, even if kotlinx.serialization + * can serialize it without the annotation (e.g., `String`, `List`, an unannotated enum, or a + * class marked with a custom `@MetaSerializable` annotation); + * + * - the entry class is generic (e.g., `SettingsScreen`), as its serializer needs type + * arguments that can't be recovered from the entry at runtime; or + * + * - looking up the entry's serializer fails, e.g., because a custom serializer throws, R8 + * removed what the lookup needs, or the app's kotlinx.serialization version is incompatible + * with this SDK. + * + * The first entry of each class that can't be named logs a warning explaining why, visible when + * the SDK's `debug` option is enabled. For fixes, see + * [Troubleshooting](https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers) + * in the Sentry Android Navigation docs. + * + * **Sharing names** + * + * Entries share a Sentry name whenever their serializers share a serial name. In particular: + * + * - All constants of an enum are named after the enum. A `@SerialName` on a constant does not + * change the destination name. + * + * - Classes that use the same custom serializer (`@Serializable(with = ...)`) are named after + * that serializer's descriptor, which ignores a `@SerialName` on the class. + * + * To tell such entries apart, define a custom [BackStackEntryMapper], e.g., one that names enum + * constants after [Enum.name]. + */ + @get:ApiStatus.Experimental + public val SerialName: BackStackEntryMapper + get() = BuiltInBackStackEntryMappers.serialName + } } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt index 0646c13ad90..9e5ff2d0946 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt @@ -33,9 +33,7 @@ import org.jetbrains.annotations.ApiStatus * // destination are attributed to the appropriate nav transaction. * SentryNavEffect( * backStack = navBackStack, - * backStackEntryMapper = { entry -> - * SentryBackStackEntry(entry.toName(), entry.extractArguments()) - * }, + * backStackEntryMapper = BackStackEntryMapper.SerialName, * options = SentryNavOptions(), * ) * diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt new file mode 100644 index 00000000000..f7cb4f05182 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt @@ -0,0 +1,421 @@ +package io.sentry.compose.navigation3.internal.backstack + +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.util.UrlUtils +import java.util.IdentityHashMap + +/** + * The core contract for the subsystem that converts properties of back stack entries into Sentry + * arguments. + * + * An [ArgumentSource] pushes information about back stack properties into this sink. Sink + * implementations are expected to materialize the provided info into a tree of Sentry arguments, + * where the tree has a bounded size and height. + * + * **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) + * via a `BackStackEntryMapper`. + * + * `ArgumentSink` and `ArgumentSource` create the seam that lets us support variable processing on + * the source side (e.g., a plain map supplied by the host app vs. arguments that write themselves) + * but uniform processing on the sink side (argument pruning, protecting against constraint + * violation, and tree materialization). + * + * Here are the moving parts: + * ```text + * ArgumentSource + * ┌────────────────────┐ + * │ HostArgumentSource │ + * │ (plain host map) │ + * └─────────┬──────────┘ + * ▼ + * ┌───────────────────────────────┐ + * │ ArgumentSink │ + * └───────────────────────────────┘ + * ▲ sole impl + * ┌───────────────┴───────────────┐ + * │ TreeArgumentWriter │ + * │ │ ┌────────────────┐ + * │ Enforce + materialize: │ spends ──▶│ ArgumentBudget │ + * │ • builds the argument tree │ └────────────────┘ + * │ • prevents constraint │ ┌────────────────┐ + * │ violation (e.g., cycles) │ throws ──▶│ DropArguments │ + * └───────────────────────────────┘ └────────────────┘ + * + * Note: BackStackConverter.ArgumentSanitizer owns the ArgumentBudget and + * selects the ArgumentSource based on what the host app provides. + * ``` + * + * Receives one back stack entry's arguments as a [source][ArgumentSource] produces them, enforcing + * the argument limits as it goes. + * + * Throws [DropArguments] when a write violates a constraint or [reject] is called. Every write + * thereafter will also throw. + */ +internal interface ArgumentSink { + + /** + * The first [DropArguments] thrown either by a write constraint violation or by a call to + * [reject]; `null` if neither has occurred. + * + * Preserves the original drop reason even if intervening code (e.g., a host app serializer) + * catches it and throws its own exception instead. + */ + val failure: DropArguments? + + /** + * Starts a map as the next value. [identity] is the object being written, if any, so that one + * that contains itself is rejected instead of written until a limit is reached. + * + * Call [end] when finished. + */ + fun beginMap(identity: Any? = null) + + /** + * Starts a list as the next value. [identity] is as for [beginMap]. + * + * Call [end] when finished. + */ + fun beginList(identity: Any? = null) + + /** + * Names the next value in the current map. If the map already has a value named [name], writing + * the next value throws [DropArguments], as recording only one of them would show Sentry a + * partial map as if it were complete. + */ + fun key(name: String) + + /** + * 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., how deeply serializers nest), and throws the resulting [DropArguments]. + * + * If a constraint was already violated, throws that instead. + */ + fun reject(reason: ArgumentDropReason, warning: String): Nothing +} + +/** + * Something that can write info about a back stack entry's properties to an [ArgumentSink]. + * + * Sources decide which data to expose and whether to filter sensitive values. The sink applies size + * and structural limits without performing sensitive-data filtering. + */ +internal interface ArgumentSource { + fun writeTo(sink: ArgumentSink) +} + +/** + * Materializes an argument tree for a single back stack entry and enforces argument constraints. + * Argument inputs are provided by an [ArgumentSource]. + * + * **Argument constraints** + * + * Rejects cycles, excessive nesting, duplicate keys, and writes that exceed the value or character + * limits in [budget]. Writes in violation of those limits throw [DropArguments], as does [reject] + * for a constraint the source enforces itself. Once thrown, subsequent writes and + * [argumentsOrThrow] rethrow that failure so a source can't accidentally return partial arguments. + * + * [budget] is shared across all back stack entries processed in one update, limiting their combined + * value and character counts. + * + * [rootIdentity] identifies the source object represented by this entry's root argument map, + * allowing references back to that object to be detected as cycles. + * + * **Key duplication** + * + * Duplicate keys are allowed only when both the key and the old and new values are + * [UrlUtils.SENSITIVE_DATA_SUBSTITUTE], since replacing one redacted value with another loses no + * information. + */ +@Suppress("TooManyFunctions") +internal class TreeArgumentWriter( + private val budget: ArgumentBudget, + rootIdentity: Any? = null, +) : ArgumentSink { + + private val root = LinkedHashMap() + + /** The open containers, innermost last, with the identity each was written from. */ + private val containers = ArrayList().apply { add(root) } + private val identities = ArrayList().apply { add(rootIdentity) } + private val activeIdentities = + IdentityHashMap().apply { rootIdentity?.let { put(it, Unit) } } + + private var pendingKey: String? = null + + override var failure: DropArguments? = null + private set + + override fun beginMap(identity: Any?) = guarded { begin(LinkedHashMap(), identity) } + + override fun beginList(identity: Any?) = guarded { begin(ArrayList(), identity) } + + override fun key(name: String) = guarded { pendingKey = budget.spendText(name) } + + override fun scalar(value: Any?) = writeScalar { value } + + override fun computedScalar(compute: () -> Any?) = writeScalar(compute) + + override fun end() = guarded { + check(containers.size > 1) { "end() without an open map or list." } + containers.removeAt(containers.lastIndex) + identities.removeAt(identities.lastIndex)?.let(activeIdentities::remove) + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing { + failure?.let { throw it } + throw DropArguments(reason, warning).also { failure = it } + } + + /** + * Returns the entry's arguments, or re-throws the [DropArguments] 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 { + failure?.let { throw it } + return root + } + + private fun begin(container: Any, identity: Any?) { + visitValue() + if (identity != null && activeIdentities.put(identity, Unit) != null) { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + add(container) + containers += container + identities += identity + } + + /** + * Enforces the depth limit, spends one value for the value about to be added, and rejects a key + * that's already taken, before the value is computed. + */ + private fun visitValue() { + // A value added while n containers are open has a depth of n. + if (containers.size > MAX_ARGUMENT_DEPTH) { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + budget.spendValue() + // A substitute key may still be written again with a substitute value, which add() decides + // once the value is known. + val key = pendingKey + val isKeyTaken = key != null && (containers.last() as? Map<*, *>)?.containsKey(key) == true + if (isKeyTaken && !key.isSubstitute()) { + throw DropArguments(ArgumentDropReason.DUPLICATE_KEY, DropArguments.DUPLICATE_KEY_WARNING) + } + } + + @Suppress("UNCHECKED_CAST") + private fun add(value: Any?) { + when (val parent = containers.last()) { + is ArrayList<*> -> (parent as ArrayList) += value + else -> { + val key = checkNotNull(pendingKey) { "A map value was written without a key." } + val map = parent as LinkedHashMap + val replacesSubstituteWithSubstitute = + key.isSubstitute() && map[key].isSubstitute() && value.isSubstitute() + if (map.containsKey(key) && !replacesSubstituteWithSubstitute) { + throw DropArguments(ArgumentDropReason.DUPLICATE_KEY, DropArguments.DUPLICATE_KEY_WARNING) + } + map[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, + is Char -> budget.spendText(value.toString()) + else -> + throw IllegalArgumentException("Unsupported scalar of type ${value.javaClass.name}.") + }, + ) + } + + private inline fun guarded(write: () -> Unit) { + failure?.let { throw it } + try { + write() + } catch (e: DropArguments) { + failure = e + throw e + } + } +} + +/** + * Writes a host app's argument map 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. + */ +internal class HostArgumentSource( + private val arguments: Map<*, *>, + private val onUnsupportedValue: (typeName: String?) -> Unit, +) : ArgumentSource { + + override fun writeTo(sink: ArgumentSink) { + writeEntries(arguments, sink) + } + + private fun writeEntries(map: Map<*, *>, sink: ArgumentSink) { + for ((key, value) in map) { + sink.key(key.toString()) + write(value, sink) + } + } + + private fun write(value: Any?, sink: ArgumentSink) { + val collection = value?.asCollectionOrNull() + when { + value is Map<*, *> -> { + sink.beginMap(identity = value) + writeEntries(value, sink) + sink.end() + } + collection != null -> { + sink.beginList(identity = value) + // Iterated without reading the collection's size, which the host app controls. + for (element in collection) { + write(element, sink) + } + sink.end() + } + // Computed only once the sink has checked the value fits, as it may run host app code. + else -> sink.computedScalar { scalarOf(value) } + } + } + + 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() + } + } +} + +/** 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 + } + +/** + * Control-flow signal to drop an entry's arguments. Overrides [fillInStackTrace] to skip + * stack-trace capture. + * + * [warning] is logged when the arguments are dropped, or no-ops if `null` (e.g., because the source + * logged its own). + */ +internal class DropArguments( + 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." + } +} + +/** + * The value and character budgets shared by the entries of one back stack update. Throws + * [DropArguments] when a value or text doesn't fit in what's left. + */ +internal class ArgumentBudget { + + private var remainingValues = MAX_ARGUMENT_VALUES + private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + + /** Spends one value. */ + fun spendValue() { + if (--remainingValues < 0) { + throw DropArguments(ArgumentDropReason.MAX_COUNT, DropArguments.MAX_COUNT_WARNING) + } + } + + /** Returns [text] after spending its characters. */ + fun spendText(text: String): String { + if (text.length > remainingCharacters) { + throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, DropArguments.MAX_CHARACTER_WARNING) + } + remainingCharacters -= text.length + return text + } +} + +private fun Any?.isSubstitute(): Boolean = this == UrlUtils.SENSITIVE_DATA_SUBSTITUTE + +/** 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/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index e15194da1c2..32b068c095b 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,13 +5,9 @@ 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.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME import io.sentry.util.ExceptionUtils -import java.util.IdentityHashMap /** * Converts the host app back stack into a list of [NormalizedSentryBackStackEntry]s. @@ -139,27 +135,37 @@ internal class BackStackConverter( ) /** - * Sanitizes a back stack entry's arguments and writes them in a serializable form. It bounds - * depth and total value count, and it rejects cyclic structures. + * Sanitizes a back stack entry's raw argument inputs and returns them in a + * [serializable form][SanitizedArguments.values]. * - * One instance is shared across every entry in a single [convert] call, so the value budget is - * enforced across the whole update. Once the budget is spent, the overflowing entry and every - * older entry are dropped, while newer (already-processed) entries are preserved. + * Internally, this class processes argument inputs returned by the [entryMapper] passed to the + * outer converter instance. Those inputs can come from built-in or custom + * [BackStackEntryMapper]s. + * + * Built-in mappers supply their own [ArgumentSource], while custom mappers typically supply an + * ordinary map. [HostArgumentSource] adapts ordinary maps to the [ArgumentSource] contract, so + * both paths can be handled by the same processing pipeline. */ internal class ArgumentSanitizer( private val logger: ILogger, private val warningState: WarningState, ) { - private val activeContainers = IdentityHashMap() - private var remainingValues = MAX_ARGUMENT_VALUES - private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + // One instance per sanitizer, so the budgets span every entry of a back stack update. + private val budget = ArgumentBudget() private var dropReason: ArgumentDropReason? = null /** - * Sanitizes one entry's arguments, or returns an empty map to drop them, either because the - * structure is cyclic or too deeply nested (this entry only), or because the shared per-update - * value budget is spent (this entry and every older one). + * Sanitizes one entry's raw argument inputs and returns the result. + * + * [SanitizedArguments.values] will be empty if [raw] is empty or if the arguments were dropped. + * Arguments can be dropped if: + * + * - a previously processed entry exceeded the shared value or character budget; + * - an argument constraint is violated; or + * - conversion fails. + * + * [SanitizedArguments.dropReason] will be non-null if and only if arguments are dropped. */ @Suppress("TooGenericExceptionCaught") fun sanitizeEntry(raw: Map): SanitizedArguments { @@ -167,161 +173,38 @@ internal class BackStackConverter( return SanitizedArguments(emptyMap(), reason) } + // Use the raw inputs' own source implementation when available; otherwise, provide them with + // an adapter. + val source = + raw as? ArgumentSource + ?: HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } + val sink = TreeArgumentWriter(budget, rootIdentity = raw) + + // A constraint violation the sink recorded takes precedence over whatever the source threw, + // as the source may have caught it and thrown something else, and it decides whether older + // entries keep their arguments. return try { - SanitizedArguments(sanitizeMap(raw, depth = 0)) - } catch (drop: DropSubtree) { - if (drop.reason.exhaustsUpdateBudget) { - dropReason = drop.reason - } - logger.log(WARNING, drop.warning) - SanitizedArguments(emptyMap(), drop.reason) + source.writeTo(sink) + SanitizedArguments(sink.argumentsOrThrow()) + } catch (drop: DropArguments) { + drop(sink.failure ?: drop) } 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) - } - } - - private fun sanitizeMap(value: Map<*, *>, depth: Int): Map { - enter(value) - try { - val sanitized = mutableMapOf() - for ((key, childValue) in value) { - val keyString = key.toString() - consumeCharacters(keyString.length) - if (sanitized.containsKey(keyString)) { - // Types only b/c key strings may contain host data. Collisions are rare, so we re-scan - // instead of tracking original keys for every map. - val otherKey = value.keys.firstOrNull { it !== key && it.toString() == keyString } - throw DropSubtree( - "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.", - ArgumentDropReason.DUPLICATE_KEY, - ) - } - sanitized[keyString] = sanitizeValue(childValue, depth + 1) - } - return sanitized - } finally { - exit(value) - } - } - - private fun sanitizeCollection(value: Collection<*>, depth: Int): List { - enter(value) - try { - // The value budget bounds allocation instead of the caller-provided collection size. - val sanitized = mutableListOf() - for (childValue in value) { - sanitized += sanitizeValue(childValue, depth + 1) - } - return sanitized - } finally { - exit(value) - } - } - - private fun sanitizeValue(value: Any?, depth: Int): Any? { - visit(depth) - val collection = value?.asSanitizableCollectionOrNull() - - return when { - value is Map<*, *> -> sanitizeMap(value, depth) - collection != null -> sanitizeCollection(collection, depth) - else -> sanitizeScalar(value) - } - } - - private fun sanitizeScalar(value: Any?): Any? = - when (value) { - null, - is Boolean -> value - is Number -> - if (value.isNonFinite()) { - value.toString().also { consumeCharacters(it.length) } - } else value - is String -> value.also { consumeCharacters(it.length) } - is CharSequence, - is Char -> value.toString().also { consumeCharacters(it.length) } - is Enum<*> -> value.name.also { consumeCharacters(it.length) } - else -> { - warningState.logUnsupportedValueWarning(value::class.simpleName, logger) - value.toString().also { consumeCharacters(it.length) } + sink.failure?.let { + return drop(it) } + logger.log(WARNING, DropArguments.STRUCTURE_WARNING, t) + SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) } - - private fun Any.asSanitizableCollectionOrNull(): 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 - } - - /** - * Records a visit to one value, enforcing the per-entry depth cap and the shared per-update - * value budget. Throws [DropSubtree] to abort the current subtree when either is exceeded. - */ - private fun visit(depth: Int) { - if (depth > MAX_ARGUMENT_DEPTH) { - throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE) - } - if (--remainingValues < 0) { - throw DropSubtree(MAX_COUNT_WARNING, ArgumentDropReason.MAX_COUNT) - } - } - - private fun consumeCharacters(count: Int) { - if (count > remainingCharacters) { - throw DropSubtree(MAX_CHARACTER_WARNING, ArgumentDropReason.CHARACTER_LIMIT) - } - remainingCharacters -= count } - private fun enter(container: Any) { - if (activeContainers.put(container, Unit) != null) { - throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE) + private fun drop(drop: DropArguments): SanitizedArguments { + if (drop.reason.exhaustsUpdateBudget) { + dropReason = drop.reason } - } - - private fun exit(container: Any) { - activeContainers.remove(container) - } - - /** - * Control-flow signal to abort sanitization of the current subtree. Internal to - * [ArgumentSanitizer]. - * - * [reason] distinguishes entry-local drops from update-wide budget exhaustion. Overrides - * [fillInStackTrace] to skip stack-trace capture. - */ - private class DropSubtree(val warning: String, val reason: ArgumentDropReason) : - 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." + drop.warning?.let { logger.log(WARNING, it) } + return SanitizedArguments(emptyMap(), drop.reason) } } @@ -451,7 +334,3 @@ internal enum class ArgumentDropReason( const val ARGUMENT_DROP_REASON_KEY = "dropped_by_sentry" } } - -/** 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 new file mode 100644 index 00000000000..eaa10605941 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -0,0 +1,98 @@ +package io.sentry.compose.navigation3.internal.backstack + +import androidx.annotation.VisibleForTesting +import io.sentry.ILogger +import io.sentry.ScopesAdapter +import io.sentry.SentryLevel.WARNING +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap + +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 a mapper can't be created. + * + * See [BackStackEntryMapper.SerialName] for more details. + */ + val serialName: BackStackEntryMapper by + lazy(LazyThreadSafetyMode.PUBLICATION) { + // PUBLICATION avoids holding a lock while mapper creation calls the app's logger. Racing + // threads may each create and probe a mapper and log warnings, and all but the first + // published instance would be discarded. + create(logger) { + KotlinxBackStackEntryMapper(logger = logger) + } + } + + private val logger: () -> ILogger = { ScopesAdapter.getInstance().options.logger } + + /** + * Returns the mapper created by [newKotlinxMapper], or an [UnavailableBackStackEntryMapper] if + * the mapper can't be linked or initialized. + */ + @VisibleForTesting + fun create( + logger: () -> ILogger, + newKotlinxMapper: () -> BackStackEntryMapper, + ): BackStackEntryMapper { + return try { + newKotlinxMapper() + } catch (e: LinkageError) { + // An incompatible kotlinx.serialization version can throw a LinkageError while the mapper is + // created, either because a class the mapper uses can't be linked or because the mapper's + // compatibility probe failed to look up names. We catch the error here so that every entry + // falls back to UNKNOWN_ENTRY_NAME instead of crashing the app. + // + // Construction runs no host app code, only kotlinx.serialization's and the SDK's, so this + // also catches an ExceptionInInitializerError from either. We fall back rather than crash, + // and log the error for diagnosis. + logger() + .log( + WARNING, + // The compiler inlines INCOMPATIBLE_KOTLINX_ADVICE, and it's use here doesn't access any + // kotlinx.serialization code. + "Nav3 built-in mapper creation failed. Using $UNKNOWN_ENTRY_NAME for all entries. See " + + "the attached error. $INCOMPATIBLE_KOTLINX_ADVICE", + e, + ) + UnavailableBackStackEntryMapper(logger) + } + } +} + +/** + * A fallback for when a built-in [BackStackEntryMapper] isn't supported by the host app. + * + * Maps every back stack entry to `null`, which Sentry records as [UNKNOWN_ENTRY_NAME]. Logs once + * per entry type. + */ +internal class UnavailableBackStackEntryMapper( + private val logger: () -> ILogger, +) : BackStackEntryMapper { + + private val loggedTypes = Collections.newSetFromMap(ConcurrentHashMap, Boolean>()) + + override fun map(backStackEntry: Any): SentryBackStackEntry? { + val type = backStackEntry.javaClass + + if (loggedTypes.add(type)) { + logger() + .log( + WARNING, + "Nav3 mapper unavailable for type %s. Using $UNKNOWN_ENTRY_NAME. Use a custom " + + "BackStackEntryMapper.", + type.name, + ) + } + + return null + } +} 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 new file mode 100644 index 00000000000..fef70e5bd0d --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -0,0 +1,282 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.ILogger +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.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.util.ExceptionUtils +import java.lang.reflect.InvocationTargetException +import java.util.concurrent.ConcurrentHashMap +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable + +/** Implementation of [BackStackEntryMapper.SerialName]. */ +internal class KotlinxBackStackEntryMapper( + /** + * 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`. + * + * May throw, as the lookup can run the app's serializer code for the first time. + */ + private val lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, + logger: () -> ILogger, + probe: KotlinxCompatibilityProbe = KotlinxCompatibilityProbe, +) : BackStackEntryMapper { + + // Resolved here, rather than on the first map() call, so that if kotlinx.serialization is + // missing, creating this mapper fails and BuiltInBackStackEntryMappers falls back to + // UnavailableBackStackEntryMapper. + private val serializableAnnotation: Class = Serializable::class.java + + // 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. + private val types = ConcurrentHashMap, CachedType>() + + private val diagnostics = KotlinxMapperDiagnostics(logger) + + init { + // Check name-lookup support during construction so an incompatible kotlinx.serialization + // version triggers the use of UnavailableBackStackEntryMapper. Later LinkageErrors likely come + // from the entry's own type and are handled per type. + probe + .nameLookupLinkageError { error -> + diagnostics.inconclusiveProbe(NAME_LOOKUP_CAPABILITY, error) + } + ?.let { throw it } + } + + 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. + val type = (backStackEntry as? Enum<*>)?.declaringJavaClass ?: backStackEntry.javaClass + val cached = cachedType(type) + val name = cached.name ?: return null + + return SentryBackStackEntry(name) + } + + private fun cachedType(type: Class<*>): CachedType = + // getOrPut may look up a type more than once if threads race on its first entry. That can cause + // a failed lookup to be logged more than once, but only one result will ever be cached. + types.getOrPut(type) { lookUp(type) } + + /** + * Looks up [type]'s serializer and name. Logs if it can't be named. + * + * Never throws for a non-fatal error. Instead, a lookup that fails returns [UNRESOLVED], which + * [cachedType] caches, so each type's failure is queried and logged only once. + */ + @OptIn(ExperimentalSerializationApi::class) + private fun lookUp(type: Class<*>): CachedType { + // Checked before the lookup, which would otherwise return serializers for types that aren't + // @Serializable. + if (!isMarkedSerializable(type)) { + return UNRESOLVED + } + + // Serializer lookup and descriptor access may run host app code. Failures affect only this + // type. + val lookup = lookUpSerializerCatching(type) + val serializer = lookup.serializer + var error = lookup.error + + val name = + try { + serializer?.descriptor?.let { descriptor -> + descriptor.serialName + } + } catch (e: LinkageError) { + // Treat descriptor linkage errors as type-specific, including incompatibilities caused by a + // serializer compiled against another kotlinx.serialization version. + error = e + null + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Custom descriptors may throw anything. Catch broadly to log once and cache the type as + // unresolved, avoiding repeated lookups. Entries use UNKNOWN_ENTRY_NAME. + ExceptionUtils.rethrowIfFatal(t) + error = t + null + } + + if (name == null) { + diagnostics.unresolved(type, error) + } + return if (name == null) UNRESOLVED else CachedType(name) + } + + /** + * Whether [type] is annotated with `@Serializable`. Logs why it can't be named if the annotation + * is absent or can't be read. + * + * We only name types the host app marks as `@Serializable`. kotlinx.serialization provides + * serializers for built-in types (e.g. String, Int) and enums, but their serial names would be + * misleading ("kotlin.String") or derived from an obfuscated class name. + */ + private fun isMarkedSerializable(type: Class<*>): Boolean = + try { + type.isAnnotationPresent(serializableAnnotation).also { isMarked -> + if (!isMarked) { + diagnostics.notSerializable(type) + } + } + } catch (e: LinkageError) { + // As for the serializer lookup, a LinkageError from reading this type's annotations only + // fails this type. + diagnostics.unresolved(type, e) + false + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Catch broadly because annotation parsing has undocumented failure modes. Cache failures as + // unresolved so the type records UNKNOWN_ENTRY_NAME and logs once, rather than throwing from + // map() and retrying on every navigation. + ExceptionUtils.rethrowIfFatal(t) + diagnostics.unresolved(type, t) + false + } + + /** + * Looks up [type]'s serializer, returning the error that made it fail, if any, instead of + * throwing it. + */ + private fun lookUpSerializerCatching(type: Class<*>): SerializerLookup = + try { + SerializerLookup(lookUpSerializer(type), error = null) + } catch (e: InvocationTargetException) { + // kotlinx.serialization (or our fallback for private objects) calls the type's + // generated serializer() method reflectively, and it threw. For instance, a custom + // serializer object whose initializer throws arrives here with an + // ExceptionInInitializerError as its cause. Only this type is affected. + val cause = e.cause ?: e + // Reflection wraps everything the method throws, fatal errors included, so we apply the + // SDK's fatal-error check to the cause. A LinkageError cause (e.g., that + // ExceptionInInitializerError) only fails this type, so it's exempt. + if (cause !is LinkageError) { + ExceptionUtils.rethrowIfFatal(cause) + } + SerializerLookup(serializer = null, error = cause) + } catch (e: ReflectiveOperationException) { + // Any other reflective failure is specific to this type's serializer members. + SerializerLookup(serializer = null, error = e) + } catch (e: LinkageError) { + // A LinkageError, which the SDK otherwise rethrows as fatal, only fails this type. If the + // app's kotlinx.serialization version couldn't support name lookups at all, the probe that + // ran when this mapper was created would most likely have failed. So the error most likely + // comes from linking or initializing a class this type's serializer needs (e.g., a + // NoSuchMethodError from a serializer compiled against another version, or a + // NoClassDefFoundError for a class that failed to initialize earlier). + SerializerLookup(serializer = null, error = e) + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because the lookup reflects over the app's classes, and the reflection and + // annotation APIs it uses can throw unchecked exceptions of their own (e.g., a + // TypeNotPresentException when R8 removed the serializer a @Serializable(with = ...) + // names). Without this catch, the exception would escape map() uncached and the lookup + // would be repeated on every navigation. Instead, the type is cached as unresolved and + // recorded as UNKNOWN_ENTRY_NAME, with the error logged once. + ExceptionUtils.rethrowIfFatal(t) + SerializerLookup(serializer = null, error = t) + } + + /** A type's serial name, or `null` if the lookup failed. */ + private class CachedType( + val name: String?, + ) + + /** A type's serializer, or the error that made looking it up fail, if any. */ + private class SerializerLookup(val serializer: KSerializer<*>?, val error: Throwable?) + + private companion object { + private const val NAME_LOOKUP_CAPABILITY = "name lookups" + private val UNRESOLVED = CachedType(name = null) + } +} + +/** + * The warnings [KotlinxBackStackEntryMapper] logs when it can't name a back stack entry. + * + * Only decides what's logged, and how often. Whether a type is looked up or encoded again is up to + * the mapper. + */ +internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { + + /** Logs that entries of [type] can't be named because the type isn't `@Serializable`. */ + fun notSerializable(type: Class<*>) { + logger() + .log( + WARNING, + "Nav3 can't name entries of type %s because the type is not @Serializable. Using " + + "$UNKNOWN_ENTRY_NAME. Add @Serializable or use a custom BackStackEntryMapper.", + type.name, + ) + } + + /** + * Logs that the probe couldn't verify support for [capability], due to [error] or a missing probe + * serializer if the error is `null`. The mapper handles subsequent failures per type. + */ + fun inconclusiveProbe(capability: String, error: Throwable?) { + // DEBUG b/c an inconclusive probe doesn't affect what's recorded. + logger() + .log( + DEBUG, + error, + "Nav3 couldn't verify kotlinx.serialization support for %s because %s. Handling " + + "failures per entry type.", + capability, + if (error != null) { + "the compatibility probe threw (see the attached error)" + } else { + "a probe serializer wasn't found" + }, + ) + } + + /** + * 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. + */ + fun unresolved(type: Class<*>, error: Throwable?) { + val reason = + if (error != null) { + "reading its annotations, serializer, or descriptor failed" + } else { + "no serializer was found (the type may be generic or require R8 keep rules)" + } + val advice = + if (error is LinkageError) { + // The probe can miss an incompatible version, which then fails every type one at a time. + "See the attached error. If all types fail, kotlinx.serialization may be incompatible. " + + INCOMPATIBLE_KOTLINX_ADVICE + } else if (error != null) { + "See the attached error or use a custom BackStackEntryMapper." + } else { + "See BackStackEntryMapper.SerialName's documentation or use a custom BackStackEntryMapper." + } + logger() + .log( + WARNING, + error, + "Nav3 can't name entries of type %s because %s. Using $UNKNOWN_ENTRY_NAME. $advice", + type.name, + reason, + ) + } + + companion object { + + /** + * The oldest kotlinx.serialization version [KotlinxBackStackEntryMapper] supports. + * + * Must match `kotlinxSerializationFloor` in `gradle/nav3.versions.toml`. + */ + const val MIN_KOTLINX_SERIALIZATION_VERSION: String = "1.7.3" + + const val INCOMPATIBLE_KOTLINX_ADVICE: String = + "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + + "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + + "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + + "BackStackEntryMapper as a workaround." + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt new file mode 100644 index 00000000000..afc4bda12b4 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt @@ -0,0 +1,116 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.util.ExceptionUtils +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.Serializable + +/** + * Checks whether the app's kotlinx.serialization version successfully links against the APIs used + * by [KotlinxBackStackEntryMapper]. It does so via two built-in probe types ([ProbeClass] and + * [ProbeObject]). + * + * **Disambiguating serializer errors from library incompatibility** + * + * Without a check like this, `KotlinxBackStackEntryMapper` would have to infer an incompatible + * kotlinx.serialization version from [LinkageError]s thrown while handling the host app's own back + * stack entry types. But such errors can also come from the host app's serializer code, and should + * therefore only fail for the entry types that can't be deserialized. `ProbeClass` and + * `ProbeObject` don't execute any host app code, so a `LinkageError` while handling them means the + * app's kotlinx.serialization version is incompatible. + * + * Note: Only a `LinkageError` is conclusive. Any other failure, or a probe type whose serializer + * can't be found, leaves the check inconclusive: it's reported to the caller's `onInconclusive` and + * otherwise ignored, as a real type that hits the same failure is handled and logged on its own. + */ +internal interface KotlinxCompatibilityProbe { + + /** + * Verifies [KotlinxBackStackEntryMapper]'s serializer and name lookups with [ProbeClass] and + * [ProbeObject]. + * + * Returns a [LinkageError] if those lookups can't link against the host app's + * kotlinx.serialization version, or `null` if they succeed or the check is inconclusive. + * + * Calls [onInconclusive] for each inconclusive result, passing the cause or `null` if a probe + * type's serializer is unavailable. + */ + fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? + + /** Probes the app's kotlinx.serialization version using [ProbeClass] and [ProbeObject]. */ + companion object : KotlinxCompatibilityProbe { + + override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? { + var isSerializerMissing = false + + val error = + probe(onInconclusive) { + val descriptors = + listOf(ProbeClass::class.java, ProbeObject::class.java).map { type -> + reflectiveSerializerOrNull(type)?.descriptor + } + for (descriptor in descriptors.filterNotNull()) { + descriptor.serialName + descriptor.elementsCount + descriptor.kind + } + isSerializerMissing = null in descriptors + } + + // Call outside probe() so an exception from onInconclusive isn't caught and reported back to + // the same callback. If a serializer is missing, the remaining lookup steps cannot be checked + // for that type. + if (isSerializerMissing) { + onInconclusive(null) + } + return error + } + + /** + * Runs [check], returning any [LinkageError] and rethrowing fatal errors. Returns `null` if the + * check succeeds or is inconclusive. + * + * Reports other errors to [onInconclusive], passing the cause. + */ + private inline fun probe( + onInconclusive: (Throwable) -> Unit, + check: () -> Unit, + ): LinkageError? = + try { + check() + null + } catch (e: LinkageError) { + e + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because the app's kotlinx.serialization version may throw anything. Only + // LinkageError confirms incompatibility. Other non-fatal failures are inconclusive. + // Failures for actual back stack types are handled and logged per type. + ExceptionUtils.rethrowIfFatal(t) + onInconclusive(t) + null + } + + /** + * A known serializable type used to test whether the app's kotlinx.serialization version + * supports serializer lookup and property encoding. Its scalar, list, and map properties + * exercise common encoding paths without running host app code. + * + * Internal visibility lets the probe look up its serializer the same way + * [KotlinxBackStackEntryMapper] looks up serializers for the host app's public back stack entry + * types. + */ + @Serializable + internal data class ProbeClass( + val name: String = "probe", + val values: List = listOf(1), + val counts: Map = mapOf("count" to 1), + ) + + /** + * A known serializable object used to test serializer lookup for the host app's object-based + * back stack entries. This lookup reads the object's singleton instance. + */ + @Serializable internal object ProbeObject + } +} 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..2db1eab44c2 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt @@ -0,0 +1,456 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.ArgumentSink +import io.sentry.compose.navigation3.internal.backstack.DropArguments +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.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 a `@Serializable` back stack entry's properties 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 [DropArguments], 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. + * + * [ValueEncoder.encodeInline] also checks value classes' underlying property names, which aren't + * written as keys. [SensitiveKeyFilter] checks every output key as a safeguard against missed + * encoder checks. + * + * 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 [DropArguments] when an argument + * limit is exceeded. + * + * Limit failures, including [MAX_SERIALIZER_NESTING], are recorded in [ArgumentSink.failure]. A + * serializer can catch [DropArguments] and then throw a different exception or return normally. + * Callers must check [ArgumentSink.failure] to determine whether to drop the arguments. + */ + fun encode(serializer: KSerializer, value: Any, sink: ArgumentSink) { + val filteredSink = SensitiveKeyFilter(sink) + RootEncoder(filteredSink, SerializerNesting(filteredSink)) + .encodeSerializableValue(serializer, value) + } + + /** Encodes a single value and writes it to [sink]. Structures are delegated to child encoders. */ + private open class ValueEncoder( + protected val sink: ArgumentSink, + 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: ArgumentSink, 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: ArgumentSink, + nesting: SerializerNesting, + private val isRoot: Boolean = false, + ) : ValueEncoder(sink, nesting) { + + override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean { + val name = descriptor.getElementName(index) + sink.key(name) + if (isSensitive(name)) { + // 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: ArgumentSink, 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. + */ + private class MapEncoder( + sink: ArgumentSink, + nesting: SerializerNesting, + private val isRoot: Boolean = false, + ) : ValueEncoder(sink, nesting) { + + private var isKey = true + private var isCurrentValueSensitive = false + + override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean { + isKey = index % 2 == 0 + // Each key is encoded before its value, so isCurrentValueSensitive already applies to it. + if (!isKey && isCurrentValueSensitive) { + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + return false + } + return 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) { + val key = value.toString() + // Let the sink reject oversized keys before the denylist scan allocates a lowercase copy. + sink.key(key) + isCurrentValueSensitive = isSensitive(key) + } else { + sink.scalar(value) + } + } + + override fun putFiltered() { + if (isKey) { + sink.key(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + isCurrentValueSensitive = true + } else { + super.putFiltered() + } + } + + 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`). + */ + private val UNSIGNED_SERIAL_NAMES = + setOf("kotlin.UByte", "kotlin.UShort", "kotlin.UInt", "kotlin.ULong") + + /** 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.failure?.let { throw it } + if (++calls > MAX_SERIALIZER_NESTING) { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + } + + fun exit() { + calls-- + } + } + + /** + * Replaces values under sensitive keys with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE] before + * forwarding them to [sink]. Nested maps and lists under those keys are discarded. + * + * All encoders write through this filter to keep sensitive values out of the output. They also + * check keys before invoking serializers, avoiding work and potential failures for values that + * will be filtered. + */ + internal class SensitiveKeyFilter(private val sink: ArgumentSink) : ArgumentSink { + + /** The number of open maps and lists being discarded, or 0 if none. */ + private var discardDepth = 0 + private var isNextValueSensitive = false + + override val failure: DropArguments? + get() = sink.failure + + override fun beginMap(identity: Any?) { + begin { sink.beginMap(identity) } + } + + override fun beginList(identity: Any?) { + begin { sink.beginList(identity) } + } + + override fun key(name: String) { + if (discardDepth > 0) { + return + } + sink.key(name) + isNextValueSensitive = isSensitive(name) + } + + override fun scalar(value: Any?) { + if (discardDepth > 0) { + return + } + sink.scalar(if (isNextValueSensitive) UrlUtils.SENSITIVE_DATA_SUBSTITUTE else value) + isNextValueSensitive = false + } + + /** + * Delegates [compute] to [sink] so limits are checked before computing the value. + * + * Skips computation for filtered or discarded values. + */ + override fun computedScalar(compute: () -> Any?) { + if (discardDepth > 0) { + return + } + val isSensitive = isNextValueSensitive + sink.computedScalar { if (isSensitive) UrlUtils.SENSITIVE_DATA_SUBSTITUTE else compute() } + isNextValueSensitive = false + } + + override fun end() { + if (discardDepth > 0) { + discardDepth-- + } else { + sink.end() + } + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing = + sink.reject(reason, warning) + + private inline fun begin(beginInSink: () -> Unit) { + when { + discardDepth > 0 -> discardDepth++ + isNextValueSensitive -> { + sink.scalar(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + isNextValueSensitive = false + discardDepth = 1 + } + else -> 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 new file mode 100644 index 00000000000..0c88012a1ee --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -0,0 +1,39 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.serializerOrNull + +/** + * Returns the serializer of [type], or `null` if kotlinx.serialization can't provide one (e.g. for + * a generic class whose serializer needs type arguments). + * + * Unlike kotlinx.serialization's [serializerOrNull], this also finds the serializers of private + * `@Serializable` objects. Like it, this returns serializers for built-in types (e.g. `String`) and + * enums that aren't `@Serializable`. + * + * This method may throw, as looking up a serializer can run the type's serializer code for the + * first time (e.g. an [InvocationTargetException][java.lang.reflect.InvocationTargetException] + * whose cause is the serializer initializer's error). + */ +@Suppress("SwallowedException") +internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = + try { + serializerOrNull(type) + } catch (_: IllegalAccessException) { + // kotlinx.serialization reads a serializable object's INSTANCE field without making it + // accessible, which fails for private objects. + privateObjectSerializerOrNull(type) + } + +/** + * 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.) + * + * Propagates any exception thrown by the reflective lookup. + */ +private fun privateObjectSerializerOrNull(type: Class<*>): KSerializer<*>? { + val instance = type.getDeclaredField("INSTANCE").apply { isAccessible = true }.get(null) + return type.getDeclaredMethod("serializer").apply { isAccessible = true }.invoke(instance) + as? KSerializer<*> +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentDuplicateKeysTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentDuplicateKeysTest.kt index 9e7c0e82e09..b37c439f9fb 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentDuplicateKeysTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentDuplicateKeysTest.kt @@ -28,8 +28,7 @@ class ArgumentDuplicateKeysTest { .log( eq(WARNING), eq( - "A Nav3 map key (String) stringifies to the same string as another key (Int). " + - "Dropping this entry's arguments.", + "Nav3 map keys stringify to the same string. Dropping this entry's arguments.", ), ) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt index 2ba320a31e8..122d7161e03 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -4,7 +4,7 @@ import com.google.common.truth.Truth.assertThat import java.io.File import org.junit.Test -/** Enforces the lifecycle package's dependency boundary. */ +/** Enforces internal dependency rules for `sentry-android-navigation3`. */ class PackageBoundariesTest { private val sources: List = @@ -14,6 +14,50 @@ class PackageBoundariesTest { .map(SourceFile::parse) .toList() + @Test + fun `only the kotlinx package may import kotlinx serialization`() { + val otherSources = sources.filterNot { it.packageName.isIn(KOTLINX) } + + val violations = otherSources.importsMatching { it.isIn("kotlinx.serialization") } + + assertThat(otherSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `source files in the kotlinx package have names that start with Kotlinx`() { + val kotlinxSources = sources.filter { it.packageName.isIn(KOTLINX) } + + val violations = kotlinxSources.filterNot { it.name.startsWith("Kotlinx") }.map { it.path } + + assertThat(kotlinxSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `only the kotlinx package and the mapper factory may import the kotlinx package`() { + val otherSources = sources.filterNot { + it.packageName.isIn(KOTLINX) || it.path == MAPPER_FACTORY_PATH + } + + val violations = otherSources.importsMatching { it.isIn(KOTLINX) } + + assertThat(otherSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `the kotlinx package has no imports from Android, AndroidX, or the lifecycle package`() { + val kotlinxSources = sources.filter { it.packageName.isIn(KOTLINX) } + + val violations = kotlinxSources.importsMatching { + it.isIn("android") || it.isIn("androidx") || it.isIn(LIFECYCLE) + } + + assertThat(kotlinxSources).isNotEmpty() + assertThat(violations).isEmpty() + } + @Test fun `the lifecycle package has no imports from other Sentry navigation3 packages, Compose, or AndroidX Nav3`() { val lifecycleSources = sources.filter { it.packageName.isIn(LIFECYCLE) } @@ -66,6 +110,7 @@ class PackageBoundariesTest { /** A source file's location, package, and import targets. */ private class SourceFile( val path: String, + val name: String, val packageName: String, val imports: List, ) { @@ -77,6 +122,7 @@ class PackageBoundariesTest { val lines = file.readLines().map(String::trim) return SourceFile( path = file.invariantSeparatorsPath, + name = file.name, packageName = lines.firstNotNullOfOrNull { PACKAGE.find(it)?.groupValues?.get(1) }.orEmpty(), imports = lines.mapNotNull { IMPORT.find(it)?.groupValues?.get(1) }, @@ -88,7 +134,10 @@ class PackageBoundariesTest { private companion object { const val SOURCE_ROOT = "src/main/kotlin" const val ROOT = "io.sentry.compose.navigation3" + const val KOTLINX = "$ROOT.internal.backstack.kotlinx" const val LIFECYCLE = "$ROOT.internal.lifecycle" + const val MAPPER_FACTORY_PATH = + "$SOURCE_ROOT/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt" /** Whether this name is [packageName] or lies inside it. */ fun String.isIn(packageName: String): Boolean = 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 850802400a4..dfe941ee2f8 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 @@ -34,6 +34,8 @@ import io.sentry.SentryTracer import io.sentry.TransactionContext import io.sentry.TransactionOptions import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.junit.Rule import org.junit.Test import org.junit.rules.TestWatcher @@ -75,6 +77,10 @@ class SentryNavEffectTest { private data class ProfileRoute(val userId: String) + @Serializable @SerialName("SerializableHome") private data object SerializableHomeRoute + + @Serializable private data class SerializableProfileRoute(val userId: String) + private class Fixture { val options = SentryOptions().apply { @@ -353,6 +359,42 @@ class SentryNavEffectTest { assertThat(observedTransactionNames).containsExactly("/HomeRoute", "/ProfileRoute").inOrder() } + @Test + fun `SerialName records serial names, and unknown names for entries that aren't @Serializable`() { + val fixture = Fixture() + val backStack = mutableStateListOf(SerializableHomeRoute) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialName, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + composeRule.runOnIdle { + backStack.add(SerializableProfileRoute("123")) + backStack.add(ProfileRoute("456")) + } + composeRule.waitForIdle() + + val profileName = "/io.sentry.compose.navigation3.SentryNavEffectTest.SerializableProfileRoute" + assertThat(fixture.breadcrumbs.first().data["to"]).isEqualTo("/SerializableHome") + assertThat(fixture.transactions.first().name).isEqualTo("/SerializableHome") + assertThat(fixture.scope.screen).isEqualTo("/unknown") + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("entry" to "/unknown"), + mapOf("entry" to profileName), + mapOf("entry" to "/SerializableHome"), + ), + ) + } + @Test fun `updated entry mapper is used for later navigation changes`() { val fixture = Fixture() diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt new file mode 100644 index 00000000000..4f77307b74e --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt @@ -0,0 +1,12 @@ +package io.sentry.compose.navigation3.internal.backstack + +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.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/backstack/ArgumentSanitizerTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt index d9f0f76864a..4c078e03ab6 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 @@ -16,6 +16,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions class ArgumentSanitizerTest { @@ -74,6 +75,88 @@ class ArgumentSanitizerTest { verify(logger, times(1)).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue")) } + // Arguments that write themselves + + @Test + fun `sanitizeEntry() - lets an ArgumentSource write its arguments instead of reading them as a map`() { + val arguments = SelfWritingArguments { sink -> + sink.key("written") + sink.scalar("by the source") + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized).isEqualTo(SanitizedArguments(mapOf("written" to "by the source"))) + } + + @Test + fun `sanitizeEntry() - records the drop reason of an ArgumentSource that drops its arguments`() { + val arguments = SelfWritingArguments { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, "source warning") + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + } + + @Test + fun `sanitizeEntry() - logs the warning of an ArgumentSource that drops its arguments`() { + val arguments = SelfWritingArguments { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, "source warning") + } + + sanitizer.sanitizeEntry(arguments) + + verify(logger).log(eq(WARNING), eq("source warning")) + } + + @Test + fun `sanitizeEntry() - logs nothing when an ArgumentSource drops its arguments without a warning`() { + val arguments = SelfWritingArguments { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + verifyNoInteractions(logger) + } + + @Test + fun `sanitizeEntry() - records the broken limit when an ArgumentSource replaces it with another exception`() { + val arguments = overCharacterLimitReplacedWith { IllegalStateException("replaced") } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `sanitizeEntry() - logs the broken limit's warning when an ArgumentSource replaces it with another exception`() { + val arguments = overCharacterLimitReplacedWith { IllegalStateException("replaced") } + + sanitizer.sanitizeEntry(arguments) + + verify(logger).log(eq(WARNING), eq(DropArguments.MAX_CHARACTER_WARNING)) + verify(logger, never()).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), any()) + } + + @Test + fun `sanitizeEntry() - records the broken limit when an ArgumentSource replaces it with its own DropArguments`() { + val arguments = overCharacterLimitReplacedWith { + DropArguments(ArgumentDropReason.INVALID_STRUCTURE, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + // Dropped arguments @Test @@ -82,7 +165,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(DropArguments.MAX_COUNT_WARNING)) } @Test @@ -92,7 +175,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(DropArguments.MAX_CHARACTER_WARNING)) } @Test @@ -142,6 +225,46 @@ class ArgumentSanitizerTest { assertThat(third).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) } + @Test + fun `entries share the value budget with arguments that write themselves`() { + // The source writes half of the value budget, so one value more than the other half doesn't + // fit. + val half = MAX_ARGUMENT_VALUES / 2 + val first = + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(half - 1) { sink.scalar(it) } + sink.end() + }, + ) + val second = sanitizer.sanitizeEntry(mapOf("values" to List(half) { it })) + + assertThat(first.dropReason).isNull() + assertThat(second).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `arguments that write themselves share the value budget with other entries`() { + // The first entry uses half of the value budget, so the source's one value more than the other + // half doesn't fit. + val half = MAX_ARGUMENT_VALUES / 2 + sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + + val sanitized = + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(half) { sink.scalar(it) } + sink.end() + }, + ) + + assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + // Failures @Test @@ -158,7 +281,7 @@ 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(DropArguments.STRUCTURE_WARNING), eq(throwing.failure)) } @Test @@ -171,8 +294,7 @@ class ArgumentSanitizerTest { assertFailsWith { sanitizer.sanitizeEntry(mapOf("fatal" to fatal)) } - verify(logger, never()) - .log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), any()) + verify(logger, never()).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), any()) } @Test @@ -195,7 +317,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(DropArguments.MAX_COUNT_WARNING)) } @Test @@ -205,7 +327,45 @@ 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(DropArguments.MAX_CHARACTER_WARNING)) + } + + @Test + fun `entries after an ArgumentSource exhausts the value budget are dropped`() { + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(MAX_ARGUMENT_VALUES) { sink.scalar(it) } + sink.end() + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `entries after an ArgumentSource replaces a broken character limit with another exception are dropped`() { + sanitizer.sanitizeEntry(overCharacterLimitReplacedWith { IllegalStateException("replaced") }) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `entries after an ArgumentSource replaces a broken character limit with its own DropArguments are dropped`() { + sanitizer.sanitizeEntry( + overCharacterLimitReplacedWith { + DropArguments(ArgumentDropReason.INVALID_STRUCTURE, warning = null) + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) } @Test @@ -228,6 +388,17 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) } + @Test + fun `an ArgumentSource that drops its arguments for invalid structure doesn't drop later entries`() { + sanitizer.sanitizeEntry( + SelfWritingArguments { throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, null) }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + @Test fun `an entry that failed sanitization doesn't drop later entries`() { sanitizer.sanitizeEntry(mapOf("throwing" to ThrowingValue())) @@ -236,4 +407,19 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) } + + /** + * Arguments that write one character more than the character budget, then catch the sink's + * [DropArguments] and throw [replacement] instead, without it as the cause. + */ + private fun overCharacterLimitReplacedWith(replacement: () -> Throwable) = + SelfWritingArguments { sink -> + try { + // The key and the value are one character more than the budget. + sink.key("v") + sink.scalar("x".repeat(MAX_ARGUMENT_CHARACTERS)) + } catch (@Suppress("SwallowedException") e: DropArguments) { + throw replacement() + } + } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index d07f3733118..59d4d77371c 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -1,6 +1,7 @@ package io.sentry.compose.navigation3.internal.backstack import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat import io.sentry.ILogger @@ -13,7 +14,6 @@ import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Compa import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME import java.io.StringWriter -import java.util.AbstractCollection import kotlin.test.assertFailsWith import org.junit.Test import org.mockito.kotlin.any @@ -396,128 +396,43 @@ class BackStackConverterTest { } @Test - fun `convert returns arguments in proper serializable form`() { - val text = StringBuilder("hello") + fun `convert returns the mapper's arguments sanitized`() { val sut = getSut( entryMapper = { entry -> - entryInfo( - entry, - mapOf( - "str" to "hello", - "charSequence" to text, - "char" to 'x', - "num" to 42, - "bool" to true, - "enum" to PrivacyMode.PRIVATE, - "nil" to null, - "nested" to mapOf("inner" to "value"), - "tags" to listOf("a", "b", "c"), - "array" to arrayOf("a", 1, false, PrivacyMode.PUBLIC, 'z'), - "ints" to intArrayOf(1, 2, 3), - "chars" to charArrayOf('a', 'b'), - "bytes" to byteArrayOf(4, 5), - ), - ) - }, - ) - - assertThat(sut.convert(HomeScreen()).arguments) - .isEqualTo( - mapOf( - "str" to "hello", - "charSequence" to "hello", - "char" to "x", - "num" to 42, - "bool" to true, - "enum" to "PRIVATE", - "nil" to null, - "nested" to mapOf("inner" to "value"), - "tags" to listOf("a", "b", "c"), - "array" to listOf("a", 1, false, "PUBLIC", "z"), - "ints" to listOf(1, 2, 3), - "chars" to listOf("a", "b"), - "bytes" to listOf(4.toByte(), 5.toByte()), - ), - ) - } - - @Test - fun `convert sanitizes arguments with nested supported containers recursively`() { - val sut = - getSut( - entryMapper = { entry -> - entryInfo( - entry, - mapOf( - "nested" to - mapOf( - "items" to - arrayOf( - StringBuilder("x"), - listOf('y', PrivacyMode.PRIVATE), - booleanArrayOf(true, false), - charArrayOf('q'), - ), - ), - ), - ) + entryInfo(entry, mapOf("mode" to PrivacyMode.PRIVATE, "ids" to intArrayOf(1, 2))) }, ) assertThat(sut.convert(HomeScreen()).arguments) - .isEqualTo( - mapOf( - "nested" to - mapOf("items" to listOf("x", listOf("y", "PRIVATE"), listOf(true, false), listOf("q"))), - ), - ) + .isEqualTo(mapOf("mode" to "PRIVATE", "ids" to listOf(1, 2))) } @Test - fun `convert coerces arguments with unsupported values to strings`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" - } + fun `convert hides state reads during argument sanitization from snapshot observation`() { + val arguments = mutableStateMapOf("state" to "value") + val sut = getSut(entryMapper = { entry -> entryInfo(entry, arguments) }) + val observedReads = mutableListOf() + val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("bad" to OpaqueValue())) }) + val converted = + try { + snapshot.enter { sut.convert(HomeScreen()) } + } finally { + snapshot.dispose() + } - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("bad" to "opaque-value")) + assertThat(converted.arguments).isEqualTo(mapOf("state" to "value")) + assertThat(observedReads).isEmpty() } @Test - fun `convert logs an unsupported value warning once per back stack update`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" + fun `convert hides state reads by an ArgumentSource from snapshot observation`() { + val state = mutableStateOf("value") + val arguments = SelfWritingArguments { sink -> + sink.key("state") + sink.scalar(state.value) } - - val sut = - getSut( - entryMapper = { entry -> - entryInfo( - entry, - when (entry) { - is HomeScreen -> mapOf("bad" to OpaqueValue()) - is ProfileScreen -> mapOf("alsoBad" to OpaqueValue()) - else -> emptyMap() - }, - ) - }, - ) - - sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) - - verify(logger, times(1)) - .log( - eq(WARNING), - eq(UNSUPPORTED_VALUE_WARNING), - eq("OpaqueValue"), - ) - } - - @Test - fun `convert hides state reads during argument sanitization from snapshot observation`() { - val arguments = mutableStateMapOf("state" to "value") val sut = getSut(entryMapper = { entry -> entryInfo(entry, arguments) }) val observedReads = mutableListOf() val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) @@ -554,54 +469,6 @@ class BackStackConverterTest { ) } - @Test - fun `convert returns empty arguments for cyclic structures`() { - val cyclic = mutableMapOf() - cyclic["self"] = cyclic - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("cyclic" to cyclic)) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert returns empty arguments for deeply nested structures`() { - var nested: Any? = "value" - repeat(25) { nested = listOf(nested) } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("nested" to nested)) }) - - val entry = sut.convert(ProfileScreen("123")) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert drops oversized arguments`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(1_001) { it })) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.MAX_COUNT) - } - - @Test - fun `convert drops arguments when character budget is exceeded`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to "x".repeat(4_097))) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - @Test fun `convert starts each back stack update with a fresh argument budget`() { val sut = @@ -614,40 +481,6 @@ class BackStackConverterTest { assertThat(entry.argumentDropReason).isNull() } - @Test - fun `convert reports sanitization failures`() { - class ThrowingValue { - override fun toString(): String = error("boom") - } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to ThrowingValue())) }) - - val converted = sut.convert(HomeScreen()) - - assertThat(converted.arguments).isEmpty() - assertThat(converted.argumentDropReason).isEqualTo(ArgumentDropReason.SANITIZATION_FAILED) - } - - @Test - fun `arguments do not use caller collection size for allocation`() { - val values = - object : AbstractCollection() { - var wasSizeRead = false - - override val size: Int - get() { - wasSizeRead = true - return 2 - } - - override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() - } - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to values)) }) - - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("values" to listOf(1, 2))) - assertThat(values.wasSizeRead).isFalse() - } - @Test fun `omitted arguments normalize to an empty map`() { val sut = getSut() 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 new file mode 100644 index 00000000000..7bb5c0594d6 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -0,0 +1,344 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.Sentry +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.MIN_KOTLINX_SERIALIZATION_VERSION +import io.sentry.test.initForTest +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.thread +import kotlin.test.assertFailsWith +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import org.junit.Test +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.verifyNoInteractions + +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") } + private val logger = mock() + + // serialName and serialNameAndProperties + + @Test + fun `serialName names entries without recording their properties`() { + val mapper = BuiltInBackStackEntryMappers.serialName + + val mapped = listOf(Home, Detail("1")).map(mapper::map) + + assertThat(mapped) + .containsExactly(SentryBackStackEntry("Home"), SentryBackStackEntry("Detail")) + .inOrder() + } + + // BackStackEntryMapper's companion mappers + + @Test + fun `BackStackEntryMapper SerialName can serve as the mapper for any entry type`() { + val homeMapper: BackStackEntryMapper = BackStackEntryMapper.SerialName + + assertThat(homeMapper.map(Home)).isEqualTo(SentryBackStackEntry("Home")) + } + + @Test + fun `BackStackEntryMapper SerialName maps entries to null when the kotlinx mapper can't be loaded`() { + val classLoader = KotlinxMapperHidingClassLoader() + + val mapper = classLoader.companionMapper("getSerialName") + + assertThat(mapper.map(Home)).isNull() + assertThat(classLoader.wasKotlinxMapperRequested).isTrue() + } + + @Test + fun `BackStackEntryMapper SerialName maps entries to null when kotlinx serialization is missing`() { + val classLoader = KotlinxMapperHidingClassLoader(hidesKotlinx = true) + val entry = classLoader.notSerializableEntry("1") + + val mapper = classLoader.companionMapper("getSerialName") + + assertThat(mapper.map("home")).isNull() + assertThat(mapper.map(entry)).isNull() + assertThat(classLoader.wasKotlinxRequested).isTrue() + } + + // First access from several threads + + @Test + fun `BackStackEntryMapper SerialName holds no lock while creating the mapper logs`() { + val race = raceOnFirstAccess("getSerialName") + + assertThat(race.otherThreadLoggerGotAppLock).isTrue() + } + + @Test + fun `BackStackEntryMapper SerialName returns the mapper published first to racing threads`() { + val race = raceOnFirstAccess("getSerialName") + + assertThat(race.otherThreadMapper).isSameInstanceAs(race.thisThreadMapper) + assertThat(race.laterMapper).isSameInstanceAs(race.thisThreadMapper) + } + + // MIN_KOTLINX_SERIALIZATION_VERSION + + @Test + fun `MIN_KOTLINX_SERIALIZATION_VERSION matches kotlinxSerializationFloor in nav3 versions catalog`() { + val floor = + checkNotNull(System.getProperty(KOTLINX_SERIALIZATION_FLOOR_PROPERTY)) { + "System property $KOTLINX_SERIALIZATION_FLOOR_PROPERTY is missing. Run this test through " + + "Gradle, which sets it from kotlinxSerializationFloor in gradle/nav3.versions.toml." + } + + assertThat(MIN_KOTLINX_SERIALIZATION_VERSION).isEqualTo(floor) + } + + // create() + + @Test + fun `create() - returns the kotlinx mapper when it can be created`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + kotlinxMapper + } + + assertThat(mapper).isSameInstanceAs(kotlinxMapper) + } + + @Test + fun `create() - doesn't log when the kotlinx mapper can be created`() { + BuiltInBackStackEntryMappers.create(logger = { logger }) { kotlinxMapper } + + verifyNoInteractions(logger) + } + + @Test + fun `create() - maps entries to null when creating the kotlinx mapper throws NoClassDefFoundError`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw NoClassDefFoundError("kotlinx/serialization/KSerializer") + } + + assertThat(mapper.map(Home)).isNull() + } + + @Test + fun `create() - maps entries to null when creating the kotlinx mapper throws ExceptionInInitializerError`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw ExceptionInInitializerError("static initializer failed") + } + + assertThat(mapper.map(Home)).isNull() + } + + @Test + fun `create() - logs the LinkageError and compatibility advice when mapper creation fails`() { + val error = NoClassDefFoundError("kotlinx/serialization/KSerializer") + + BuiltInBackStackEntryMappers.create(logger = { logger }) { throw error } + + val message = argumentCaptor() + verify(logger, times(1)).log(eq(SentryLevel.WARNING), message.capture(), eq(error)) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `create() - propagates an exception that is not a linkage error from creating the kotlinx mapper`() { + val exception = IllegalStateException("mapper bug") + + val thrown = + assertFailsWith { + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw exception + } + } + + assertThat(thrown).isSameInstanceAs(exception) + } + + /** + * Races two threads on the first access of a fresh copy of the companion mapper [getterName], in + * the shape of a deadlock: this thread holds a lock of the app's while it accesses the mapper, + * and the other thread's creation of the mapper, which is already logging that the kotlinx mapper + * can't be loaded, waits for that lock in the app's logger. + * + * Every wait is bounded, so a deadlock makes the logger give up on the lock rather than hang. The + * assertions inside are precondition guards that the race ran as intended, not the contracts + * under test. + */ + private fun raceOnFirstAccess(getterName: String): FirstAccessRace { + val appLock = ReentrantLock() + val logger = LockingLogger(appLock, thisThread = Thread.currentThread()) + initForTest( + { + it.dsn = "https://key@sentry.io/proj" + it.isDebug = true + it.setLogger(logger) + }, + true, + ) + try { + val classLoader = KotlinxMapperHidingClassLoader() + appLock.lock() + var otherThreadMapper: Any? = null + val otherThread = + thread(name = "other-mapper-user") { + otherThreadMapper = classLoader.companionMapper(getterName).delegate + } + assertThat(logger.otherThreadLogging.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue() + + val thisThreadMapper = + try { + classLoader.companionMapper(getterName).delegate + } finally { + appLock.unlock() + } + otherThread.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS * 2)) + assertThat(otherThread.isAlive).isFalse() + + return FirstAccessRace( + otherThreadLoggerGotAppLock = logger.otherThreadGotLock, + otherThreadMapper = otherThreadMapper, + thisThreadMapper = thisThreadMapper, + laterMapper = classLoader.companionMapper(getterName).delegate, + ) + } finally { + Sentry.close() + } + } + + private class FirstAccessRace( + val otherThreadLoggerGotAppLock: Boolean, + val otherThreadMapper: Any?, + val thisThreadMapper: Any, + val laterMapper: Any, + ) + + /** + * An app's logger that takes [appLock] to log that the built-in mappers couldn't be created, as + * an app's logger might, giving up after a timeout. Records whether a thread other than + * [thisThread] got the lock. + */ + private class LockingLogger(private val appLock: ReentrantLock, private val thisThread: Thread) : + ILogger { + val otherThreadLogging = CountDownLatch(1) + + @Volatile var otherThreadGotLock = false + + override fun log(level: SentryLevel, message: String, vararg args: Any?) = Unit + + override fun log(level: SentryLevel, message: String, throwable: Throwable?) { + if (!message.startsWith(CREATION_FAILED)) return + val isOtherThread = Thread.currentThread() != thisThread + if (isOtherThread) otherThreadLogging.countDown() + val gotLock = appLock.tryLock(TIMEOUT_SECONDS, TimeUnit.SECONDS) + if (isOtherThread) otherThreadGotLock = gotLock + if (gotLock) appLock.unlock() + } + + override fun log( + level: SentryLevel, + throwable: Throwable?, + message: String, + vararg args: Any?, + ) = Unit + + override fun isEnabled(level: SentryLevel?): Boolean = true + } + + /** + * Loads its own copy of this module's classes, so their singletons are created anew, but can't + * find [KotlinxBackStackEntryMapper], as when it can't be linked against the app's + * kotlinx.serialization. Other classes come from the test's class loader. + * + * With `hidesKotlinx = true`, it finds [KotlinxBackStackEntryMapper] but not + * kotlinx.serialization itself, as when the app doesn't depend on it. + */ + private class KotlinxMapperHidingClassLoader(private val hidesKotlinx: Boolean = false) : + ClassLoader(BuiltInBackStackEntryMappersTest::class.java.classLoader) { + + @Volatile + var wasKotlinxMapperRequested = false + private set + + @Volatile + var wasKotlinxRequested = false + private set + + /** Returns a [NotSerializable] loaded by this class loader, which doesn't need kotlinx. */ + fun notSerializableEntry(id: String): Any = + loadClass(NotSerializable::class.java.name).getConstructor(String::class.java).newInstance(id) + + /** Returns the mapper of this class loader's `BackStackEntryMapper.Companion.`. */ + fun companionMapper(getterName: String): Mapper { + val companion = + loadClass(BackStackEntryMapper::class.java.name).getField("Companion").get(null) + return Mapper(companion.javaClass.getMethod(getterName).invoke(companion)) + } + + override fun loadClass(name: String, resolve: Boolean): Class<*> = + synchronized(this) { + when { + name == HIDDEN_CLASS && !hidesKotlinx -> { + wasKotlinxMapperRequested = true + throw ClassNotFoundException(name) + } + name.startsWith(KOTLINX_PACKAGE) && hidesKotlinx -> { + wasKotlinxRequested = true + throw ClassNotFoundException(name) + } + !name.startsWith(ISOLATED_PACKAGE) -> super.loadClass(name, resolve) + else -> findLoadedClass(name) ?: define(name) + } + } + + private fun define(name: String): Class<*> { + val bytes = + parent.getResourceAsStream(name.replace('.', '/') + ".class")?.use { it.readBytes() } + ?: throw ClassNotFoundException(name) + return defineClass(name, bytes, 0, bytes.size) + } + + /** A mapper loaded by this class loader, whose types differ from the test's. */ + class Mapper(val delegate: Any) { + val type: Class<*> = delegate.javaClass + + fun map(backStackEntry: Any): Any? = + type.getMethod("map", Any::class.java).invoke(delegate, backStackEntry) + } + + private companion object { + const val ISOLATED_PACKAGE = "io.sentry.compose.navigation3." + const val KOTLINX_PACKAGE = "kotlinx.serialization." + val HIDDEN_CLASS: String = KotlinxBackStackEntryMapper::class.java.name + } + } + + private companion object { + /** Bounds every wait, so that a deadlock fails the test rather than hanging it. */ + const val TIMEOUT_SECONDS = 5L + + const val CREATION_FAILED = "Nav3 built-in mapper creation failed." + + /** Set by the module's Gradle build from `kotlinxSerializationFloor`. */ + const val KOTLINX_SERIALIZATION_FLOOR_PROPERTY = "nav3.kotlinxSerializationFloor" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt new file mode 100644 index 00000000000..609e4cb4788 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt @@ -0,0 +1,436 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.BeginList +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.BeginMap +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.End +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.Key +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.Scalar +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.UncomputedScalar +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 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() + } + + // 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(nested), Key("1"), Scalar("a"), End) + .inOrder() + } + + @Test + fun `writeTo() - passes a nested map as its own identity`() { + val nested = mapOf("k" to "v") + val source = hostArgumentSource(mapOf("nested" to nested)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(nested) + } + + @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(set), Scalar("a"), Scalar("b"), End) + .inOrder() + } + + @Test + fun `writeTo() - passes a collection as its own identity`() { + val list = listOf("a") + val source = hostArgumentSource(mapOf("list" to list)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(list) + } + + @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(array), 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() - passes a primitive array as its own identity`() { + val ints = intArrayOf(1, 2) + val source = hostArgumentSource(mapOf("ints" to ints)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(ints) + } + + @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(listOf(outer)), + BeginMap(outer), + Key("inner"), + BeginList(inner), + 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() + } + + // 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 = DropArguments(ArgumentDropReason.MAX_COUNT, DropArguments.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 } + + sealed interface Event { + data class Key(val name: String) : Event + + data class Scalar(val value: Any?) : Event + + data class BeginMap(val identity: Any?) : Event + + data class BeginList(val identity: Any?) : 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 val failure: DropArguments? = null + + override fun beginMap(identity: Any?) { + events += BeginMap(identity) + } + + override fun beginList(identity: Any?) { + events += BeginList(identity) + } + + override fun key(name: 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 = + throw UnsupportedOperationException("HostArgumentSource enforces no limits of its own") + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt new file mode 100644 index 00000000000..ccba9d16797 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt @@ -0,0 +1,15 @@ +package io.sentry.compose.navigation3.internal.backstack + +/** + * Arguments that write themselves with [write], like a built-in mapper's. Read as a map, they hold + * only [entries], which differ from what they write unless a test sets them. + */ +internal class SelfWritingArguments( + override val entries: Set> = mapOf("read" to "as a map").entries, + private val write: (ArgumentSink) -> Unit, +) : AbstractMap(), ArgumentSource { + + override fun writeTo(sink: ArgumentSink) { + write(sink) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt new file mode 100644 index 00000000000..8ce124c1261 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt @@ -0,0 +1,781 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.util.UrlUtils +import kotlin.test.assertFailsWith +import org.junit.Test + +class TreeArgumentWriterTest { + + private val budget = ArgumentBudget() + private val sink = TreeArgumentWriter(budget) + + private val characterLimitDrop = + ArgumentDropReason.CHARACTER_LIMIT to DropArguments.MAX_CHARACTER_WARNING + private val duplicateKeyDrop = + ArgumentDropReason.DUPLICATE_KEY to DropArguments.DUPLICATE_KEY_WARNING + private val maxCountDrop = ArgumentDropReason.MAX_COUNT to DropArguments.MAX_COUNT_WARNING + private val structureDrop = + ArgumentDropReason.INVALID_STRUCTURE to DropArguments.STRUCTURE_WARNING + + private val DropArguments.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() - writes text exactly as long as the remaining characters`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(2)) + limitedSink.key("") + + limitedSink.scalar("ab") + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to "ab")) + } + + @Test + fun `scalar() - spends characters for a CharSequence value`() { + val limitedSink = TreeArgumentWriter(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 = TreeArgumentWriter(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 = TreeArgumentWriter(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 = TreeArgumentWriter(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 = TreeArgumentWriter(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 IllegalArgumentException for an unsupported type`() { + sink.key("opaque") + + assertFailsWith { sink.scalar(Any()) } + } + + @Test + fun `scalar() - throws IllegalStateException for a map value written without a key`() { + assertFailsWith { sink.scalar(1) } + } + + // 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 = TreeArgumentWriter(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 = TreeArgumentWriter(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() - drops the arguments for a duplicate key without computing the value`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + var computations = 0 + + val drop = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - drops the arguments for a duplicate key when computing the value would throw`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + + val drop = + assertFailsWith { + sink.computedScalar { throw IllegalStateException("host toString() failed") } + } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @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() - accepts a key exactly as long as the remaining characters`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(2)) + + limitedSink.key("ab") + limitedSink.scalar(null) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("ab" to null)) + } + + @Test + fun `key() - spends the characters of the key`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + + val drop = assertFailsWith { limitedSink.key("ab") } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `key() - doesn't spend a value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + + limitedSink.key("a") + + val drop = assertFailsWith { limitedSink.scalar(1) } + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + // Containers + + @Test + fun `beginMap() - spends one value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + limitedSink.key("map") + + val drop = assertFailsWith { limitedSink.beginMap() } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `beginList() - spends one value`() { + val limitedSink = TreeArgumentWriter(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 = TreeArgumentWriter(budgetWithValuesRemaining(1)) + limitedSink.key("id") + + limitedSink.scalar(1) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("id" to 1)) + } + + @Test + fun `end() - throws IllegalStateException when no map or list is open`() { + assertFailsWith { sink.end() } + } + + @Test + fun `end() - throws IllegalStateException 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") + + 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() + + 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") + + assertThat(sink.argumentsOrThrow()["nested"]) + .isEqualTo(nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf")) + } + + // Cycles + + @Test + fun `a container nested in a container with the same identity drops the arguments for invalid structure`() { + val list = mutableListOf() + sink.key("cyclic") + sink.beginList(identity = list) + + val drop = assertFailsWith { sink.beginList(identity = list) } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container with the root identity drops the arguments for invalid structure`() { + val root = mutableMapOf() + val rootedSink = TreeArgumentWriter(budget, rootIdentity = root) + rootedSink.key("self") + + val drop = assertFailsWith { rootedSink.beginMap(identity = root) } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container identical to the root is written when no root identity is given`() { + val root = mutableMapOf() + sink.key("self") + + sink.beginMap(identity = root) + sink.end() + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("self" to emptyMap())) + } + + @Test + fun `sibling containers with the same identity are both written`() { + val shared = listOf("a") + sink.key("first") + sink.beginList(identity = shared) + sink.scalar("a") + sink.end() + sink.key("second") + + sink.beginList(identity = shared) + sink.scalar("a") + sink.end() + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("first" to listOf("a"), "second" to listOf("a"))) + } + + @Test + fun `nested containers without an identity are never treated as a cycle`() { + sink.key("nested") + sink.beginList(identity = null) + + sink.beginList(identity = null) + sink.end() + sink.end() + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("nested" to listOf(emptyList()))) + } + + // Duplicate keys + + @Test + fun `a scalar under a key already in its map drops the arguments for a duplicate key`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + + val drop = assertFailsWith { sink.scalar(2) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a map under a key already in its map drops the arguments for a duplicate key when the map begins`() { + sink.key("filters") + sink.scalar(null) + sink.key("filters") + + val drop = assertFailsWith { sink.beginMap() } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a list under a key already in its map drops the arguments for a duplicate key when the list begins`() { + sink.key("tags") + sink.beginList() + sink.end() + sink.key("tags") + + val drop = assertFailsWith { sink.beginList() } + + 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 `a substitute value under a substitute key already holding the substitute is written once`() { + sink.key(SUBSTITUTE) + sink.scalar(SUBSTITUTE) + sink.key(SUBSTITUTE) + + sink.scalar(SUBSTITUTE) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf(SUBSTITUTE to SUBSTITUTE)) + } + + @Test + fun `a substitute value under a substitute key holding another value drops the arguments for a duplicate key`() { + sink.key(SUBSTITUTE) + sink.scalar("secret") + sink.key(SUBSTITUTE) + + val drop = assertFailsWith { sink.scalar(SUBSTITUTE) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `another value under a substitute key holding the substitute drops the arguments for a duplicate key`() { + sink.key(SUBSTITUTE) + sink.scalar(SUBSTITUTE) + sink.key(SUBSTITUTE) + + val drop = assertFailsWith { sink.scalar("secret") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a substitute value under another key holding the substitute drops the arguments for a duplicate key`() { + sink.key("token") + sink.scalar(SUBSTITUTE) + sink.key("token") + + val drop = assertFailsWith { sink.scalar(SUBSTITUTE) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + // Value budget + + @Test + fun `values exactly filling the remaining value budget are written`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(2)) + limitedSink.key("list") + limitedSink.beginList() + + limitedSink.scalar(1) + limitedSink.end() + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("list" to listOf(1))) + } + + // Shared budget + + @Test + fun `sinks built on one budget share the value budget`() { + val first = TreeArgumentWriter(budget) + val second = TreeArgumentWriter(budget) + writeScalars(first, count = MAX_ARGUMENT_VALUES - 1) + writeScalars(second, count = 1) + second.key("overflow") + + val drop = assertFailsWith { second.scalar(1) } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `sinks built on one budget share the character budget`() { + val first = TreeArgumentWriter(budget) + val second = TreeArgumentWriter(budget) + first.key("x".repeat(MAX_ARGUMENT_CHARACTERS - 1)) + first.scalar(null) + second.key("y") + + val drop = assertFailsWith { second.scalar("z") } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + // Sticky failure + + @Test + fun `every write after the arguments are dropped rethrows the same DropArguments`() { + 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 DropArguments a source caught and swallowed`() { + val caught = exhaustValues() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(caught) + } + + // Recorded failure + + @Test + fun `failure - is null while every write is within the limits`() { + sink.key("id") + sink.scalar("123") + + assertThat(sink.failure).isNull() + } + + @Test + fun `failure - is the DropArguments thrown by the write that broke a limit`() { + val drop = exhaustValues() + + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `failure - stays the first DropArguments after later writes throw`() { + val drop = exhaustValues() + assertFailsWith { sink.key("after") } + assertFailsWith { sink.scalar("x".repeat(MAX_ARGUMENT_CHARACTERS)) } + + val failure = sink.failure + + assertThat(failure).isSameInstanceAs(drop) + } + + @Test + fun `failure - stays null after a write throws for an unsupported value`() { + sink.key("opaque") + assertFailsWith { sink.scalar(Any()) } + + val failure = sink.failure + + assertThat(failure).isNull() + } + + // Limits a source enforces itself + + @Test + fun `reject() - throws DropArguments with the given reason and warning`() { + val drop = rejectStructure() + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `reject() - records the DropArguments it throws as the failure`() { + val drop = rejectStructure() + + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArguments when a write already broke a limit`() { + val writeDrop = exhaustValues() + + val drop = rejectStructure() + + assertThat(drop).isSameInstanceAs(writeDrop) + assertThat(sink.failure).isSameInstanceAs(writeDrop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArguments when a limit was already rejected`() { + val firstDrop = rejectStructure() + + val drop = + assertFailsWith { + sink.reject(ArgumentDropReason.MAX_COUNT, DropArguments.MAX_COUNT_WARNING) + } + + assertThat(drop).isSameInstanceAs(firstDrop) + assertThat(sink.failure).isSameInstanceAs(firstDrop) + } + + @Test + fun `every write after a rejected limit rethrows the rejected DropArguments`() { + val drop = rejectStructure() + + assertThat(assertFailsWith { sink.key("a") }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.scalar(1) }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginMap() }).isSameInstanceAs(drop) + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `argumentsOrThrow() - rethrows the rejected DropArguments a source caught and swallowed`() { + sink.key("id") + sink.scalar("123") + val rejected = rejectStructure() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(rejected) + } + + // DropArguments + + @Test + fun `DropArguments - has no stack trace`() { + val drop = exhaustValues() + + assertThat(drop.stackTrace).isEmpty() + } + + /** 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(): DropArguments = + 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(): DropArguments = + assertFailsWith { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.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/backstack/UnavailableBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt new file mode 100644 index 00000000000..b42874d8393 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt @@ -0,0 +1,43 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel +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 + +class UnavailableBackStackEntryMapperTest { + + private data object Home + + private data class Detail(val id: String) + + private val logger = mock() + + @Test + fun `maps every back stack entry to null`() { + val mapper = UnavailableBackStackEntryMapper(logger = { logger }) + + val mapped = listOf(Home, Detail("1"), "home").map(mapper::map) + + assertThat(mapped).containsExactly(null, null, null) + } + + @Test + fun `logs a warning once per back stack entry type`() { + val mapper = UnavailableBackStackEntryMapper(logger = { logger }) + + repeat(3) { + mapper.map(Home) + mapper.map(Detail("$it")) + } + + verify(logger, times(1)).log(eq(SentryLevel.WARNING), any(), eq(Home::class.java.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), any(), eq(Detail::class.java.name)) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt new file mode 100644 index 00000000000..63edcc3a2e4 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt @@ -0,0 +1,796 @@ +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.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import java.lang.reflect.InvocationTargetException +import kotlin.test.assertFailsWith +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.MetaSerializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argThat +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify + +@OptIn(ExperimentalSerializationApi::class) +@MetaSerializable +@Target(AnnotationTarget.CLASS) +private annotation class MetaSerializableRoute + +@MetaSerializableRoute private data class MetaSerializableEntry(val id: String) + +class KotlinxBackStackEntryMapperNamingTest { + + @Serializable data class WithoutSerialName(val id: String) + + @Serializable + enum class Tab { + FEED, + @SerialName("tab.search") SEARCH, + } + + @Serializable(with = CustomNameSerializer::class) + @SerialName("IgnoredSerialName") + internal class CustomSerialized + + internal object CustomNameSerializer : NamingOnlySerializer() { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + } + + @Serializable + enum class TabWithBodies { + FEED { + override val icon = "feed" + }, + SEARCH { + override val icon = "search" + }; + + abstract val icon: String + } + + data class NotSerializable(val id: String) + + enum class UnannotatedTab { + FEED, + } + + @Serializable data class Generic(val value: T) + + // A class whose serializer's initializer threw can't be initialized again for the rest of the + // JVM's life, so each test that triggers it gets its own pair. + + @Serializable(with = UninitializableSerializerA::class) internal class UninitializableSerializedA + + internal object UninitializableSerializerA : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer A init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.A", PrimitiveKind.STRING) + } + + @Serializable(with = UninitializableSerializerB::class) internal class UninitializableSerializedB + + internal object UninitializableSerializerB : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer B init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.B", PrimitiveKind.STRING) + } + + @Serializable(with = UninitializableSerializerC::class) private object PrivateUninitializable + + private object UninitializableSerializerC : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer C init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.C", PrimitiveKind.STRING) + } + + @Serializable(with = DescriptorThrowsIllegalStateSerializer::class) + internal class DescriptorThrowsIllegalState + + internal object DescriptorThrowsIllegalStateSerializer : + NamingOnlySerializer() { + val error = IllegalStateException("descriptor failed") + + override val descriptor: SerialDescriptor + get() = throw error + } + + @Serializable(with = DescriptorThrowsAbstractMethodErrorSerializer::class) + internal class DescriptorThrowsAbstractMethodError + + internal object DescriptorThrowsAbstractMethodErrorSerializer : + NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = throw AbstractMethodError("descriptor not implemented") + } + + @Serializable(with = DescriptorThrowsNoClassDefFoundErrorSerializer::class) + internal class DescriptorThrowsNoClassDefFoundError + + internal object DescriptorThrowsNoClassDefFoundErrorSerializer : + NamingOnlySerializer() { + val error = NoClassDefFoundError("com/example/MissingDescriptorClass") + + override val descriptor: SerialDescriptor + get() = throw error + } + + // Naming + + @Test + fun `names entries after their SerialName`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Search("shoes"))) + + assertThat(mapped) + .containsExactly(SentryBackStackEntry("Detail"), SentryBackStackEntry("Search")) + .inOrder() + } + + @Test + fun `names entries without @SerialName after their fully qualified class name`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(WithoutSerialName("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.WithoutSerialName")) + } + + @Test + fun `names constants of @Serializable enums after their enum`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(Tab.FEED) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.Tab")) + } + + @Test + fun `names enum constants that have a @SerialName after their enum`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(Tab.SEARCH) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.Tab")) + } + + @Test + fun `names constants of @Serializable enums that have bodies after their enum`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { if (it == TabWithBodies::class.java) TabWithBodies.serializer() else null } + val mapper = fixture.mapper + + val mapped = mapper.map(TabWithBodies.SEARCH) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.TabWithBodies")) + } + + @Test + fun `names entries of a class with a custom serializer after its descriptor, ignoring the class's @SerialName`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(CustomSerialized()) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("custom.Name")) + } + + @Test + fun `returns null for entries that aren't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + val mapped = mapper.map(NotSerializable("1")) + + assertThat(mapped).isNull() + } + + @Test + fun `returns null for entries that aren't @Serializable even if the lookup has a serializer`() { + // kotlinx serialization has serializers for built-in types and enums that aren't @Serializable. + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { String.serializer() } + val mapper = fixture.mapper + + val mapped = + listOf( + mapper.map("home"), + mapper.map(42), + mapper.map(UnannotatedTab.FEED), + mapper.map(NotSerializable("1")), + ) + + assertThat(mapped).containsExactly(null, null, null, null) + } + + @Test + fun `returns null for entries of a class marked with a @MetaSerializable annotation`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(MetaSerializableEntry("1")) + + assertThat(mapped).isNull() + } + + // Name lookup caching and logging + + @Test + fun `looks up each @Serializable type once, including failed lookups`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Home) + mapper.map(Detail("$it")) + mapper.map(Generic("$it")) + } + + assertThat(fixture.lookedUpTypes) + .containsExactly(Home::class.java, Detail::class.java, Generic::class.java) + } + + @Test + fun `never looks up types that aren't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(NotSerializable("$it")) + mapper.map("home") + mapper.map(42) + mapper.map(UnannotatedTab.FEED) + } + + assertThat(fixture.lookedUpTypes).isEmpty() + } + + @Test + fun `looks up an enum that has bodies once for all its constants`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + mapper.map(TabWithBodies.FEED) + mapper.map(TabWithBodies.SEARCH) + + assertThat(fixture.lookedUpTypes).containsExactly(TabWithBodies::class.java) + } + + @Test + fun `logs a warning once per type that isn't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(NotSerializable("$it")) + mapper.map("home") + mapper.map(UnannotatedTab.FEED) + mapper.map(Home) + } + + verifyNotSerializableLoggedOnce(fixture, NotSerializable::class.java) + verifyNotSerializableLoggedOnce(fixture, String::class.java) + verifyNotSerializableLoggedOnce(fixture, UnannotatedTab::class.java) + verify(fixture.logger, never()).log(any(), any(), eq(Home::class.java.name)) + } + + @Test + fun `logs a warning once per @Serializable type whose serializer can't be found`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { if (it == Detail::class.java) null else fixture.serializers[it] } + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail("$it")) + mapper.map(Home) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + isNull(), + any(), + eq(Detail::class.java.name), + eq(SERIALIZER_NOT_FOUND), + ) + verify(fixture.logger, never()) + .log(any(), anyOrNull(), any(), eq(Home::class.java.name), any()) + } + + @Test + fun `advises making the type @Serializable when a type that isn't @Serializable can't be named`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + mapper.map(NotSerializable("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log(eq(SentryLevel.WARNING), message.capture(), eq(NotSerializable::class.java.name)) + assertThat(message.firstValue).contains("Add @Serializable") + } + + @Test + fun `advises seeing the docs when a @Serializable type's serializer can't be found`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { null } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + isNull(), + message.capture(), + eq(Detail::class.java.name), + eq(SERIALIZER_NOT_FOUND), + ) + assertThat(message.firstValue).contains("See BackStackEntryMapper.SerialName's documentation") + assertThat(message.firstValue).doesNotContain("Add @Serializable") + } + + @Test + fun `advises seeing the attached error without compatibility advice when a type's name lookup throws an exception`() { + val error = IllegalStateException("lookup failed") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + eq(error), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_ERROR), + ) + assertThat(message.firstValue).contains("See the attached error") + assertThat(message.firstValue).doesNotContain(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `advises checking kotlinx compatibility when a type's name lookup throws a LinkageError`() { + val error = NoSuchMethodError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + eq(error), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_ERROR), + ) + assertThat(message.firstValue).contains("See the attached error") + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + // Serializer lookup errors that only affect one type + + @Test + fun `returns null and logs the error once for a type whose name lookup throws a LinkageError`() { + val error = NoSuchMethodError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `doesn't look up a type again after its name lookup throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw NoSuchMethodError() } + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java) + } + + @Test + fun `keeps naming other types after a type's name lookup throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == Detail::class.java) throw NoSuchMethodError() else fixture.serializers[it] + } + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home), mapper.map(Search("shoes"))) + + assertThat(mapped) + .containsExactly(null, SentryBackStackEntry("Home"), SentryBackStackEntry("Search")) + .inOrder() + } + + @Test + fun `returns null and logs the error once for a type whose name lookup throws ReflectiveOperationException`() { + val error = NoSuchMethodException("serializer") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `returns null and logs the error once for a type whose name lookup throws an unchecked exception`() { + val error = TypeNotPresentException("com.example.RemovedSerializer", null) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `doesn't look up a type again after its name lookup throws an unchecked exception`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { error("lookup failed") } + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java) + } + + @Test + fun `keeps naming other types after a type's name lookup throws an unchecked exception`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == Detail::class.java) error("lookup failed") else fixture.serializers[it] + } + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home)) + + assertThat(mapped).containsExactly(null, SentryBackStackEntry("Home")).inOrder() + } + + @Test + fun `restores the interrupt status when a type's name lookup throws InterruptedException`() { + val error = InterruptedException() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + try { + assertThat(mapper.map(Detail("1"))).isNull() + assertThat(Thread.currentThread().isInterrupted).isTrue() + verifyLookUpErrorLoggedOnce(fixture, error) + } finally { + Thread.interrupted() + } + } + + @Test + fun `propagates fatal errors a name lookup throws`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer lookup errors wrapped in an InvocationTargetException + + @Test + fun `returns null and logs the cause once for a type whose name lookup throws a wrapped exception`() { + val cause = IllegalStateException("serializer() failed") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(cause) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, cause) + } + + @Test + fun `returns null and logs the cause once when a name lookup throws a wrapped ExceptionInInitializerError`() { + val cause = ExceptionInInitializerError(IllegalStateException("serializer init failed")) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(cause) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, cause) + } + + @Test + fun `keeps naming other types after a type's name lookup throws a wrapped LinkageError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == Detail::class.java) throw InvocationTargetException(NoSuchMethodError()) + else fixture.serializers[it] + } + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home)) + + assertThat(mapped).containsExactly(null, SentryBackStackEntry("Home")).inOrder() + } + + @Test + fun `returns null and logs the InvocationTargetException once when a name lookup throws one without a cause`() { + val error = InvocationTargetException(null) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `restores the interrupt status when a type's name lookup throws a wrapped InterruptedException`() { + val error = InterruptedException() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(error) } + val mapper = fixture.mapper + + try { + assertThat(mapper.map(Detail("1"))).isNull() + assertThat(Thread.currentThread().isInterrupted).isTrue() + verifyLookUpErrorLoggedOnce(fixture, error) + } finally { + Thread.interrupted() + } + } + + @Test + fun `propagates fatal errors a name lookup throws wrapped in an InvocationTargetException`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(error) } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer descriptors that throw + + @Test + fun `returns null without looking up again for a type whose serializer's descriptor throws`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { DescriptorThrowsIllegalStateSerializer } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(DescriptorThrowsIllegalState()) } + + assertThat(mapped).containsExactly(null, null, null) + assertThat(fixture.lookedUpTypes).containsExactly(DescriptorThrowsIllegalState::class.java) + } + + @Test + fun `logs the error once for a type whose serializer's descriptor throws`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { DescriptorThrowsIllegalStateSerializer } + val mapper = fixture.mapper + + repeat(3) { mapper.map(DescriptorThrowsIllegalState()) } + + verifyLookUpErrorLoggedOnce( + fixture, + DescriptorThrowsIllegalStateSerializer.error, + DescriptorThrowsIllegalState::class.java, + ) + } + + @Test + fun `keeps naming other types after a type's serializer's descriptor throws AbstractMethodError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == DescriptorThrowsAbstractMethodError::class.java) { + DescriptorThrowsAbstractMethodErrorSerializer + } else { + fixture.serializers[it] + } + } + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(DescriptorThrowsAbstractMethodError()), mapper.map(Home)) + + assertThat(mapped).containsExactly(null, SentryBackStackEntry("Home")).inOrder() + } + + @Test + fun `returns null and logs the error once for a type whose serializer's descriptor throws NoClassDefFoundError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { DescriptorThrowsNoClassDefFoundErrorSerializer } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(DescriptorThrowsNoClassDefFoundError()) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce( + fixture, + DescriptorThrowsNoClassDefFoundErrorSerializer.error, + DescriptorThrowsNoClassDefFoundError::class.java, + ) + } + + @Test + fun `propagates fatal errors thrown by a serializer's descriptor`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + object : NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = throw error + } + } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer descriptors whose shape throws + + @Test + fun `names an entry after its SerialName without reading its descriptor's shape`() { + val serializer = ShapeThrowingDetailSerializer() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { serializer } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(serializer.shapeReads).isEqualTo(0) + } + + // Integration: serializer initializers that throw through real reflection + // + // Unlike the tests above, these use the mapper's default serializer lookup and its real + // reflection, to check that the mapper handles the errors it actually throws. + + @Test + fun `returns null without looking up again for a type whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create() + // Wraps the default lookup, rather than using it directly, so that lookedUpTypes records each + // lookup. + fixture.lookUp = { reflectiveSerializerOrNull(it) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(UninitializableSerializedA()) } + + assertThat(mapped).containsExactly(null, null, null) + assertThat(fixture.lookedUpTypes).containsExactly(UninitializableSerializedA::class.java) + } + + @Test + fun `logs the initializer error once for a type whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + repeat(3) { mapper.map(UninitializableSerializedB()) } + + val logged = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + logged.capture(), + any(), + eq(UninitializableSerializedB::class.java.name), + eq(LOOK_UP_ERROR), + ) + assertThat(logged.firstValue).isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(logged.firstValue) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("serializer B init failed") + } + + @Test + fun `logs the initializer error once for a private object whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(PrivateUninitializable) } + + assertThat(mapped).containsExactly(null, null, null) + val logged = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + logged.capture(), + any(), + eq(PrivateUninitializable::class.java.name), + eq(LOOK_UP_ERROR), + ) + assertThat(logged.firstValue).isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(logged.firstValue) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("serializer C init failed") + } + + private fun verifyLookUpErrorLoggedOnce( + fixture: KotlinxMapperFixture, + error: Throwable, + type: Class<*> = Detail::class.java, + ) { + verify(fixture.logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(type.name), eq(LOOK_UP_ERROR)) + } + + private fun verifyNotSerializableLoggedOnce(fixture: KotlinxMapperFixture, type: Class<*>) { + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + argThat { contains(NOT_SERIALIZABLE) }, + eq(type.name), + ) + } + + private companion object { + val TEST_CLASS: String = KotlinxBackStackEntryMapperNamingTest::class.java.name + + const val NOT_SERIALIZABLE = "because the type is not @Serializable" + + const val SERIALIZER_NOT_FOUND = + "no serializer was found (the type may be generic or require R8 keep rules)" + + const val LOOK_UP_ERROR = "reading its annotations, serializer, or descriptor failed" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt new file mode 100644 index 00000000000..8703282b6fc --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt @@ -0,0 +1,115 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.FakeCompatibilityProbe.Inconclusive +import kotlin.test.assertFailsWith +import org.junit.Test +import org.mockito.kotlin.argThat +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions + +/** How [KotlinxBackStackEntryMapper] acts on what its [KotlinxCompatibilityProbe] finds. */ +class KotlinxBackStackEntryMapperProbeTest { + + // Name lookup check + + @Test + fun `logs nothing when created for a kotlinx version the name lookup check finds compatible`() { + val fixture = KotlinxMapperFixture.create(probe = FakeCompatibilityProbe()) + + fixture.mapper + + verifyNoInteractions(fixture.logger) + } + + @Test + fun `throws the probe's LinkageError when created for a kotlinx version that can't support name lookups`() { + val error = NoSuchMethodError("serializerOrNull") + val probe = FakeCompatibilityProbe(nameLookupError = error) + + val thrown = + assertFailsWith { + KotlinxBackStackEntryMapper(logger = { mock() }, probe = probe) + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `doesn't log when created for a kotlinx version that can't support name lookups`() { + // BuiltInBackStackEntryMappers logs the error it catches, so the mapper doesn't log it too. + val logger = mock() + val probe = FakeCompatibilityProbe(nameLookupError = NoSuchMethodError()) + + assertFailsWith { + KotlinxBackStackEntryMapper(logger = { logger }, probe = probe) + } + + verifyNoInteractions(logger) + } + + @Test + fun `names entries when the name lookup check is inconclusive`() { + val probe = + FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(IllegalStateException())) + val fixture = KotlinxMapperFixture.create(probe = probe) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + } + + @Test + fun `logs at debug level with the error when the name lookup check throws inconclusively`() { + val error = IllegalStateException("check failed") + val probe = FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(error)) + + val fixture = KotlinxMapperFixture.create(probe = probe) + + val message = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.DEBUG), + eq(error), + message.capture(), + eq(NAME_LOOKUP_CAPABILITY), + eq(PROBE_THREW), + ) + assertThat(message.firstValue).startsWith(INCONCLUSIVE_PROBE) + } + + @Test + fun `logs at debug level when the name lookup check can't find a probe type's serializer`() { + val probe = FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(error = null)) + + val fixture = KotlinxMapperFixture.create(probe = probe) + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.DEBUG), + isNull(), + argThat { startsWith(INCONCLUSIVE_PROBE) }, + eq(NAME_LOOKUP_CAPABILITY), + eq(PROBE_SERIALIZER_NOT_FOUND), + ) + } + + private companion object { + const val NAME_LOOKUP_CAPABILITY = "name lookups" + + const val INCONCLUSIVE_PROBE = "Nav3 couldn't verify kotlinx.serialization support for %s" + + const val PROBE_THREW = "the compatibility probe threw (see the attached error)" + + const val PROBE_SERIALIZER_NOT_FOUND = "a probe serializer wasn't found" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt new file mode 100644 index 00000000000..b7fe764f3c1 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt @@ -0,0 +1,40 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.Companion.ProbeClass +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.Companion.ProbeObject +import org.junit.Test + +/** + * Runs the default probe against the kotlinx.serialization version on the test classpath, which CI + * also sets to the latest version with `-Pnav3TestKotlinxVersion`. + */ +class KotlinxCompatibilityProbeTest { + + // nameLookupLinkageError() + + @Test + fun `nameLookupLinkageError() - returns null for a compatible kotlinx serialization version conclusively`() { + val inconclusive = mutableListOf() + + val error = KotlinxCompatibilityProbe.nameLookupLinkageError { inconclusive += it } + + assertThat(error).isNull() + assertThat(inconclusive).isEmpty() + } + + // Probe types + + @Test + fun `the serializer lookup names the probe's types`() { + // A probe type the lookup couldn't find would make the check pass without looking up a name. + val names = + listOf(ProbeClass::class.java, ProbeObject::class.java).map { + reflectiveSerializerOrNull(it)?.descriptor?.serialName + } + + assertThat(names) + .containsExactly(ProbeClass::class.qualifiedName, ProbeObject::class.qualifiedName) + .inOrder() + } +} 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..36e09db8eca --- /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.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentSink +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +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 = TreeArgumentWriter(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/KotlinxMapperFixture.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt new file mode 100644 index 00000000000..1d0f853c8d8 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt @@ -0,0 +1,169 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.ILogger +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.ArgumentSource +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +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 + +/** + * 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) + } +} + +/** + * 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() +} + +/** + * A [KotlinxCompatibilityProbe] that finds the app's kotlinx.serialization version compatible + * unless [nameLookupError] or [encodingError] is set, so that mapper tests don't depend on the real + * probe. Reports the name check inconclusive with [nameLookupInconclusive], if set, and the + * encoding check inconclusive with [encodingInconclusiveError], if set. Counts the checks of the + * properties encoder in [encodingChecks]. + */ +internal class FakeCompatibilityProbe( + private val nameLookupError: LinkageError? = null, + private val nameLookupInconclusive: Inconclusive? = null, +) : KotlinxCompatibilityProbe { + + override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? { + nameLookupError?.let { + return it + } + nameLookupInconclusive?.let { onInconclusive(it.error) } + return null + } + + /** Why the name check is inconclusive: [error], or `null` if a probe serializer wasn't found. */ + class Inconclusive(val error: Throwable?) +} + +/** + * A [KotlinxBackStackEntryMapper] whose serializer lookup returns [serializers] by default. The + * mapper only looks up `@Serializable` types, so [lookUp] never sees any others. Its compatibility + * [probe] finds 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( + useDefaultLookUp: Boolean, + val probe: KotlinxCompatibilityProbe, +) { + 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(logger = { logger }, probe = probe) + } else { + KotlinxBackStackEntryMapper( + lookUpSerializer = { + lookedUpTypes += it + lookUp(it) + }, + logger = { logger }, + probe = probe, + ) + } + + companion object { + fun create( + useDefaultLookUp: Boolean = false, + probe: KotlinxCompatibilityProbe = FakeCompatibilityProbe(), + ) = KotlinxMapperFixture(useDefaultLookUp, probe) + } +} + +/** 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) + +/** Maps [entry] and reads its arguments, which encodes its properties. */ +internal fun KotlinxBackStackEntryMapper.mapAndReadArguments(entry: Any): SentryBackStackEntry? = + map(entry)?.also { it.arguments?.size } + +/** + * Maps [entry] and writes its arguments to a sink with a budget of its own, as the argument + * sanitizer does, which encodes its properties. Ignores the [DropArguments] a failure throws. + */ +internal fun KotlinxBackStackEntryMapper.mapAndWriteArguments(entry: Any) { + val arguments = map(entry)?.arguments as ArgumentSource + try { + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + } catch (_: DropArguments) {} +} 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..6f3fa0c41ea --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt @@ -0,0 +1,516 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments +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) + } + + @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() - 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..ea2bafa11b5 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt @@ -0,0 +1,422 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import io.sentry.compose.navigation3.internal.backstack.budgetWithValuesRemaining +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 [DropArguments], records it and + * encodes a fallback with [recover] instead. + */ + internal class RecoveringLinkSerializer(private val recover: (Encoder) -> Unit) : + KSerializer { + var caught: DropArguments? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.RecoveringLink", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + try { + encoder.encodeSerializableValue(LinkSerializer, value) + } catch (e: DropArguments) { + 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 [DropArguments] that throws in [caught], then encodes a fallback + * with [fallback]. + */ + private class CatchingWriteSerializer(private val fallback: KSerializer) : + KSerializer { + var caught: DropArguments? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.CatchingWrite", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Code) { + try { + encoder.encodeString(value.code) + } catch (e: DropArguments) { + 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(DropArguments.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(DropArguments.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(DropArguments.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(DropArguments.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(DropArguments.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(DropArguments.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(DropArguments.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(DropArguments.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(DropArguments.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(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - records the nesting failure on the sink`() { + val sink = TreeArgumentWriter(ArgumentBudget()) + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) + + val exception = assertFailsWith { encodeInto(LinkSerializer, entry, sink) } + + assertThat(sink.failure).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(DropArguments.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(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - keeps the nesting failure on the sink when a serializer catches it and returns`() { + val sink = TreeArgumentWriter(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 = TreeArgumentWriter(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) + assertThat(sink.failure).isSameInstanceAs(serializer.caught) + assertThat(sink.failure?.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 = TreeArgumentWriter(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..0fe2cfe5479 --- /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.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments +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/KotlinxSerializerLookupTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt new file mode 100644 index 00000000000..0c0f61ba8c3 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt @@ -0,0 +1,289 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import java.lang.reflect.InvocationTargetException +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Assert.assertThrows +import org.junit.Test + +class KotlinxSerializerLookupTest { + + @Serializable @SerialName("Detail") data class Detail(val id: String) + + @Serializable @SerialName("Home") data object Home + + @Serializable + @SerialName("Route") + sealed interface Route { + @Serializable @SerialName("route.settings") data object Settings : Route + } + + @Serializable + @SerialName("Tab") + enum class Tab { + FEED, + } + + @Serializable + @SerialName("TabWithBodies") + enum class TabWithBodies { + FEED { + override val icon = "feed" + }; + + abstract val icon: String + } + + @Serializable(with = CustomSerializer::class) internal data class CustomSerialized(val id: String) + + internal object CustomSerializer : NamingOnlySerializer() { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + } + + @Serializable @SerialName("PrivateObject") private data object PrivateObject + + @Serializable @SerialName("PrivateClass") private data class PrivateClass(val id: String) + + data class NotSerializable(val id: String) + + /** + * Looks like a private object to kotlinx.serialization, as it has a private static `INSTANCE` + * field of its own type, but lacks the `serializer()` method the compiler plugin generates. + */ + class InaccessibleInstanceWithoutSerializer private constructor() { + private companion object { + @Suppress("unused") private val INSTANCE = InaccessibleInstanceWithoutSerializer() + } + } + + enum class UnannotatedTab { + FEED, + } + + @Serializable data class Generic(val value: T) + + // A class whose serializer's initializer threw can't be initialized again for the rest of the + // JVM's life, so each test that triggers one gets its own pair, separate from other suites'. + + @Serializable(with = UninitializableSerializer::class) internal class Uninitializable + + internal object UninitializableSerializer : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable", PrimitiveKind.STRING) + } + + @Serializable(with = IncompatiblyUninitializableSerializer::class) + internal class IncompatiblyUninitializable + + internal object IncompatiblyUninitializableSerializer : + NamingOnlySerializer() { + init { + // As for FatallyUninitializableSerializer, the error isn't wrapped in an + // ExceptionInInitializerError. + if (System.nanoTime() != 0L) throw NoSuchMethodError("serializer init failed to link") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("incompatible", PrimitiveKind.STRING) + } + + @Serializable(with = PrivateUninitializableSerializer::class) + private object PrivateUninitializable + + private object PrivateUninitializableSerializer : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("private serializer init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("private.uninitializable", PrimitiveKind.STRING) + } + + @Serializable(with = FatallyUninitializableSerializer::class) private object PrivateFatal + + private object FatallyUninitializableSerializer : NamingOnlySerializer() { + init { + // Unlike an exception, an error thrown by an initializer isn't wrapped in an + // ExceptionInInitializerError. + if (System.nanoTime() != 0L) throw OutOfMemoryError("serializer init failed fatally") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("fatal", PrimitiveKind.STRING) + } + + // @Serializable types + + @Test + fun `returns the serializer of a @Serializable class`() { + val serializer = reflectiveSerializerOrNull(Detail::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Detail") + } + + @Test + fun `returns the serializer of a @Serializable object`() { + val serializer = reflectiveSerializerOrNull(Home::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Home") + } + + @Test + fun `returns the subtype's own serializer for a @Serializable sealed subtype`() { + val serializer = reflectiveSerializerOrNull(Route.Settings::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("route.settings") + } + + @Test + fun `returns the serializer of a @Serializable enum`() { + val serializer = reflectiveSerializerOrNull(Tab::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Tab") + } + + @Test + fun `returns the custom serializer of a class that is @Serializable with a custom serializer`() { + val serializer = reflectiveSerializerOrNull(CustomSerialized::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("custom.Name") + } + + @Test + fun `returns the serializer of a private @Serializable object`() { + val serializer = reflectiveSerializerOrNull(PrivateObject::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateObject") + } + + @Test + fun `returns the serializer of a private @Serializable class`() { + val serializer = reflectiveSerializerOrNull(PrivateClass::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateClass") + } + + // Types that aren't @Serializable but that kotlinx serialization can serialize + + @Test + fun `returns kotlinx serialization's serializers for built-in types`() { + val types = listOf(String::class.java, Integer::class.java) + + val serialNames = types.map { reflectiveSerializerOrNull(it)?.descriptor?.serialName } + + assertThat(serialNames).containsExactly("kotlin.String", "kotlin.Int").inOrder() + } + + @Test + fun `returns kotlinx serialization's enum serializer for an enum that isn't @Serializable`() { + val serializer = reflectiveSerializerOrNull(UnannotatedTab::class.java) + + assertThat(serializer?.descriptor?.serialName) + .isEqualTo(UnannotatedTab::class.java.canonicalName) + } + + // Types without a serializer to return + + @Test + fun `returns null for a class that isn't @Serializable`() { + val serializer = reflectiveSerializerOrNull(NotSerializable::class.java) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for the class of a @Serializable enum's constant that has a body`() { + val serializer = reflectiveSerializerOrNull(TabWithBodies.FEED.javaClass) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for a generic @Serializable class`() { + val serializer = reflectiveSerializerOrNull(Generic::class.java) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for a generic built-in collection type`() { + val serializer = reflectiveSerializerOrNull(ArrayList::class.java) + + assertThat(serializer).isNull() + } + + // Serializer initializers that throw + + @Test + fun `throws a class's serializer initializer error wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(Uninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .isEqualTo("serializer init failed") + } + + @Test + fun `throws a class's serializer initializer NoSuchMethodError wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(IncompatiblyUninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(NoSuchMethodError::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed to link") + } + + @Test + fun `throws a private object's serializer initializer error wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(PrivateUninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .isEqualTo("private serializer init failed") + } + + @Test + fun `throws a private object's fatal serializer initializer error wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(PrivateFatal::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed fatally") + } + + // Private object lookups that fail + + @Test + fun `throws the reflection error when a type with an inaccessible INSTANCE field has no serializer method`() { + val thrown = + assertThrows(NoSuchMethodException::class.java) { + reflectiveSerializerOrNull(InaccessibleInstanceWithoutSerializer::class.java) + } + + assertThat(thrown).hasMessageThat().contains("serializer") + } +} 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 new file mode 100644 index 00000000000..c912d881bb2 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -0,0 +1,87 @@ +@file:Suppress("MatchingDeclarationName") + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +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 + +@Serializable @SerialName("Home") internal data object Home + +@Serializable @SerialName("Detail") internal data class Detail(val id: String) + +@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 +} 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..2c5518f5d77 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt @@ -0,0 +1,326 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import io.sentry.compose.navigation3.internal.backstack.budgetWithValuesRemaining +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxPropertiesEncoder.SensitiveKeyFilter +import io.sentry.util.UrlUtils.SENSITIVE_DATA_SUBSTITUTE +import kotlin.test.assertFailsWith +import org.junit.Test + +class SensitiveKeyFilterTest { + + private val sink = TreeArgumentWriter(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")))) + } + + // 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"), + ), + ) + } + + // Computed scalars + + @Test + fun `computedScalar() - writes the computed value under a non-sensitive key`() { + filter.key("query") + filter.computedScalar { "shoes" } + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("query" to "shoes")) + } + + @Test + fun `computedScalar() - writes the substitute under a sensitive key without computing the value`() { + var computed = false + + filter.key("password") + filter.computedScalar { + computed = true + "hunter2" + } + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("password" to SENSITIVE_DATA_SUBSTITUTE)) + assertThat(computed).isFalse() + } + + @Test + fun `computedScalar() - writes nothing and doesn't compute the value in a map under a sensitive key`() { + var computed = false + + filter.key("credentials") + filter.beginMap() + filter.key("user") + filter.computedScalar { + computed = true + "alice" + } + filter.end() + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("credentials" to SENSITIVE_DATA_SUBSTITUTE)) + assertThat(computed).isFalse() + } + + @Test + fun `computedScalar() - resets sensitivity for the next value after writing a filtered value`() { + filter.key("rows") + filter.beginList() + filter.beginMap() + filter.key("jwt") + filter.computedScalar { "t-1" } + filter.end() + filter.computedScalar { "plain" } + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo(mapOf("rows" to listOf(mapOf("jwt" to SENSITIVE_DATA_SUBSTITUTE), "plain"))) + } + + @Test + fun `computedScalar() - throws the sink's broken limit without computing the value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + val limitedFilter = SensitiveKeyFilter(limitedSink) + var computed = false + limitedFilter.key("query") + + val thrown = + assertFailsWith { + limitedFilter.computedScalar { + computed = true + "shoes" + } + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(computed).isFalse() + } + + // Maps + + @Test + fun `beginMap() - writes the substitute in place of a map under a sensitive key`() { + filter.key("credentials") + filter.beginMap() + filter.key("user") + filter.scalar("alice") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("credentials" to SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `beginMap() - discards the nested maps, lists, and keys of a map under a sensitive key`() { + filter.key("credentials") + filter.beginMap() + filter.key("history") + filter.beginList() + filter.beginMap() + filter.key("user") + filter.scalar("alice") + filter.end() + filter.end() + filter.key("note") + filter.scalar("visible?") + filter.end() + filter.key("page") + filter.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("credentials" to SENSITIVE_DATA_SUBSTITUTE, "page" to 2)) + } + + @Test + fun `beginMap() - passes the map's identity to the sink`() { + val map = Any() + filter.key("filters") + filter.beginMap(map) + filter.key("nested") + + val drop = assertFailsWith { filter.beginMap(map) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + // Lists + + @Test + fun `beginList() - writes the substitute in place of a list under a sensitive key`() { + filter.key("refreshTokens") + filter.beginList() + filter.scalar("t-1") + filter.scalar("t-2") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("refreshTokens" to SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `beginList() - passes the list's identity to the sink`() { + val list = Any() + filter.key("rows") + filter.beginList(list) + + val drop = assertFailsWith { filter.beginList(list) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + // Ends of maps and lists + + @Test + fun `end() - resumes writing the containing map after a discarded map ends`() { + filter.key("filters") + filter.beginMap() + filter.key("token") + filter.beginMap() + filter.key("value") + filter.scalar("t-1") + filter.end() + filter.key("color") + filter.scalar("red") + filter.end() + filter.key("page") + filter.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf( + "filters" to mapOf("token" to SENSITIVE_DATA_SUBSTITUTE, "color" to "red"), + "page" to 2, + ), + ) + } + + @Test + fun `end() - writes a map under a non-sensitive key that follows a discarded map`() { + filter.key("password") + filter.beginMap() + filter.end() + 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, DropArguments.STRUCTURE_WARNING) + } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `reject() - rejects the limit on the sink within a map under a sensitive key`() { + // The filter discards writes under a sensitive key, but not limits a source rejects. + filter.key("credentials") + filter.beginMap() + + val drop = + assertFailsWith { + filter.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + + assertThat(sink.failure).isSameInstanceAs(drop) + } +} diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 8dd75b41add..f351bae3abd 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -8025,6 +8025,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)) { diff --git a/settings.gradle.kts b/settings.gradle.kts index 18340a6c241..897227ad444 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -38,6 +38,11 @@ dependencyResolutionManagement { mavenCentral() mavenLocal() } + versionCatalogs { + create("nav3Libs") { + from(files("gradle/nav3.versions.toml")) + } + } } rootProject.name = "sentry-root"