From 0e209b02bac44cdada81740de25a81faabbb3d18 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 11:54:07 +0100 Subject: [PATCH] feat(nav3): Add the built-in SerialNameAndProperties mapper Add BackStackEntryMapper.SerialNameAndProperties, which names entries as SerialName does and also records each entry's kotlinx.serialization properties as arguments, through KotlinxArgumentSource. Creating the mapper checks that the properties encoder works with the app's kotlinx.serialization version by encoding a known value with built-in serializers, as the name check does, and comparing the output with its known encoding. Any failure or mismatch keeps entry names but drops every entry's arguments with encoding_failed, since recording wrong arguments is worse than recording none. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + sentry-android-navigation3/README.md | 3 +- .../api/sentry-android-navigation3.api | 1 + sentry-android-navigation3/proguard-rules.pro | 5 +- .../navigation3/BackStackEntryMapper.kt | 78 ++- .../backstack/BuiltInBackStackEntryMappers.kt | 18 +- .../kotlinx/KotlinxBackStackEntryMapper.kt | 236 +++++++- .../kotlinx/KotlinxCompatibilityCheck.kt | 109 +++- .../kotlinx/KotlinxSerializerLookup.kt | 17 +- .../internal/backstack/kotlinx/README.md | 3 +- .../navigation3/BackStackEntryMapperTest.kt | 7 + .../navigation3/SentryNavEffectTest.kt | 152 ++++++ .../BuiltInBackStackEntryMappersTest.kt | 61 +++ ...rialNameAndPropertiesArgumentLimitsTest.kt | 152 ++++++ .../SerialNameAndPropertiesParityTest.kt | 406 ++++++++++++++ ...inxBackStackEntryMapperEncoderCheckTest.kt | 138 +++++ ...tlinxBackStackEntryMapperPropertiesTest.kt | 503 ++++++++++++++++++ .../KotlinxBackStackEntryMapperTest.kt | 10 +- .../kotlinx/KotlinxCompatibilityCheckTest.kt | 75 +++ .../kotlinx/KotlinxMapperDiagnosticsTest.kt | 155 ++++++ .../backstack/kotlinx/KotlinxMapperFixture.kt | 147 +++++ 21 files changed, 2238 insertions(+), 39 deletions(-) create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesArgumentLimitsTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesParityTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperEncoderCheckTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 9868074937a..bba6668cecf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Features - Nav3: Add `BackStackEntryMapper.SerialName`, a convenience mapper that names back stack entries after their [serial names](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-serial-descriptor/serial-name.html) ([#6703](https://github.com/getsentry/sentry-java/pull/6703)) +- Nav3: Add `BackStackEntryMapper.SerialNameAndProperties`, which is like `SerialName` except that it also records the properties of each back stack entry as arguments ([#6706](https://github.com/getsentry/sentry-java/pull/6706)) ### Improvements diff --git a/sentry-android-navigation3/README.md b/sentry-android-navigation3/README.md index 5b80d74bd91..a65903b80b5 100644 --- a/sentry-android-navigation3/README.md +++ b/sentry-android-navigation3/README.md @@ -9,7 +9,8 @@ This module requires Nav3. It doesn't declare its own dependencies on Compose, l your Nav3 dependency brings in. Because Nav3 back stacks can have arbitrary key types, host apps need to provide `SentryNavEffect` with a mapping between their back stack -keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` mapper). +keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` and `SerialNameAndProperties` +mappers). See the [Navigation for Android docs](https://docs.sentry.io/platforms/android/integrations/navigation/) for additional details, including configuration, supported setups, and limitations. diff --git a/sentry-android-navigation3/api/sentry-android-navigation3.api b/sentry-android-navigation3/api/sentry-android-navigation3.api index 04c3349cd46..04a7ba34aac 100644 --- a/sentry-android-navigation3/api/sentry-android-navigation3.api +++ b/sentry-android-navigation3/api/sentry-android-navigation3.api @@ -5,6 +5,7 @@ public abstract interface class io/sentry/compose/navigation3/BackStackEntryMapp public final class io/sentry/compose/navigation3/BackStackEntryMapper$Companion { public final fun getSerialName ()Lio/sentry/compose/navigation3/BackStackEntryMapper; + public final fun getSerialNameAndProperties ()Lio/sentry/compose/navigation3/BackStackEntryMapper; } public final class io/sentry/compose/navigation3/BuildConfig { diff --git a/sentry-android-navigation3/proguard-rules.pro b/sentry-android-navigation3/proguard-rules.pro index b34c23cc870..971f668a7ec 100644 --- a/sentry-android-navigation3/proguard-rules.pro +++ b/sentry-android-navigation3/proguard-rules.pro @@ -8,8 +8,9 @@ ##---------------Begin: proguard configuration for kotlinx.serialization ---------- -# Serial names survive R8 minification because Kotlin's serialization compiler plugin fixes them at compile time. Our built-in mapper -# fallback for private `@Serializable` objects relies on members preserved by kotlinx.serialization's own consumer rules. +# Serial names, including the property names `SerialNameAndProperties` records as argument keys, survive R8 minification because Kotlin's +# serialization compiler plugin fixes them at compile time. Our built-in mappers' fallback for private `@Serializable` objects relies on +# members preserved by kotlinx.serialization's own consumer rules. # We don't ship rules for `@Serializable` classes with named companion objects. kotlinx.serialization's rules cover them but only from # 1.10.0 on. A generic rule set that fixes older versions exists, but we don't apply it because it would keep `InnerClasses` and diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index c24ed39db13..cb9ef4ff237 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt @@ -6,7 +6,8 @@ import org.jetbrains.annotations.ApiStatus /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * See [SerialName] for an out-of-the-box mapper, or else provide your own. + * See [SerialName] and [SerialNameAndProperties] for out-of-the-box mappers, or else provide your + * own. * * **Privacy / PII** * @@ -14,6 +15,10 @@ import org.jetbrains.annotations.ApiStatus * personal information. Only return names and arguments that are known to be safe or have been * pre-scrubbed. * + * Neither `sendDefaultPii` nor the `dataCollection` options change what any mapper returns. + * `SerialNameAndProperties` filters only a limited set of secrets; see its documentation for + * details. + * * **Performance** * * Mappers are invoked synchronously from [SentryNavEffect] on the same apply thread that runs the @@ -93,7 +98,7 @@ import org.jetbrains.annotations.ApiStatus * ) * * // Consider falling back to a built-in mapper for the rest. - * else -> BackStackEntryMapper.SerialName.map(entry) + * else -> BackStackEntryMapper.SerialNameAndProperties.map(entry) * } * } * ``` @@ -125,7 +130,8 @@ public fun interface BackStackEntryMapper { * ``` * * this mapper returns `"ProductDetailScreen"` for `ProductDetail(productId = "zyx987")` but - * omits the destination's properties (`productId`). + * omits the destination's properties (`productId`). (To return arguments too, see + * [SerialNameAndProperties].) * * **Name == SerialDescriptor.serialName** * @@ -142,7 +148,8 @@ public fun interface BackStackEntryMapper { * particular: * * - All constants of an enum share the enum class's serial name, regardless of any - * `@SerialName` on the constants. + * `@SerialName` on the constants. (A constant's `@SerialName` only changes how + * [SerialNameAndProperties] records it as an argument.) * * - Classes that share a custom serializer (`@Serializable(with = ...)`) share its descriptor's * serial name, regardless of any `@SerialName` on the classes. @@ -158,12 +165,69 @@ public fun interface BackStackEntryMapper { * Sentry displays `null` entries as "/unknown" with an `unknown_entry_reason`. With SDK * debugging enabled, the first unnamed entry of each class also logs a warning. * - * See the - * [Troubleshooting Guide](https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers) - * for more details. + * See the discussion of + * [Unknown Destination Names](https://docs.sentry.io/platforms/android/integrations/navigation/#unknown-destination-names) + * in the Sentry Android Navigation docs for more details. */ public val SerialName: BackStackEntryMapper get() = BuiltInBackStackEntryMappers.serialName + + /** + * Like [SerialName], but also returns the properties that each back stack entry's serializer + * encodes, as Sentry arguments. + * + * For instance, given: + * ``` + * @Serializable + * @SerialName("ProductDetailScreen") + * data class ProductDetail(val userId: String, val productId: String) : NavKey + * ``` + * + * this mapper returns `"ProductDetailScreen"` for `ProductDetail(userId = "123abc", productId = + * "zyx987")`, along with these arguments: + * ```json + * { + * "userId": "123abc", + * "productId": "zyx987" + * } + * ``` + * + * Entry names follow the rules for [SerialName]. Entries that can't be named are recorded as + * "/unknown" with an `unknown_entry_reason`. They're returned without arguments, since their + * inability to be named means they have no usable serializer. The argument limits described in + * [BackStackEntryMapper] apply. + * + * **Privacy / PII** + * + * This mapper returns every property that each back stack entry's serializer encodes, which may + * include private data and PII. Properties the serializer doesn't encode (e.g., `@Transient` + * ones) aren't returned. Apart from the limited filtering of secrets described below, + * properties are sent as-is. + * + * If an entry contains data that shouldn't be sent to Sentry, either filter that property out + * of this mapper's arguments, or use a custom [BackStackEntryMapper] that special-cases the + * entry and falls back to this mapper (or [SerialName]) for the rest. See + * [Choosing Which Arguments to Send](https://docs.sentry.io/platforms/android/integrations/navigation/#choosing-which-arguments-to-send) + * for examples. + * + * **Limited filtering of secrets** + * + * If a property's + * [serial name](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-serial-descriptor/serial-name.html) + * or map key contains a term from + * [Sentry's sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist) + * (ignoring case), then its value will be replaced with `"[Filtered]"`. See + * [Choosing Which Arguments to Send](https://docs.sentry.io/platforms/android/integrations/navigation/#choosing-which-arguments-to-send) + * for more details. + * + * **Argument encoding failures** + * + * Argument encoding failures preserve the entry's name and replace its arguments with a drop + * reason, e.g., `{"dropped_by_sentry": "encoding_failed"}`. With `debug` enabled, the first + * failure of each kind for each entry type also logs a warning. + */ + public val SerialNameAndProperties: BackStackEntryMapper + get() = BuiltInBackStackEntryMappers.serialNameAndProperties } } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt index 3fd1247a200..d359e7e4a47 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -23,7 +23,8 @@ internal object BuiltInBackStackEntryMappers { * A built-in [BackStackEntryMapper] for apps that use kotlinx.serialization and only need to * track the serial name of each of their back stack entries (and not each entry's properties). * - * Falls back to [UnavailableBackStackEntryMapper] if the kotlinx mapper can't be created. + * Falls back to [UnavailableBackStackEntryMapper] if the underlying kotlinx mapper can't be + * created. * * See [BackStackEntryMapper.SerialName] for more details. */ @@ -34,6 +35,21 @@ internal object BuiltInBackStackEntryMappers { create(logger) { KotlinxBackStackEntryMapper(logger = logger) } } + /** + * Like [serialName], but also returns the properties of each back stack entry as Sentry + * arguments. + * + * Falls back to [UnavailableBackStackEntryMapper] if the underlying kotlinx mapper can't be + * created. + * + * See [BackStackEntryMapper.SerialNameAndProperties] for more details. + */ + val serialNameAndProperties: BackStackEntryMapper = + // Deferred for the same reason as serialName. + DeferredBackStackEntryMapper { + create(logger) { KotlinxBackStackEntryMapper(includeProperties = true, logger = logger) } + } + /** * Returns the mapper created by [newKotlinxMapper], or an [UnavailableBackStackEntryMapper] if * the mapper can't be linked or initialized. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt index 07cd2ffc47d..ce5cb650258 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -5,21 +5,40 @@ import io.sentry.SentryLevel.DEBUG import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import io.sentry.util.ExceptionUtils import java.lang.reflect.GenericSignatureFormatError import java.lang.reflect.InvocationTargetException import java.lang.reflect.MalformedParameterizedTypeException +import java.util.Collections import java.util.concurrent.ConcurrentHashMap import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.StructureKind -/** Implementation of [BackStackEntryMapper.SerialName]. */ +/** + * Implementation of [BackStackEntryMapper.SerialName] and + * [BackStackEntryMapper.SerialNameAndProperties], each of which relies on kotlinx serializers. + */ internal class KotlinxBackStackEntryMapper( + /** + * Whether this mapper returns each back stack entry's properties as arguments, as well as its + * name. + */ + private val includeProperties: Boolean = false, /** * Returns the serializer of a back stack entry's `@Serializable` class, or `null` if there's none * (e.g. for a generic class). Only called for classes marked `@Serializable`. @@ -35,11 +54,16 @@ internal class KotlinxBackStackEntryMapper( private val isAnnotatedSerializable: (Class<*>) -> Boolean = serializableAnnotationCheck(), /** Throws a [LinkageError] if the app's kotlinx.serialization version is incompatible. */ checkCompatibility: () -> Unit = { checkKotlinxCompatibility() }, + /** + * Returns why the properties encoder can't be used with the app's kotlinx.serialization version, + * or `null` if it can. Only called if [includeProperties] is `true`. + */ + checkEncoderCompatibility: () -> Throwable? = { kotlinxEncoderIncompatibility() }, logger: () -> ILogger, ) : BackStackEntryMapper { // Serializer lookups use reflection and mapping runs on every navigation, so we cache each - // class's name. Cache size is bounded by the number of back stack entry types. + // class's serializer and name. Cache size is bounded by the number of back stack entry types. private val types = ConcurrentHashMap, CachedType>() private val diagnostics = KotlinxMapperDiagnostics(logger) @@ -59,6 +83,19 @@ internal class KotlinxBackStackEntryMapper( } } + /** + * `true` if the app's kotlinx.serialization version can't be used to encode properties. Entries + * with properties then record [ArgumentDropReason.ENCODING_FAILED] without being encoded. Names + * are unaffected. + */ + private val isEncodingIncompatible: Boolean = + includeProperties && + run { + val error = checkEncoderCompatibility() ?: return@run false + diagnostics.incompatibleEncoder(error) + true + } + override fun map(backStackEntry: Any): SentryBackStackEntry? { // An enum constant with a body is an instance of an anonymous subclass, which isn't // @Serializable itself, so we look up the enum class instead. @@ -72,7 +109,9 @@ internal class KotlinxBackStackEntryMapper( } } - return SentryBackStackEntry(cached.name) + val arguments = if (includeProperties) argumentsOf(type, cached, backStackEntry) else null + + return SentryBackStackEntry(cached.name, arguments) } private fun cachedType(type: Class<*>): CachedType { @@ -109,7 +148,10 @@ internal class KotlinxBackStackEntryMapper( if (serializer == null) { unresolved(type, error = null) } else { - CachedType.Resolved(serializer.descriptor.serialName) + val descriptor = serializer.descriptor + // Read before the shape, so a failure reading the shape doesn't cost the type its name. + val name = descriptor.serialName + CachedType.Resolved(name, serializer, includeProperties && hasProperties(descriptor)) } } catch (e: InvocationTargetException) { // The type's serializer() or descriptor threw through reflection, e.g., a custom serializer's @@ -206,11 +248,59 @@ internal class KotlinxBackStackEntryMapper( ) } + /** + * Whether entries described by [descriptor] may have properties. A class or object without + * properties records no arguments, so its entries aren't encoded. + */ + @OptIn(ExperimentalSerializationApi::class) + private fun hasProperties(descriptor: SerialDescriptor): Boolean = + try { + descriptor.elementsCount > 0 || + (descriptor.kind != StructureKind.CLASS && descriptor.kind != StructureKind.OBJECT) + } catch (_: LinkageError) { + // As for the name, a LinkageError from the type's own descriptor only fails this type. + true + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad b/c a custom serializer's descriptor is host app code, which may throw anything. The + // entry keeps its name, and encoding, which reads the same descriptor, records why its + // arguments are dropped. + ExceptionUtils.rethrowIfFatal(t) + true + } + + /** + * Returns lazily encoded arguments derived from [backStackEntry]'s properties, or `null` if its + * [type] has no properties. + */ + private fun argumentsOf( + type: Class<*>, + cached: CachedType.Resolved, + backStackEntry: Any, + ): Map? { + if (!cached.hasProperties) { + return null + } + if (isEncodingIncompatible) { + return KotlinxUnencodableArguments + } + @Suppress("UNCHECKED_CAST") + return KotlinxArgumentSource(backStackEntry, cached.serializer as KSerializer) { error -> + diagnostics.propertyFailure(type, error) + } + } + /** What [lookUp] found for a back stack entry type, cached so each type is looked up once. */ private sealed interface CachedType { - /** A type that can be named, and its [name]. */ - class Resolved(val name: String) : CachedType + /** + * A type that can be named: its [name], its [serializer], and whether it [hasProperties] to + * encode. `hasProperties` is always `false` if the mapper doesn't include properties. + */ + class Resolved( + val name: String, + val serializer: KSerializer<*>, + val hasProperties: Boolean, + ) : CachedType /** * A type that can't be named, e.g., because it isn't `@Serializable` or reading its serializer @@ -234,9 +324,10 @@ internal class KotlinxBackStackEntryMapper( /** * The warnings [KotlinxBackStackEntryMapper] logs if it can't find the serializer for a back stack - * entry or resolve the entry's name. + * entry, resolve the entry's name, or encode its properties. * - * Only decides what's logged. Whether a type is looked up again is up to the mapper. + * Only decides what's logged, and how often. Whether a type is looked up or encoded again is up to + * the mapper. * * The R8 check matches the start of [compatibilityCheckFailed]'s message, so rewording it requires * updating `CompatibilityLogChecks.kt` @@ -244,6 +335,14 @@ internal class KotlinxBackStackEntryMapper( */ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { + /** + * The kinds of property encoding failure already logged for each type. Failing types are still + * encoded again, as whether encoding fails can depend on the value, so this only keeps each + * warning from being logged more than once per type. + */ + private val loggedPropertyFailures = + Collections.newSetFromMap(ConcurrentHashMap, PropertyFailure>, Boolean>()) + /** Logs that entries of [type] can't be named because the type isn't `@Serializable`. */ fun notSerializable(type: Class<*>) { logger() @@ -281,6 +380,127 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { ) } + /** + * Logs [error] indicating that the app's kotlinx.serialization version can't be used to encode + * properties. Entries are recorded by name without arguments. + */ + fun incompatibleEncoder(error: Throwable) { + logger() + .log( + WARNING, + "Nav3 SerialNameAndProperties is incompatible with this app's kotlinx.serialization " + + "version. Recording names without arguments. $INCOMPATIBLE_KOTLINX_ADVICE", + error, + ) + } + + /** + * Logs why encoding the properties of an entry of [type] failed. Logged once per type and kind of + * failure, as whether encoding fails can depend on the entry's values (e.g., whether a contextual + * property is null, or which subtype a sealed property has). + * + * Attaches [error] unless it's a [DropArgumentsException], which carries only the reason that's + * logged. + */ + @Suppress("LongMethod") // One flat branch per kind of failure. + fun propertyFailure(type: Class<*>, error: Throwable) { + when (error) { + is DropArgumentsException -> + logOncePerType(type, PropertyFailure.OVER_LIMITS) { + log( + WARNING, + "Nav3 dropped arguments for type %s (%s). Limits are $MAX_ARGUMENT_DEPTH levels, " + + "$MAX_ARGUMENT_VALUES values, $MAX_ARGUMENT_CHARACTERS characters, and " + + "$MAX_SERIALIZER_NESTING nested serializer calls. Map keys must stringify to " + + "distinct strings. Use a custom BackStackEntryMapper to select fewer properties or " + + "flatten nested values.", + type.name, + error.reason.serializedValue, + ) + } + is SerializationException -> + logOncePerType(type, PropertyFailure.UNENCODABLE) { + log( + WARNING, + error, + "Nav3 couldn't encode properties for type %s. Recording names without arguments. " + + "Contextual and open polymorphic properties and structured map keys aren't " + + "supported. Use a custom BackStackEntryMapper to select supported properties or " + + "extract arguments directly. See the attached error.", + type.name, + ) + } + is ArgumentProtocolException -> + logOncePerType(type, PropertyFailure.PROTOCOL_VIOLATION) { + log( + WARNING, + error, + "Nav3 couldn't encode properties for type %s because a value was written outside " + + "the encoder's protocol (by a custom serializer or an SDK bug). Recording names " + + "without arguments. See the attached error.", + type.name, + ) + } + is LinkageError -> + logOncePerType(type, PropertyFailure.UNLOADABLE) { + log( + WARNING, + error, + "Nav3 couldn't encode properties for type %s because a required class couldn't be " + + "linked, initialized, or found. Recording names without arguments. See the " + + "attached error. If all types fail, kotlinx.serialization may be incompatible. " + + INCOMPATIBLE_KOTLINX_ADVICE, + type.name, + ) + } + else -> + logOncePerType(type, PropertyFailure.THROWING) { + log( + WARNING, + error, + "Nav3 couldn't encode properties for type %s because a serializer threw. Recording " + + "names without arguments. See the attached error.", + type.name, + ) + } + } + } + + /** Runs [log] on the logger unless a [failure] of this kind was already logged for [type]. */ + private inline fun logOncePerType( + type: Class<*>, + failure: PropertyFailure, + log: ILogger.() -> Unit, + ) { + if (loggedPropertyFailures.add(type to failure)) { + logger().log() + } + } + + /** Why encoding an entry's properties failed, which determines the warning we log. */ + private enum class PropertyFailure { + /** Encoding threw a [SerializationException], e.g., for a contextual property. */ + UNENCODABLE, + + /** + * The entry broke an argument limit, e.g., by having too many values, or has a map with two + * keys recorded as the same string. + */ + OVER_LIMITS, + + /** + * A value was written out of order or couldn't be recorded (an [ArgumentProtocolException]), + * e.g., by a custom serializer that writes values outside its elements. + */ + PROTOCOL_VIOLATION, + + /** A serializer threw something other than a [SerializationException] or [LinkageError]. */ + THROWING, + + /** A class a serializer needs couldn't be linked, initialized, or found. */ + UNLOADABLE, + } + /** * Logs why [type] can't be named. [error] is what reading its annotations, serializer, or * descriptor threw, or `null` if the serializer lookup found none without throwing. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt index ed5ac25d540..049203b9736 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt @@ -2,23 +2,120 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.util.ExceptionUtils import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.TripleSerializer +import kotlinx.serialization.builtins.nullable +import kotlinx.serialization.builtins.serializer /** * Verifies that the host app's `kotlinx-serialization-core` version is compatible with the APIs * used by our built-in `BackStackEntryMapper`s. * - * Does so by calling each kotlinx.serialization API that [KotlinxBackStackEntryMapper] calls, looks - * up the built-in `String` serializer, and reads its serial name. + * Does so by calling each kotlinx.serialization API that [KotlinxBackStackEntryMapper] invokes, + * looks up the built-in `String` serializer, and reads its serial name. * - * Throws a [LinkageError] if the app's `kotlinx-serialization-core` version is incompatible. A - * `LinkageError` thrown here is conclusive: unlike looking up an app type's serializer, the check - * runs no app code and no serializer generated by a compiler plugin, either of which could throw - * one for reasons that affect only its own type. + * Throws a [LinkageError] if the app's `kotlinx-serialization-core` version is incompatible. + * + * Note: A `LinkageError` thrown here is conclusive. Unlike looking up an app type's serializer, the + * check runs no app code and no serializer generated by a compiler plugin, either of which could + * throw one for reasons that affect only its own type. */ internal fun checkKotlinxCompatibility( lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, ) { lookUpSerializer(String::class.java)?.descriptor?.serialName } + +/** + * Returns why the properties encoder can't be used with the host app's `kotlinx-serialization-core` + * version, or `null` if it can. + * + * Encodes [COMPATIBILITY_CHECK_VALUE] with [KotlinxPropertiesEncoder], as [KotlinxArgumentSource] + * does, and compares the output with [COMPATIBILITY_CHECK_ENCODING]. Like + * [checkKotlinxCompatibility], it uses only built-in serializers, so it runs no app code and no + * serializer generated by a compiler plugin. + * + * Unlike `checkKotlinxCompatibility`, every failure is taken into account, rather than just + * [LinkageError]s. An incompatible version may fail in other ways (e.g., a `NullPointerException` + * under R8) or silently encode wrong arguments, and recording no arguments is better than recording + * wrong ones. + */ +internal fun kotlinxEncoderIncompatibility( + /** Encodes [COMPATIBILITY_CHECK_VALUE] to the provided [ArgumentSink]. */ + encode: (ArgumentSink) -> Unit = ::encodeCompatibilityCheckValue, +): Throwable? = + try { + val sink = TreeArgumentSink(ArgumentBudget()) + encode(sink) + if (sink.argumentsOrThrow() == COMPATIBILITY_CHECK_ENCODING) { + null + } else { + EncoderProducedUnexpectedOutput() + } + } catch (e: LinkageError) { + // Returned rather than rethrown, so that an encoder that can't link only disables properties. + // Rethrown, it would fail the mapper's creation, and entries would lose their names too. + e + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad b/c an incompatible kotlinx.serialization version can fail the encoder in many ways. + ExceptionUtils.rethrowIfFatal(t) + t + } + +/** Encodes [COMPATIBILITY_CHECK_VALUE] to [sink], using only built-in serializers. */ +internal fun encodeCompatibilityCheckValue(sink: ArgumentSink) { + @Suppress("UNCHECKED_CAST") + KotlinxPropertiesEncoder.encode( + TripleSerializer( + String.serializer(), + ListSerializer(Int.serializer().nullable), + MapSerializer(String.serializer(), UInt.serializer()), + ) + as KSerializer, + COMPATIBILITY_CHECK_VALUE, + sink, + ) +} + +/** + * The value [kotlinxEncoderIncompatibility] encodes to check the properties encoder. + * + * Covers classes, lists, maps, nulls, and, through [UInt], value classes and the conversion of + * unsigned numbers, which encode wrong values rather than fail if kotlinx.serialization changes how + * it encodes them. + */ +private val COMPATIBILITY_CHECK_VALUE = + Triple("check", listOf(1, null), mapOf("count" to UInt.MAX_VALUE)) + +/** + * The expected encoding of [COMPATIBILITY_CHECK_VALUE]. + * + * None of its keys are on the + * [sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist), + * so none are filtered. + */ +private val COMPATIBILITY_CHECK_ENCODING: Map = + mapOf( + "first" to "check", + "second" to listOf(1, null), + "third" to mapOf("count" to UInt.MAX_VALUE.toLong()), + ) + +/** + * Signals that the properties encoder produced unexpected output for [COMPATIBILITY_CHECK_VALUE]. + * + * Suggests the app's `kotlinx-serialization-core` version shouldn't be trusted because it will + * likely mis-encode other properties, too. + */ +internal class EncoderProducedUnexpectedOutput : + RuntimeException( + // Message deliberately omits any back stack entry data, which could be sensitive. + "The kotlinx.serialization properties encoder produced unexpected output.", + ) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt index 919c915535c..47f42db1bb4 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -5,12 +5,13 @@ import kotlinx.serialization.KSerializer import kotlinx.serialization.serializerOrNull /** - * Returns [type]'s serializer, or `null` if unavailable, including when type arguments are needed. - * Extends [serializerOrNull] to support private `@Serializable` objects. Also supports built-in - * types and unannotated enums. + * Returns [type]'s serializer, or `null` if it has no serializer or if `type` is generic. * - * May execute serializer code and throw. What that code throws through reflection, including fatal - * errors such as [OutOfMemoryError], arrives wrapped in an [InvocationTargetException]. + * Like [serializerOrNull], which it extends, it returns serializers for built-in types and enums + * that aren't `@Serializable`; unlike it, it also supports private `@Serializable` objects. + * + * May execute serializer code and throw. Whatever that code throws via reflection, including fatal + * errors such as [OutOfMemoryError], will arrive wrapped in an [InvocationTargetException]. */ @Suppress("SwallowedException") internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = @@ -23,9 +24,9 @@ internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = } /** - * Uses reflection to look up the serializer of a private `@Serializable object` through the members - * the serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules - * keep both members.) kotlinx.serialization's own object lookup reads the same two members, so this + * Uses reflection to look up the serializer of a private `@Serializable object` via the members the + * serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules keep + * both members.) kotlinx.serialization's own object lookup reads the same two members, so this * fallback can break only if that lookup breaks too. * * Propagates any exception thrown by the reflective lookup. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md index ba524b283c2..c68defa962f 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -42,7 +42,8 @@ Recommended rules for raising the floor: - Raise it in a reviewed change of its own, with a CHANGELOG entry and a corresponding update to the [Sentry Nav3 docs](https://docs.sentry.io/platforms/android/integrations/navigation/#navigation-3). -- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `internal/common/KotlinxSerializationSupport.kt` to match. A unit test will fail if the two differ. +- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `internal/common/KotlinxSerializationSupport.kt` to match. A unit test will fail if the two + differ. ## Minification diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt index 6722f66584d..6ef8bff6973 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt @@ -14,4 +14,11 @@ class BackStackEntryMapperTest { assertThat(homeMapper).isSameInstanceAs(BuiltInBackStackEntryMappers.serialName) } + + @Test + fun `SerialNameAndProperties - returns the built-in properties mapper as a mapper for any entry type`() { + val homeMapper: BackStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties + + assertThat(homeMapper).isSameInstanceAs(BuiltInBackStackEntryMappers.serialNameAndProperties) + } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt index f75f7063b92..15b42808c5f 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt @@ -19,11 +19,13 @@ import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import io.sentry.Breadcrumb +import io.sentry.DataCollection import io.sentry.Hint import io.sentry.IScope import io.sentry.IScopes import io.sentry.ISentryClient import io.sentry.ITransaction +import io.sentry.KeyValueCollectionBehavior import io.sentry.PropagationContext import io.sentry.Scope import io.sentry.ScopeCallback @@ -34,8 +36,14 @@ import io.sentry.SentryTracer import io.sentry.TransactionContext import io.sentry.TransactionOptions import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator +import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import org.junit.Rule import org.junit.Test import org.junit.rules.TestWatcher @@ -81,6 +89,28 @@ class SentryNavEffectTest { @Serializable private data class SerializableProfileRoute(val userId: String) + @Serializable + @SerialName("Checkout") + private data class CheckoutRoute(val cartId: String, val authToken: String) + + @Serializable @SerialName("Cart") private data class CartRoute(val cartId: String) + + @Serializable + @SerialName("Account") + private data class AccountRoute(val accountId: String, val email: String) + + @Serializable(with = BrokenRouteSerializer::class) private class BrokenRoute + + /** Names [BrokenRoute] "Broken", but throws when encoding it. */ + private object BrokenRouteSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("Broken", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: BrokenRoute): Unit = error("can't encode") + + override fun deserialize(decoder: Decoder): BrokenRoute = BrokenRoute() + } + private class Fixture { val options = SentryOptions().apply { @@ -396,6 +426,113 @@ class SentryNavEffectTest { .inOrder() } + @Test + fun `SerialNameAndProperties records serial names with properties as arguments, filtering sensitive values`() { + val fixture = Fixture() + val backStack = mutableStateListOf(CheckoutRoute(cartId = "c-1", authToken = "secret")) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + assertThat(fixture.breadcrumbs.single().data["to"]).isEqualTo("/Checkout") + assertThat(fixture.breadcrumbs.single().data["to_arguments"]) + .isEqualTo(mapOf("cartId" to "c-1", "authToken" to "[Filtered]")) + assertThat(fixture.transactions.single().getData("arguments")) + .isEqualTo(mapOf("cartId" to "c-1", "authToken" to "[Filtered]")) + } + + @Test + fun `SerialNameAndProperties records PII properties without sendDefaultPii and with all data collection off`() { + val fixture = Fixture() + fixture.options.isSendDefaultPii = false + fixture.options.dataCollection = dataCollectionOff() + val backStack = mutableStateListOf(AccountRoute(accountId = "a-1", email = "a@b.c")) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + val arguments = mapOf("accountId" to "a-1", "email" to "a@b.c") + assertThat(fixture.breadcrumbs.single().data["to_arguments"]).isEqualTo(arguments) + assertThat(fixture.transactions.single().getData("arguments")).isEqualTo(arguments) + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo(listOf(mapOf("entry" to "/Account", "entry_arguments" to arguments))) + } + + @Test + fun `a mapper that wraps SerialNameAndProperties records the properties it doesn't remove`() { + val fixture = Fixture() + val backStack = mutableStateListOf(AccountRoute(accountId = "a-1", email = "a@b.c")) + val mapper = + BackStackEntryMapper { entry -> + BackStackEntryMapper.SerialNameAndProperties.map(entry)?.let { mapped -> + SentryBackStackEntry(mapped.name, mapped.arguments?.filterKeys { it != "email" }) + } + } + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = mapper, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + assertThat(fixture.breadcrumbs.single().data["to"]).isEqualTo("/Account") + assertThat(fixture.breadcrumbs.single().data["to_arguments"]) + .isEqualTo(mapOf("accountId" to "a-1")) + assertThat(fixture.transactions.single().getData("arguments")) + .isEqualTo(mapOf("accountId" to "a-1")) + } + + @Test + fun `SerialNameAndProperties drops only an unencodable route's properties, recording why`() { + val fixture = Fixture() + val backStack = mutableStateListOf(CartRoute(cartId = "c-1"), BrokenRoute()) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialNameAndProperties, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + val dropped = mapOf("dropped_by_sentry" to "encoding_failed") + assertThat(fixture.breadcrumbs.single().data["to"]).isEqualTo("/Broken") + assertThat(fixture.breadcrumbs.single().data["to_arguments"]).isEqualTo(dropped) + assertThat(fixture.transactions.single().name).isEqualTo("/Broken") + assertThat(fixture.transactions.single().getData("arguments")).isEqualTo(dropped) + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("entry" to "/Broken", "entry_arguments" to dropped), + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")), + ), + ) + } + @Test fun `updated entry mapper is used for later navigation changes`() { val fixture = Fixture() @@ -854,6 +991,21 @@ class SentryNavEffectTest { ) } + /** Turns off every data collection option. */ + private fun dataCollectionOff(): DataCollection = + DataCollection().apply { + userInfo = false + cookies = KeyValueCollectionBehavior.off() + urlQueryParams = KeyValueCollectionBehavior.off() + httpBodies = emptySet() + databaseQueryData = false + filePaths = false + httpHeaders.request = KeyValueCollectionBehavior.off() + httpHeaders.response = KeyValueCollectionBehavior.off() + graphql.document = false + graphql.variables = false + } + private fun IScope.navigationBackStack(): List>? { val navigationContext = contexts[NAVIGATION_CONTEXT_KEY] as? Map<*, *> ?: return null diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt index 92a433e38d6..c2fc9aad8cf 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -35,6 +35,8 @@ class BuiltInBackStackEntryMappersTest { @Serializable @SerialName("Home") data object Home + @Serializable @SerialName("Detail") data class Detail(val id: String) + data class NotSerializable(val id: String) private val kotlinxMapper = BackStackEntryMapper { SentryBackStackEntry("Kotlinx") } @@ -93,6 +95,65 @@ class BuiltInBackStackEntryMappersTest { assertThat(race.unavailableTypeWarnings).isEqualTo(1) } + // serialNameAndProperties + + @Test + fun `serialNameAndProperties - records properties as arguments`() { + val mapper = BuiltInBackStackEntryMappers.serialNameAndProperties + + val mapped = listOf(Home, Detail("1")).map(mapper::map) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("Home"), + SentryBackStackEntry("Detail", mapOf("id" to "1")), + ) + .inOrder() + } + + @Test + fun `serialNameAndProperties - returns the same mapper on every access`() { + assertThat(BuiltInBackStackEntryMappers.serialNameAndProperties) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialNameAndProperties) + } + + @Test + fun `serialNameAndProperties - is a different mapper from serialName`() { + assertThat(BuiltInBackStackEntryMappers.serialNameAndProperties) + .isNotSameInstanceAs(BuiltInBackStackEntryMappers.serialName) + } + + @Test + fun `serialNameAndProperties - doesn't create the kotlinx mapper when read`() { + val classLoader = KotlinxMapperHidingClassLoader() + + classLoader.companionMapper("getSerialNameAndProperties") + + assertThat(classLoader.wasKotlinxMapperRequested).isFalse() + } + + @Test + fun `serialNameAndProperties - maps entries to null when the kotlinx mapper can't be loaded`() { + val classLoader = KotlinxMapperHidingClassLoader() + + val mapper = classLoader.companionMapper("getSerialNameAndProperties") + + assertThat(mapper.map(Home)).isNull() + assertThat(classLoader.wasKotlinxMapperRequested).isTrue() + } + + @Test + fun `serialNameAndProperties - maps entries to null when kotlinx serialization is missing`() { + val classLoader = KotlinxMapperHidingClassLoader(hidesKotlinx = true) + val entry = classLoader.notSerializableEntry("1") + + val mapper = classLoader.companionMapper("getSerialNameAndProperties") + + assertThat(mapper.map("home")).isNull() + assertThat(mapper.map(entry)).isNull() + assertThat(classLoader.wasKotlinxRequested).isTrue() + } + // create() @Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesArgumentLimitsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesArgumentLimitsTest.kt new file mode 100644 index 00000000000..4c744985d8a --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesArgumentLimitsTest.kt @@ -0,0 +1,152 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.descriptors.element +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.junit.Test +import org.mockito.kotlin.mock + +/** + * Converts back stacks with [BackStackEntryMapper.SerialNameAndProperties] whose entries' host app + * serializers interfere with how the argument limits are enforced, checking the drop reasons + * recorded across the kotlinx encoding and argument sanitization layers. + * + * Each back stack is ordered top first, as [BackStackObserver] converts it. + */ +class SerialNameAndPropertiesArgumentLimitsTest { + + @Serializable(with = ReportSerializer::class) private class ReportRoute(val body: String) + + /** + * Encodes a [ReportRoute] as a class with its body, but replaces any exception with a + * [SerializationException] of its own, without the original as the cause, as a host app + * serializer might. + */ + private object ReportSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("Report") { element("body") } + + override fun serialize(encoder: Encoder, value: ReportRoute) { + try { + encoder.encodeStructure(descriptor) { encodeStringElement(descriptor, 0, value.body) } + } catch (@Suppress("SwallowedException", "TooGenericExceptionCaught") e: Exception) { + throw SerializationException("Couldn't encode the report") + } + } + + override fun deserialize(decoder: Decoder): ReportRoute = throw UnsupportedOperationException() + } + + @Serializable(with = DraftSerializer::class) private class DraftRoute(val lineIds: List) + + /** + * Encodes a [DraftRoute] as a class with its line ids, then throws, as a host app serializer that + * fails after writing part of an entry's properties might. + */ + private object DraftSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("Draft") { element>("lineIds") } + + override fun serialize(encoder: Encoder, value: DraftRoute) { + encoder.encodeStructure(descriptor) { + encodeSerializableElement(descriptor, 0, ListSerializer(Int.serializer()), value.lineIds) + } + throw SerializationException("Couldn't encode the draft") + } + + override fun deserialize(decoder: Decoder): DraftRoute = throw UnsupportedOperationException() + } + + @Serializable @SerialName("Catalog") private data class CatalogRoute(val itemIds: List) + + @Serializable @SerialName("Cart") private data class CartRoute(val cartId: String) + + /** + * Wraps `SerialNameAndProperties` and reads each entry's arguments before returning them + * unchanged. + */ + private val argumentReadingMapper = + BackStackEntryMapper { entry -> + BackStackEntryMapper.SerialNameAndProperties.map(entry)?.also { it.arguments?.size } + } + + private val logger = mock() + + @Test + fun `an entry whose serializer replaces the character limit failure drops its own and older entries' arguments`() { + // The body alone is one character over the limit of MAX_ARGUMENT_CHARACTERS per update. + val report = ReportRoute(body = "b".repeat(MAX_ARGUMENT_CHARACTERS + 1)) + val backStack = listOf(report, CartRoute(cartId = "c-1")) + + val converted = convert(backStack, BackStackEntryMapper.SerialNameAndProperties) + + assertThat(converted) + .containsExactly( + NormalizedSentryBackStackEntry( + "/Report", + argumentDropReason = ArgumentDropReason.CHARACTER_LIMIT, + ), + NormalizedSentryBackStackEntry( + "/Cart", + argumentDropReason = ArgumentDropReason.CHARACTER_LIMIT, + ), + ) + .inOrder() + } + + @Test + fun `a serializer throwing after overflowing the value budget drops older entries' arguments unless read first`() { + // The catalog spends 151 of the MAX_ARGUMENT_VALUES = 200 values per update: its list and 150 + // items. The draft's list and 59 items are 60 more, which fit in a budget of their own but + // overflow what the catalog left, before the draft's serializer throws. Read first, the draft + // failed to encode with a budget of its own and spends none of the update's. + val catalog = CatalogRoute(itemIds = List(150) { it }) + val draft = DraftRoute(lineIds = List(59) { it }) + val backStack = listOf(catalog, draft, CartRoute(cartId = "c-1")) + + val written = convert(backStack, BackStackEntryMapper.SerialNameAndProperties) + val readFirst = convert(backStack, argumentReadingMapper) + + val recordedCatalog = + NormalizedSentryBackStackEntry("/Catalog", mapOf("itemIds" to List(150) { it })) + assertThat(written) + .containsExactly( + recordedCatalog, + NormalizedSentryBackStackEntry("/Draft", argumentDropReason = ArgumentDropReason.MAX_COUNT), + NormalizedSentryBackStackEntry("/Cart", argumentDropReason = ArgumentDropReason.MAX_COUNT), + ) + .inOrder() + assertThat(readFirst) + .containsExactly( + recordedCatalog, + NormalizedSentryBackStackEntry( + "/Draft", + argumentDropReason = ArgumentDropReason.ENCODING_FAILED, + ), + NormalizedSentryBackStackEntry("/Cart", mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + private fun convert( + backStack: List, + entryMapper: BackStackEntryMapper, + ): List = + BackStackConverter(ForwardingBackStackEntryMapper { entryMapper }, logger) + .convert(backStack, RetentionPolicy.KEEP_FIRST) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesParityTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesParityTest.kt new file mode 100644 index 00000000000..cfd6949590a --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SerialNameAndPropertiesParityTest.kt @@ -0,0 +1,406 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertWithMessage +import io.sentry.ILogger +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.util.UrlUtils.SENSITIVE_DATA_SUBSTITUTE +import kotlin.jvm.JvmInline +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.descriptors.element +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test +import org.mockito.kotlin.mock + +/** + * Converts each scenario's back stack along every [ArgumentPath] by which a host app can hand + * `SerialNameAndProperties`' arguments to Sentry, and checks that all of them record the same + * arguments and drop reasons. + * + * The paths differ in how they spend the update's argument budget: the built-in mapper's arguments + * encode straight into the update's budget, or replay a copy cached by an earlier read, while a + * wrapper's copy is encoded with a budget of its own. Each scenario runs along all of them, so a + * new scenario can't cover one path and miss another. The intended differences are stated in the + * scenario: an entry over an update-wide limit seen through a wrapper, as + * [Scenario.expectedWrapped], and an entry whose encoding failed after a read, which spends none of + * the update's budget, as [Scenario.expectedReadFirst]. + * + * Limits are covered by one that drops older entries' arguments and one that doesn't. Their + * enforcement is covered by `TreeArgumentSinkTest` and the encoder suites. + * + * Each back stack is ordered top first, as [BackStackObserver] converts it. + */ +class SerialNameAndPropertiesParityTest { + + @Serializable @SerialName("Cart") private data class CartRoute(val cartId: String) + + @Serializable private data class Address(val city: String, val zip: Int) + + private enum class Delivery { + STANDARD, + EXPRESS, + } + + @Serializable + @SerialName("Order") + private data class OrderRoute( + val orderId: Long, + val gift: Boolean, + val note: String?, + val delivery: Delivery, + val address: Address, + val tags: List, + val quantities: Map, + ) + + @Serializable @SerialName("Catalog") private data class CatalogRoute(val prices: Map) + + @Serializable @SerialName("Nested") private data class NestedRoute(val child: NestedRoute?) + + @Serializable(with = UnencodableSerializer::class) private class UnencodableRoute + + @Serializable private data class LateFailingProperties(val values: List) + + @Serializable(with = LateFailingSerializer::class) + private class LateFailingRoute(val values: List) + + /** + * Encodes a [LateFailingRoute]'s properties, then throws, as a serializer that fails late might. + */ + private object LateFailingSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("LateFailing") { element>("values") } + + override fun serialize(encoder: Encoder, value: LateFailingRoute) { + LateFailingProperties.serializer().serialize(encoder, LateFailingProperties(value.values)) + error("Failed after encoding") + } + + override fun deserialize(decoder: Decoder): LateFailingRoute = + throw UnsupportedOperationException() + } + + /** A map key whose underlying property's name (`token`) is sensitive. */ + @Serializable @JvmInline private value class SecretKey(val token: String) + + @Serializable + @SerialName("Headers") + private data class HeadersRoute(val headers: Map) + + /** Throws when encoding an [UnencodableRoute], as a broken host app serializer might. */ + private object UnencodableSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("Unencodable") { element("email") } + + override fun serialize(encoder: Encoder, value: UnencodableRoute) { + error("Can't encode") + } + + override fun deserialize(decoder: Decoder): UnencodableRoute = + throw UnsupportedOperationException() + } + + /** One way a host app can hand `SerialNameAndProperties`' arguments to Sentry. */ + private enum class ArgumentPath { + /** Returns the built-in mapper's entry, whose arguments encode as Sentry writes them. */ + BUILT_IN, + + /** + * Reads the built-in mapper's arguments, then returns its entry, which replays that read, or + * drops the arguments without spending the budget if the read failed to encode. + */ + READ_FIRST, + + /** Returns a copy of the built-in mapper's arguments, with one key filtered out. */ + WRAPPED, + + /** Returns a plain map equal to what the built-in mapper encodes. */ + PLAIN, + } + + /** + * A back stack and what every [ArgumentPath] should record for it, in serialized form. + * + * [plainEntries] pairs each entry with an equivalent plain-map entry for [ArgumentPath.PLAIN], or + * is `null` if some entry has none, e.g., because it can't be encoded. + */ + private class Scenario( + val backStack: List, + val plainEntries: Map?, + val expected: List>, + val expectedWrapped: List> = expected, + val expectedReadFirst: List> = expected, + ) + + private val cart = CartRoute(cartId = "c-1") + private val plainCart = SentryBackStackEntry("Cart", mapOf("cartId" to "c-1")) + private val recordedCart = + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")) + + private val logger = mock() + + @Test + fun `every path records the same arguments for entries within the argument limits`() { + val order = + OrderRoute( + orderId = 42L, + gift = true, + note = null, + delivery = Delivery.EXPRESS, + address = Address(city = "Vienna", zip = 1010), + tags = listOf("new", "sale"), + quantities = mapOf("apple" to 2, "pear" to 3), + ) + val plainOrder = + SentryBackStackEntry( + "Order", + mapOf( + "orderId" to 42L, + "gift" to true, + "note" to null, + "delivery" to Delivery.EXPRESS, + "address" to mapOf("city" to "Vienna", "zip" to 1010), + "tags" to listOf("new", "sale"), + "quantities" to mapOf("apple" to 2, "pear" to 3), + ), + ) + + assertEveryPathRecords( + Scenario( + backStack = listOf(order, cart), + plainEntries = mapOf(order to plainOrder, cart to plainCart), + expected = + listOf( + mapOf( + "entry" to "/Order", + "entry_arguments" to + mapOf( + "orderId" to 42L, + "gift" to true, + "note" to null, + "delivery" to "EXPRESS", + "address" to mapOf("city" to "Vienna", "zip" to 1010), + "tags" to listOf("new", "sale"), + "quantities" to mapOf("apple" to 2, "pear" to 3), + ), + ), + recordedCart, + ), + ), + ) + } + + @Test + fun `every path drops an entry's arguments over the value limit, and only a wrapper keeps older entries'`() { + // The prices map and its MAX_ARGUMENT_VALUES + 1 entries are MAX_ARGUMENT_VALUES + 2 values, + // over the limit of MAX_ARGUMENT_VALUES per update. + val prices = (0..MAX_ARGUMENT_VALUES).associate { "item$it" to it } + val catalog = CatalogRoute(prices = prices) + val droppedCatalog = + mapOf( + "entry" to "/Catalog", + "entry_arguments" to mapOf("dropped_by_sentry" to "max_argument_count_exceeded"), + ) + + assertEveryPathRecords( + Scenario( + backStack = listOf(catalog, cart), + plainEntries = + mapOf( + catalog to SentryBackStackEntry("Catalog", mapOf("prices" to prices)), + cart to plainCart, + ), + expected = + listOf( + droppedCatalog, + mapOf( + "entry" to "/Cart", + "entry_arguments" to mapOf("dropped_by_sentry" to "max_argument_count_exceeded"), + ), + ), + // The wrapper's copy was encoded with its own budget, so Sentry receives the drop reason + // as an ordinary argument and older entries keep theirs. + expectedWrapped = listOf(droppedCatalog, recordedCart), + ), + ) + } + + @Test + fun `every path drops the arguments of an entry nested past the depth limit, but not of older entries`() { + // The innermost child is nested one level past the depth limit of MAX_ARGUMENT_DEPTH. + val nested = nestedRoute(levels = MAX_ARGUMENT_DEPTH + 1) + + assertEveryPathRecords( + Scenario( + backStack = listOf(nested, cart), + plainEntries = + mapOf( + nested to + SentryBackStackEntry("Nested", plainNestedArguments(levels = MAX_ARGUMENT_DEPTH + 1)), + cart to plainCart, + ), + expected = + listOf( + mapOf( + "entry" to "/Nested", + "entry_arguments" to mapOf("dropped_by_sentry" to "invalid_structure"), + ), + recordedCart, + ), + ), + ) + } + + @Test + fun `every path records the same encoding failure for an entry that can't be encoded`() { + assertEveryPathRecords( + Scenario( + backStack = listOf(UnencodableRoute(), cart), + plainEntries = null, + expected = + listOf( + mapOf( + "entry" to "/Unencodable", + "entry_arguments" to mapOf("dropped_by_sentry" to "encoding_failed"), + ), + recordedCart, + ), + ), + ) + } + + @Test + fun `only the built-in path spends the budget an entry wrote before its encoding failed`() { + // The late-failing entry writes its list and MAX_ARGUMENT_VALUES - 2 elements before it throws, + // which leaves one value, too few for the catalog's map and its one price. + val lateFailing = LateFailingRoute(values = List(MAX_ARGUMENT_VALUES - 2) { it }) + val catalog = CatalogRoute(prices = mapOf("item" to 1)) + val failedLateFailing = + mapOf( + "entry" to "/LateFailing", + "entry_arguments" to mapOf("dropped_by_sentry" to "encoding_failed"), + ) + val catalogKeepsItsPrices = + listOf( + failedLateFailing, + mapOf("entry" to "/Catalog", "entry_arguments" to mapOf("prices" to mapOf("item" to 1))), + ) + + assertEveryPathRecords( + Scenario( + backStack = listOf(lateFailing, catalog), + plainEntries = null, + expected = + listOf( + failedLateFailing, + mapOf( + "entry" to "/Catalog", + "entry_arguments" to mapOf("dropped_by_sentry" to "max_argument_count_exceeded"), + ), + ), + // The wrapper's copy was encoded with its own budget, so Sentry receives only the drop + // reason, as an ordinary argument. + expectedWrapped = catalogKeepsItsPrices, + // A copy that failed to encode when read spends none of the update's budget. + expectedReadFirst = catalogKeepsItsPrices, + ), + ) + } + + @Test + fun `every path spends the budget of one entry for map entries whose keys are filtered`() { + // The headers map and its single filtered entry are 2 values, which leaves exactly enough for + // the catalog's map and its MAX_ARGUMENT_VALUES - 3 prices. Charging for every filtered entry + // would push the catalog over the limit. + val headers = + HeadersRoute( + mapOf(SecretKey("a") to "secret-a", SecretKey("b") to "secret-b", SecretKey("c") to "x"), + ) + val prices = (0 until MAX_ARGUMENT_VALUES - 3).associate { "item$it" to it } + val catalog = CatalogRoute(prices = prices) + val filteredHeaders = mapOf(SENSITIVE_DATA_SUBSTITUTE to SENSITIVE_DATA_SUBSTITUTE) + + assertEveryPathRecords( + Scenario( + backStack = listOf(headers, catalog), + plainEntries = + mapOf( + headers to SentryBackStackEntry("Headers", mapOf("headers" to filteredHeaders)), + catalog to SentryBackStackEntry("Catalog", mapOf("prices" to prices)), + ), + expected = + listOf( + mapOf("entry" to "/Headers", "entry_arguments" to mapOf("headers" to filteredHeaders)), + mapOf("entry" to "/Catalog", "entry_arguments" to mapOf("prices" to prices)), + ), + ), + ) + } + + /** Converts [scenario]'s back stack along every [ArgumentPath] and checks what each records. */ + private fun assertEveryPathRecords(scenario: Scenario) { + for (path in ArgumentPath.entries) { + val mapper = mapperFor(path, scenario) ?: continue + val expected = + when (path) { + ArgumentPath.WRAPPED -> scenario.expectedWrapped + ArgumentPath.READ_FIRST -> scenario.expectedReadFirst + else -> scenario.expected + } + + val recorded = convert(scenario.backStack, mapper).serialize() + + assertWithMessage("arguments recorded along $path").that(recorded).isEqualTo(expected) + } + } + + /** Returns the mapper for [path], or `null` if [scenario] can't run along it. */ + private fun mapperFor(path: ArgumentPath, scenario: Scenario): BackStackEntryMapper? { + val builtIn = BackStackEntryMapper.SerialNameAndProperties + return when (path) { + ArgumentPath.BUILT_IN -> builtIn + ArgumentPath.READ_FIRST -> + BackStackEntryMapper { entry -> builtIn.map(entry)?.also { it.arguments?.size } } + // Removes the `email` argument, as the mapper's KDoc documents. + ArgumentPath.WRAPPED -> + BackStackEntryMapper { entry -> + builtIn.map(entry)?.let { mapped -> + SentryBackStackEntry(mapped.name, mapped.arguments?.filterKeys { it != "email" }) + } + } + ArgumentPath.PLAIN -> + scenario.plainEntries?.let { plainEntries -> + BackStackEntryMapper { entry -> plainEntries.getValue(entry) } + } + } + } + + private fun convert( + backStack: List, + entryMapper: BackStackEntryMapper, + ): List = + BackStackConverter(ForwardingBackStackEntryMapper { entryMapper }, logger) + .convert(backStack, RetentionPolicy.KEEP_FIRST) + + /** A [NestedRoute] wrapping [levels] more of them, the innermost with no child. */ + private fun nestedRoute(levels: Int): NestedRoute { + var route = NestedRoute(child = null) + repeat(levels) { route = NestedRoute(child = route) } + return route + } + + /** The plain map equivalent of [nestedRoute]'s arguments. */ + private fun plainNestedArguments(levels: Int): Map { + var arguments = mapOf("child" to null) + repeat(levels) { arguments = mapOf("child" to arguments) } + return arguments + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperEncoderCheckTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperEncoderCheckTest.kt new file mode 100644 index 00000000000..897b9c9dd36 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperEncoderCheckTest.kt @@ -0,0 +1,138 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions + +/** How [KotlinxBackStackEntryMapper] acts on what its properties encoder check finds. */ +class KotlinxBackStackEntryMapperEncoderCheckTest { + + @Test + fun `logs nothing when created with properties included for a kotlinx version its encoder check finds compatible`() { + val fixture = + KotlinxMapperFixture.create(includeProperties = true, encoderCheck = FakeEncoderCheck()) + + fixture.mapper + + verifyNoInteractions(fixture.logger) + } + + @Test + fun `checks the properties encoder once when created with properties included`() { + val encoderCheck = FakeEncoderCheck() + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + repeat(3) { mapper.mapAndReadArguments(Detail("$it")) } + + assertThat(encoderCheck.checks).isEqualTo(1) + } + + @Test + fun `never checks the properties encoder when properties are excluded`() { + // No incompatible check is logged, as the encoder check isn't run when properties are excluded. + val encoderCheck = FakeEncoderCheck(NoSuchMethodError()) + val fixture = + KotlinxMapperFixture.create(includeProperties = false, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(encoderCheck.checks).isEqualTo(0) + verifyNoInteractions(fixture.logger) + } + + @Test + fun `keeps the name and records only the encoding failure when the properties encoder is incompatible`() { + val encoderCheck = FakeEncoderCheck(NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Search("shoes"))) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + SentryBackStackEntry("Search", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + ) + .inOrder() + } + + @Test + fun `keeps the name and records only the encoding failure when the properties encoder can't link`() { + // Runs the LinkageError through the real check's failure handling instead of returning it. + val mapper = + KotlinxBackStackEntryMapper( + includeProperties = true, + lookUpSerializer = { Detail.serializer() }, + checkCompatibility = {}, + checkEncoderCompatibility = { kotlinxEncoderIncompatibility { throw NoSuchMethodError() } }, + logger = { mock() }, + ) + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `records no arguments for objects when the properties encoder is incompatible`() { + val encoderCheck = FakeEncoderCheck(NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + val mapped = mapper.map(Home) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Home", arguments = null)) + } + + @Test + fun `doesn't encode properties when the properties encoder is incompatible`() { + val encoderCheck = FakeEncoderCheck(NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + mapper.mapAndReadArguments(Detail("1")) + mapper.mapAndWriteArguments(Detail("2")) + + assertThat(fixture.detailSerializer.serialized).isEmpty() + } + + @Test + fun `logs the incompatible encoder warning with the error when created for an incompatible properties encoder`() { + val error = NoSuchMethodError("encodeStructure") + val encoderCheck = FakeEncoderCheck(error) + + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + + verify(fixture.logger, times(1)).log(eq(SentryLevel.WARNING), any(), eq(error)) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `logs nothing more for entries mapped when the properties encoder is incompatible`() { + val error = NoSuchMethodError() + val encoderCheck = FakeEncoderCheck(error) + val fixture = KotlinxMapperFixture.create(includeProperties = true, encoderCheck = encoderCheck) + val mapper = fixture.mapper + + repeat(3) { + mapper.mapAndReadArguments(Detail("$it")) + mapper.mapAndWriteArguments(Search("$it")) + } + + verify(fixture.logger, times(1)).log(eq(SentryLevel.WARNING), any(), eq(error)) + verifyNoMoreInteractions(fixture.logger) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt new file mode 100644 index 00000000000..658720c9ba9 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt @@ -0,0 +1,503 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.ArgumentSource +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlin.test.assertFailsWith +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.junit.Test +import org.mockito.AdditionalAnswers.delegatesTo +import org.mockito.Mockito +import org.mockito.kotlin.any +import org.mockito.kotlin.argThat +import org.mockito.kotlin.doThrow +import org.mockito.kotlin.eq +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions +import org.mockito.kotlin.whenever + +class KotlinxBackStackEntryMapperPropertiesTest { + + @Serializable @SerialName("PropertyLess") class PropertyLess + + /** Encodes to its code alone, a string rather than a structure. */ + @Serializable(with = CodeSerializer::class) class Code(val code: String) + + object CodeSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("Code", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Code) { + encoder.encodeString(value.code) + } + + override fun deserialize(decoder: Decoder): Code = Code(decoder.decodeString()) + } + + /** Serializes [PropertyLess] with its own descriptor, except that reading its `kind` throws. */ + @OptIn(ExperimentalSerializationApi::class) + object KindThrowingPropertyLessSerializer : KSerializer { + private val delegate = PropertyLess.serializer().descriptor + + override val descriptor: SerialDescriptor = + Mockito.mock(SerialDescriptor::class.java, delegatesTo(delegate)).apply { + doThrow(IllegalStateException("no kind")).whenever(this).kind + } + + override fun serialize(encoder: Encoder, value: PropertyLess) { + encoder.encodeStructure(descriptor) {} + } + + override fun deserialize(decoder: Decoder): PropertyLess = throw UnsupportedOperationException() + } + + /** Writes [Detail]'s id inside its structure without naming the element it belongs to. */ + private object KeylessDetailSerializer : KSerializer { + override val descriptor: SerialDescriptor = Detail.serializer().descriptor + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { (this as Encoder).encodeString(value.id) } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + /** An id over the argument character limit. */ + private val overLimitId = "x".repeat(MAX_ARGUMENT_CHARACTERS + 1) + + // Properties + + @Test + fun `records encoded properties as arguments when properties are included`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Detail("2"))) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("Detail", mapOf("id" to "1")), + SentryBackStackEntry("Detail", mapOf("id" to "2")), + ) + .inOrder() + } + + @Test + fun `doesn't encode properties when properties are excluded`() { + val fixture = KotlinxMapperFixture.create(includeProperties = false) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(fixture.detailSerializer.serialized).isEmpty() + } + + @Test + fun `records no arguments for objects`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + val mapped = mapper.map(Home) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Home", arguments = null)) + } + + @Test + fun `records no arguments for classes without properties`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { PropertyLess.serializer() } + val mapper = fixture.mapper + + val mapped = mapper.map(PropertyLess()) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("PropertyLess", arguments = null)) + } + + @Test + fun `records the value of entries whose serializer doesn't encode a class`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { CodeSerializer } + val mapper = fixture.mapper + + val mapped = mapper.map(Code("abc")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Code", mapOf("value" to "abc"))) + } + + @Test + fun `doesn't encode properties of entries that can't be named`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { null } + val mapper = fixture.mapper + + val mapped = mapper.mapAndReadArguments(Detail("1")) + + assertThat(mapped).isNull() + assertThat(fixture.detailSerializer.serialized).isEmpty() + } + + @Test + fun `keeps recording arguments for other types after a type's name lookup throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { + if (it == Detail::class.java) throw NoSuchMethodError() else fixture.serializers[it] + } + val mapper = fixture.mapper + mapper.map(Detail("1")) + + val mapped = mapper.map(Search("shoes")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Search", mapOf("query" to "shoes"))) + } + + // Properties that can't be encoded + + @Test + fun `keeps the name and records only the encoding failure when a type's properties can't be encoded`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + val mapped = mapper.map(WithContextual("1", Unregistered("2"))) + + assertThat(mapped) + .isEqualTo( + SentryBackStackEntry("WithContextual", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + ) + } + + @Test + fun `keeps encoding a type's properties after they couldn't be encoded once`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = SerializationException("unencodable") + val mapper = fixture.mapper + mapper.mapAndReadArguments(Detail("1")) + fixture.detailSerializer.error = null + + val mapped = mapper.map(Detail("2")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail", mapOf("id" to "2"))) + } + + @Test + fun `logs an unsupported-properties warning once per type whose properties can't be encoded`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = SerializationException("detail unencodable") + fixture.searchSerializer.error = SerializationException("search unencodable") + val mapper = fixture.mapper + + repeat(3) { + mapper.mapAndReadArguments(Detail("$it")) + mapper.mapAndReadArguments(Search("$it")) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(Detail::class.java.name), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(Search::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `doesn't log that a type's properties can't be encoded until its arguments are read`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = SerializationException("unencodable") + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + verifyNoInteractions(fixture.logger) + } + + // Properties over the argument limits + + @Test + fun `logs a warning with the drop reason once per type whose properties exceed the argument limits`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + repeat(3) { + mapper.mapAndReadArguments(Detail(overLimitId)) + mapper.mapAndReadArguments(Search(overLimitId)) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + eq(Detail::class.java.name), + eq(ArgumentDropReason.CHARACTER_LIMIT.serializedValue), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + eq(Search::class.java.name), + eq(ArgumentDropReason.CHARACTER_LIMIT.serializedValue), + ) + } + + // Property encoding that throws a LinkageError + + @Test + fun `keeps encoding a type's properties after one entry's encoding throws a LinkageError`() { + // A serializer may only reach a class that fails to link for some values (e.g., one subtype of + // a sealed property), so a LinkageError only drops the arguments of the entry whose encoding + // threw it, and leaves other types alone. + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = NoClassDefFoundError() + fixture.detailSerializer.failsFor = { it.id == "unlinkable" } + val mapper = fixture.mapper + + val mapped = + listOf( + mapper.mapAndReadArguments(Detail("unlinkable")), + mapper.mapAndReadArguments(Search("shoes")), + mapper.mapAndReadArguments(Detail("2")), + ) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + SentryBackStackEntry("Search", mapOf("query" to "shoes")), + SentryBackStackEntry("Detail", mapOf("id" to "2")), + ) + .inOrder() + } + + @Test + fun `logs a warning once per type whose property encoding throws a LinkageError`() { + val error = AbstractMethodError() + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = error + fixture.searchSerializer.error = error + val mapper = fixture.mapper + + repeat(3) { + mapper.mapAndReadArguments(Detail("$it")) + mapper.mapAndReadArguments(Search("$it")) + } + + // Each entry's encoding threw, yet each type's warning was logged once. + assertThat(fixture.detailSerializer.serialized) + .containsExactly(Detail("0"), Detail("1"), Detail("2")) + assertThat(fixture.searchSerializer.serialized) + .containsExactly(Search("0"), Search("1"), Search("2")) + verify(fixture.logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(Detail::class.java.name)) + verify(fixture.logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(Search::class.java.name)) + verifyNoMoreInteractions(fixture.logger) + } + + // Property encoding that throws other exceptions + + @Test + fun `logs a serializer-threw warning once per type whose property encoding throws an exception`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = IllegalArgumentException("invalid id") + fixture.searchSerializer.error = IllegalArgumentException("invalid query") + val mapper = fixture.mapper + + repeat(3) { + mapper.mapAndReadArguments(Detail("$it")) + mapper.mapAndReadArguments(Search("$it")) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(SERIALIZER_THREW) }, + eq(Detail::class.java.name), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(SERIALIZER_THREW) }, + eq(Search::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `logs a serializer-threw warning once for an entry whose arguments are read and then written`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = IllegalArgumentException("invalid id") + val arguments = fixture.mapper.map(Detail("1"))?.arguments!! + arguments.size + + assertFailsWith { + (arguments as ArgumentSource).writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(fixture.detailSerializer.serialized).containsExactly(Detail("1")) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(SERIALIZER_THREW) }, + eq(Detail::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + // Serializers that write outside the encoder's protocol + + @Test + fun `drops the arguments of an entry whose serializer writes a value outside its elements`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { KeylessDetailSerializer } + + val mapped = fixture.mapper.mapAndReadArguments(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `logs a protocol-violation warning for a serializer that writes outside its elements`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { KeylessDetailSerializer } + + fixture.mapper.mapAndReadArguments(Detail("1")) + + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(PROTOCOL_VIOLATION) }, + eq(Detail::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + // Serializer descriptors whose shape throws + + @Test + fun `keeps the name and records the properties when an entry's descriptor's elementsCount throws`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { + ShapeThrowingDetailSerializer(elementsCountError = IllegalStateException("no count")) + } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail", mapOf("id" to "1"))) + } + + @Test + fun `keeps the name and records only the encoding failure when an entry's descriptor's kind throws`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(kindError = IllegalStateException("no kind")) } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `keeps the name and records only the encoding failure when a property-less entry's descriptor's kind throws`() { + // Without properties, whether the entry may still have arguments depends on its kind. + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { KindThrowingPropertyLessSerializer } + val mapper = fixture.mapper + + val mapped = mapper.map(PropertyLess()) + + assertThat(mapped) + .isEqualTo( + SentryBackStackEntry("PropertyLess", droppedBy(ArgumentDropReason.ENCODING_FAILED)), + ) + } + + @Test + fun `logs a warning once for a type whose descriptor's kind throws`() { + val error = IllegalStateException("no kind") + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(kindError = error) } + val mapper = fixture.mapper + + repeat(3) { mapper.mapAndReadArguments(Detail("$it")) } + + verify(fixture.logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(Detail::class.java.name)) + } + + @Test + fun `keeps the name and records the properties when an entry's descriptor's elementsCount throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(elementsCountError = NoClassDefFoundError()) } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail", mapOf("id" to "1"))) + } + + @Test + fun `keeps the name and records only the encoding failure when an entry's descriptor's kind throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(kindError = NoClassDefFoundError()) } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `propagates fatal errors thrown by an entry's descriptor's elementsCount`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.lookUp = { ShapeThrowingDetailSerializer(elementsCountError = error) } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + private companion object { + const val UNSUPPORTED_PROPERTIES = + "Contextual and open polymorphic properties and structured map keys aren't supported" + + const val SERIALIZER_THREW = "because a serializer threw" + + const val PROTOCOL_VIOLATION = "because a value was written outside the encoder's protocol" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt index 7a71d52b043..269ec658238 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt @@ -860,16 +860,16 @@ class KotlinxBackStackEntryMapperTest { mapper = if (isAnnotatedSerializable == null) { KotlinxBackStackEntryMapper( - recordingLookUp, + lookUpSerializer = recordingLookUp, checkCompatibility = checkLinkage, logger = { logger }, ) } else { KotlinxBackStackEntryMapper( - recordingLookUp, - isAnnotatedSerializable, - checkLinkage, - { logger }, + lookUpSerializer = recordingLookUp, + isAnnotatedSerializable = isAnnotatedSerializable, + checkCompatibility = checkLinkage, + logger = { logger }, ) } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt index 5e64aeefd3b..9819eea93ee 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt @@ -1,6 +1,8 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink import kotlin.test.assertFailsWith import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.builtins.serializer @@ -60,4 +62,77 @@ class KotlinxCompatibilityCheckTest { fun `checkKotlinxCompatibility() - succeeds without reading a serial name when no serializer is found`() { checkKotlinxCompatibility { null } } + + // kotlinxEncoderIncompatibility() + + @Test + fun `kotlinxEncoderIncompatibility() - returns null for the kotlinx serialization version on the classpath`() { + val error = kotlinxEncoderIncompatibility() + + assertThat(error).isNull() + } + + @Test + fun `encodeCompatibilityCheckValue() - encodes a null and an unsigned value beyond the signed range`() { + val sink = TreeArgumentSink(ArgumentBudget()) + + encodeCompatibilityCheckValue(sink) + + assertThat(sink.argumentsOrThrow()) + .isEqualTo( + mapOf( + "first" to "check", + "second" to listOf(1, null), + "third" to mapOf("count" to 4_294_967_295L), + ), + ) + } + + @Test + fun `kotlinxEncoderIncompatibility() - returns EncoderProducedUnexpectedOutput when the encoding differs`() { + val error = kotlinxEncoderIncompatibility { sink -> + sink.key("first") + sink.scalar("other") + } + + assertThat(error).isInstanceOf(EncoderProducedUnexpectedOutput::class.java) + } + + @Test + fun `kotlinxEncoderIncompatibility() - returns a LinkageError the encoder throws instead of rethrowing it`() { + // Rethrown, the error would fail the mapper's creation and disable names too. + val errors = listOf(NoSuchMethodError(), NoClassDefFoundError(), VerifyError()) + + val failures = errors.map { error -> kotlinxEncoderIncompatibility { throw error } } + + assertThat(failures).containsExactlyElementsIn(errors).inOrder() + } + + @Test + fun `kotlinxEncoderIncompatibility() - returns a non-fatal exception the encoder throws`() { + val error = NullPointerException() + + val failure = kotlinxEncoderIncompatibility { throw error } + + assertThat(failure).isSameInstanceAs(error) + } + + @Test + fun `kotlinxEncoderIncompatibility() - rethrows a fatal error the encoder throws that isn't a LinkageError`() { + val error = OutOfMemoryError() + + val thrown = assertFailsWith { kotlinxEncoderIncompatibility { throw error } } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `EncoderProducedUnexpectedOutput is a RuntimeException with a fixed message`() { + val error = EncoderProducedUnexpectedOutput() + + assertThat(error).isInstanceOf(RuntimeException::class.java) + assertThat(error) + .hasMessageThat() + .isEqualTo("The kotlinx.serialization properties encoder produced unexpected output.") + } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt index b500c609c3c..2b567c34728 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt @@ -5,13 +5,21 @@ import io.sentry.ILogger import io.sentry.SentryLevel import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.common.MIN_KOTLINX_SERIALIZATION_VERSION +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlinx.serialization.SerializationException import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.times import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions class KotlinxMapperDiagnosticsTest { @@ -19,6 +27,7 @@ class KotlinxMapperDiagnosticsTest { private val diagnostics = KotlinxMapperDiagnostics { logger } private val type = Detail::class.java + private val otherType = Search::class.java // notSerializable() @@ -58,6 +67,145 @@ class KotlinxMapperDiagnosticsTest { .startsWith("Nav3 couldn't verify kotlinx.serialization compatibility") } + // incompatibleEncoder() + + @Test + fun `incompatibleEncoder() - logs a warning with the error and compatibility advice`() { + val error = NoSuchMethodError("encodeStructure") + + diagnostics.incompatibleEncoder(error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), message.capture(), eq(error)) + assertThat(message.firstValue) + .startsWith( + "Nav3 SerialNameAndProperties is incompatible with this app's kotlinx.serialization " + + "version.", + ) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + // propertyFailure() + + @Test + fun `propertyFailure() - logs an over-limits warning with the type and drop reason for a DropArgumentsException`() { + val error = DropArgumentsException(ArgumentDropReason.CHARACTER_LIMIT, warning = null) + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger) + .log( + eq(SentryLevel.WARNING), + message.capture(), + eq(type.name), + eq(ArgumentDropReason.CHARACTER_LIMIT.serializedValue), + ) + assertThat(message.firstValue).startsWith("Nav3 dropped arguments for type") + } + + @Test + fun `propertyFailure() - logs a SerializationException attached to an unsupported-properties warning`() { + val error = SerializationException("unencodable") + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains(UNSUPPORTED_PROPERTIES) + } + + @Test + fun `propertyFailure() - logs a LinkageError attached to a warning with compatibility advice`() { + val error = NoClassDefFoundError("kotlinx/serialization/internal/Missing") + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + verifyNoMoreInteractions(logger) + } + + @Test + fun `propertyFailure() - logs an ArgumentProtocolException attached to a protocol-violation warning`() { + val error = ArgumentProtocolException("A map value was written without a key.") + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains(PROTOCOL_VIOLATION) + assertThat(message.firstValue).doesNotContain(SERIALIZER_THREW) + verifyNoMoreInteractions(logger) + } + + @Test + fun `propertyFailure() - logs a serializer's exception attached to a serializer-threw warning`() { + val error = IllegalArgumentException("invalid id") + + diagnostics.propertyFailure(type, error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains(SERIALIZER_THREW) + verifyNoMoreInteractions(logger) + } + + @Test + fun `propertyFailure() - logs each kind of failure once per type`() { + val failures = + listOf( + DropArgumentsException(ArgumentDropReason.MAX_COUNT, warning = null), + SerializationException("unencodable"), + AbstractMethodError(), + IllegalStateException("thrown"), + ArgumentProtocolException("A map value was written without a key."), + ) + + repeat(2) { failures.forEach { diagnostics.propertyFailure(type, it) } } + + verify(logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + eq(type.name), + eq(ArgumentDropReason.MAX_COUNT.serializedValue), + ) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(failures[1]), any(), eq(type.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(failures[2]), any(), eq(type.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(failures[3]), any(), eq(type.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(failures[4]), any(), eq(type.name)) + verifyNoMoreInteractions(logger) + } + + @Test + fun `propertyFailure() - logs the same kind of failure again for another type`() { + val error = SerializationException("unencodable") + + diagnostics.propertyFailure(type, error) + diagnostics.propertyFailure(otherType, error) + + verify(logger) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(type.name), + ) + verify(logger) + .log( + eq(SentryLevel.WARNING), + any(), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(otherType.name), + ) + } + // unresolved() @Test @@ -128,5 +276,12 @@ class KotlinxMapperDiagnosticsTest { private companion object { const val KOTLINX_SERIALIZATION_FLOOR_PROPERTY = "nav3.kotlinxSerializationFloor" + + const val UNSUPPORTED_PROPERTIES = + "Contextual and open polymorphic properties and structured map keys aren't supported" + + const val SERIALIZER_THREW = "because a serializer threw" + + const val PROTOCOL_VIOLATION = "because a value was written outside the encoder's protocol" } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt new file mode 100644 index 00000000000..04e0914ea30 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt @@ -0,0 +1,147 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.ILogger +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentSource +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.mockito.AdditionalAnswers.delegatesTo +import org.mockito.Mockito +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +/** + * Serializes [Detail] with a descriptor whose shape, its `elementsCount` and `kind`, throws + * [elementsCountError] and [kindError] when set. Counts every read of the shape in [shapeReads]. + * Encoding reads the descriptor's `kind`, so it throws [kindError] too. + */ +@OptIn(ExperimentalSerializationApi::class) +internal class ShapeThrowingDetailSerializer( + private val elementsCountError: Throwable? = null, + private val kindError: Throwable? = null, +) : KSerializer { + var shapeReads = 0 + + private val delegate = Detail.serializer().descriptor + + override val descriptor: SerialDescriptor = + Mockito.mock(SerialDescriptor::class.java, delegatesTo(delegate)).apply { + doAnswer { + shapeReads++ + elementsCountError?.let { error -> throw error } + delegate.elementsCount + } + .whenever(this) + .elementsCount + doAnswer { + shapeReads++ + kindError?.let { error -> throw error } + delegate.kind + } + .whenever(this) + .kind + } + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { encodeStringElement(descriptor, 0, value.id) } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() +} + +/** + * Stands in for the properties encoder's compatibility check, reporting [error] (or `null` if the + * encoder is compatible), so that mapper tests don't depend on the real check. Counts its runs in + * [checks]. + */ +internal class FakeEncoderCheck(private val error: Throwable? = null) { + var checks = 0 + + fun check(): Throwable? { + checks++ + return error + } +} + +/** + * A [KotlinxBackStackEntryMapper] whose serializer lookup returns [serializers] by default. The + * mapper only looks up `@Serializable` types, so [lookUp] never sees any others. Its compatibility + * checks find the app's kotlinx.serialization version compatible by default. + * + * With `useDefaultLookUp = true`, the mapper uses its real serializer lookup, so [lookUp] and + * [lookedUpTypes] are unused. + */ +internal class KotlinxMapperFixture +private constructor( + includeProperties: Boolean, + useDefaultLookUp: Boolean, + val encoderCheck: FakeEncoderCheck, +) { + val logger = mock() + + val detailSerializer = RecordingSerializer(Detail.serializer()) + val searchSerializer = RecordingSerializer(Search.serializer()) + val serializers: Map, KSerializer<*>> = + mapOf( + Home::class.java to Home.serializer(), + Detail::class.java to detailSerializer, + Search::class.java to searchSerializer, + WithContextual::class.java to WithContextual.serializer(), + ) + + val lookedUpTypes = mutableListOf>() + var lookUp: (Class<*>) -> KSerializer<*>? = { serializers[it] } + + val mapper = + if (useDefaultLookUp) { + KotlinxBackStackEntryMapper( + includeProperties = includeProperties, + checkCompatibility = {}, + checkEncoderCompatibility = encoderCheck::check, + logger = { logger }, + ) + } else { + KotlinxBackStackEntryMapper( + includeProperties = includeProperties, + lookUpSerializer = { + lookedUpTypes += it + lookUp(it) + }, + checkCompatibility = {}, + checkEncoderCompatibility = encoderCheck::check, + logger = { logger }, + ) + } + + companion object { + fun create( + includeProperties: Boolean = false, + useDefaultLookUp: Boolean = false, + encoderCheck: FakeEncoderCheck = FakeEncoderCheck(), + ) = KotlinxMapperFixture(includeProperties, useDefaultLookUp, encoderCheck) + } +} + +/** 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 [DropArgumentsException] a failure + * throws. + */ +internal fun KotlinxBackStackEntryMapper.mapAndWriteArguments(entry: Any) { + val arguments = map(entry)?.arguments as ArgumentSource + try { + arguments.writeTo(TreeArgumentSink(ArgumentBudget())) + } catch (_: DropArgumentsException) {} +}