diff --git a/CHANGELOG.md b/CHANGELOG.md index a677f265758..40218f3df45 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 kotlinx.serialization serial names ([#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)) ### Fixes diff --git a/sentry-android-navigation3/README.md b/sentry-android-navigation3/README.md index 2135233aefd..6d819112df3 100644 --- a/sentry-android-navigation3/README.md +++ b/sentry-android-navigation3/README.md @@ -6,7 +6,8 @@ Use `SentryNavEffect` alongside your `NavDisplay` to record navigation transacti users move around your app. Configure the data you want captured via `SentryNavOptions`. Because Nav3 back stacks can have arbitrary key types, host apps need to provide `SentryNavEffect` with a mapping between their back stack -keys and the data Sentry should display for each (see `BackStackEntryMapper` 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/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index 0ce6a4f534e..b325c8ad1ce 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 @@ -54,13 +54,17 @@ public class SentryBackStackEntry( /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * If you use kotlinx.serialization, see [SerialName] for convenient, out-of-the-box mappers. - * Otherwise, provide your own implementation. (Note: Custom implementations can always fall back to - * `SerialName` for any entries that don't have to be special-cased.) + * If you use kotlinx.serialization, see [SerialName] and [SerialNameAndProperties] for convenient, + * out-of-the-box mappers. Otherwise, provide your own implementation. (Note: Custom implementations + * can always fall back to `SerialName` or `SerialNameAndProperties` for any entries that don't have + * to be special-cased.) * * **Privacy / PII** * - * Custom mappers are responsible for filtering their own arguments. + * Built-in mappers that capture entry properties apply limited sensitive-data filtering before + * recording arguments; see [SerialNameAndProperties] for the filtering rules. Custom mappers are + * responsible for filtering their own arguments; Sentry does not apply its built-in sensitive-data + * filtering to arguments they supply themselves. * * Only return names and arguments that are known to be safe or have been pre-scrubbed. All * arguments remain subject to size and structural limits. @@ -144,6 +148,8 @@ public fun interface BackStackEntryMapper { * would return `"ProductDetail"` as the destination's name, but would ***not*** return the * destination's properties (`userId` and `productId`). * + * To return both entry names and properties, see [SerialNameAndProperties]. + * * **Name == SerialDescriptor.serialName** * * This mapper names each back stack entry after the entry's @@ -177,8 +183,8 @@ public fun interface BackStackEntryMapper { * * Entries share a Sentry name whenever their serializers share a serial name. In particular: * - * - All constants of an enum are named after the enum. A `@SerialName` on a constant does not - * change the destination name. + * - All constants of an enum are named after the enum. A `@SerialName` on a constant only + * changes how [SerialNameAndProperties] records the constant as an argument. * * - Classes that use the same custom serializer (`@Serializable(with = ...)`) are named after * that serializer's descriptor, which ignores a `@SerialName` on the class. @@ -189,5 +195,72 @@ public fun interface BackStackEntryMapper { @get:ApiStatus.Experimental public val SerialName: BackStackEntryMapper get() = BuiltInBackStackEntryMappers.serialName + + /** + * Like [SerialName], but also returns the properties of each back stack entry as Sentry + * arguments. + * + * For instance, given: + * ``` + * @Serializable + * @SerialName("ProductDetail") + * data class ProductDetail( + * val userId: String, + * val productId: String + * ) : NavKey + * ``` + * + * when navigating to `ProductDetail(userId = "123abc", productId = "zyx987")`, this mapper + * would return `"ProductDetail"` as the destination's name, along with the following arguments: + * ```json + * { + * "userId": "123abc", + * "productId": "zyx987" + * } + * ``` + * + * Returns `null` for any entries that can't be named (see [SerialName]). Sentry displays these + * entries as `"/unknown"` with no arguments. + * + * The argument limits described in [BackStackEntryMapper] apply. + * + * **Privacy / PII** + * + * This mapper returns arguments for every property of each back stack entry passed to it, which + * may include private data or PII. Almost all properties are sent as-is (see below for limited + * exceptions in the case of sensitive secrets). Neither `sendDefaultPii` nor the + * `dataCollection` options change what this mapper returns. + * + * Modify your use of this mapper if any entry in your back stack contains info you don't want + * sent to Sentry. For instance, i) use this mapper for all entries but filter out any + * properties you want to omit, or ii) use a custom [BackStackEntryMapper] that special-cases + * entries with sensitive info or PII and falls back to this mapper (or [SerialName]) for + * entries without it. See + * [Choosing Which Arguments to Send](https://docs.sentry.io/platforms/android/integrations/navigation/#choosing-which-arguments-to-send) + * for examples. + * + * **Limited filtering for sensitive secrets** + * + * Values are replaced with `"[Filtered]"` when their property's targeted name (i.e., their + * `@SerialName` if they have one, or else the property's name) contains a term from + * [Sentry's sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist) + * (ignoring case). This filters secrets like `authToken`, but leaves PII like `userEmail` + * unchanged. + * + * Matching follows the same rule Sentry SDKs use for HTTP headers, cookies, and query + * parameters, meaning it may filter harmless properties like `insideCart` (`sid`) or `keyword` + * (`key`). + * + * **Encoding and encoding failures** + * + * Properties are encoded on the first argument read, including by `equals` or `hashCode`. + * + * Failures preserve the entry's name and replace its arguments with a drop reason, e.g., + * `{"dropped_by_sentry": "encoding_failed"}`. Encoding errors are logged once per entry type + * when `debug` is enabled. + */ + @get:ApiStatus.Experimental + 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 eaa10605941..c6d638431d2 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 @@ -28,7 +28,23 @@ internal object BuiltInBackStackEntryMappers { // threads may each create and probe a mapper and log warnings, and all but the first // published instance would be discarded. create(logger) { - KotlinxBackStackEntryMapper(logger = logger) + KotlinxBackStackEntryMapper(includeProperties = false, logger = logger) + } + } + + /** + * Like [serialName], but also returns the properties of each back stack entry as Sentry + * arguments. + * + * Falls back to [UnavailableBackStackEntryMapper] if a mapper can't be created. + * + * See [BackStackEntryMapper.SerialNameAndProperties] for more details. + */ + val serialNameAndProperties: BackStackEntryMapper by + lazy(LazyThreadSafetyMode.PUBLICATION) { + // PUBLICATION, as for serialName. + create(logger) { + KotlinxBackStackEntryMapper(includeProperties = true, logger = logger) } } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md index bc8bb10067e..c922d77cf3f 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md @@ -9,6 +9,11 @@ The host app's `BackStackEntryMapper` supplies each entry's name and optional ar `SentryBackStackEntry`. Properties are the fields and values on the host's back stack entry; arguments are the values the mapper chooses to expose as `SentryBackStackEntry.arguments`. +When a host app uses the built-in `SerialNameAndProperties` mapper, the SDK maps entry properties to +arguments itself, in the [kotlinx subpackage](kotlinx/README.md). Hence `SerialNameAndProperties` and +`KotlinxPropertiesEncoder`, but `SentryBackStackEntry(arguments = ...)`. A custom mapper performs +that mapping on its end and hands us the resulting arguments. + Arguments are the mapper's output before sanitization. `BackStackConverter` normalizes entry names and sanitizes arguments before they are recorded. Sanitization can stringify values or drop an entry's arguments when they are invalid or exceed the limits in `ArgumentConstraints`. 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 fef70e5bd0d..9e20df27716 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,17 +5,35 @@ 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.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING import io.sentry.util.ExceptionUtils import java.lang.reflect.InvocationTargetException +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]. + */ internal class KotlinxBackStackEntryMapper( + /** + * True if this mapper should return each back stack entry's properties as arguments; false if + * they should be omitted. + */ + private val includeProperties: Boolean, /** * 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`. @@ -33,7 +51,7 @@ internal class KotlinxBackStackEntryMapper( private val serializableAnnotation: Class = Serializable::class.java // Serializer lookups use reflection and mapping runs on every navigation, so we cache each - // class's name. Cache size is bounded by the number of back stack entry types. + // 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) @@ -49,6 +67,19 @@ internal class KotlinxBackStackEntryMapper( ?.let { throw it } } + /** + * `true` if the app's kotlinx.serialization version doesn't support the properties encoder, in + * which case no arguments are produced for any entries. Instead, entries with properties record + * [ArgumentDropReason.ENCODING_FAILED] without being encoded. Names are unaffected. + */ + private val isEncodingIncompatible: Boolean = + includeProperties && + run { + val error = probe.encoderIncompatibility() ?: 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. @@ -56,7 +87,9 @@ internal class KotlinxBackStackEntryMapper( val cached = cachedType(type) val name = cached.name ?: return null - return SentryBackStackEntry(name) + val arguments = if (includeProperties) argumentsOf(type, cached, backStackEntry) else null + + return SentryBackStackEntry(name, arguments) } private fun cachedType(type: Class<*>): CachedType = @@ -84,10 +117,15 @@ internal class KotlinxBackStackEntryMapper( val serializer = lookup.serializer var error = lookup.error + var hasProperties = false val name = try { serializer?.descriptor?.let { descriptor -> - descriptor.serialName + // SerialName only needs the name. Read it before inspecting the shape so it isn't lost if + // shape lookup fails. + val serialName = descriptor.serialName + hasProperties = includeProperties && hasProperties(descriptor) + serialName } } catch (e: LinkageError) { // Treat descriptor linkage errors as type-specific, including incompatibilities caused by a @@ -105,7 +143,7 @@ internal class KotlinxBackStackEntryMapper( if (name == null) { diagnostics.unresolved(type, error) } - return if (name == null) UNRESOLVED else CachedType(name) + return if (name == null) UNRESOLVED else CachedType(serializer, name, hasProperties) } /** @@ -179,9 +217,55 @@ internal class KotlinxBackStackEntryMapper( SerializerLookup(serializer = null, error = t) } - /** A type's serial name, or `null` if the lookup failed. */ + /** + * Whether entries described by [descriptor] may have properties. A class or object without + * properties records no arguments, so its entries skip encoding. + */ + @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 because 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, + 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) + } + } + + /** + * A type's serializer and name, or `null`s if the lookup failed, and whether the type has + * properties to encode. A resolved name implies a serializer. + */ private class CachedType( + val serializer: KSerializer<*>?, val name: String?, + val hasProperties: Boolean = false, ) /** A type's serializer, or the error that made looking it up fail, if any. */ @@ -189,18 +273,27 @@ internal class KotlinxBackStackEntryMapper( private companion object { private const val NAME_LOOKUP_CAPABILITY = "name lookups" - private val UNRESOLVED = CachedType(name = null) + private val UNRESOLVED = CachedType(serializer = null, name = null) } } /** - * The warnings [KotlinxBackStackEntryMapper] logs when it can't name a back stack entry. + * The warnings [KotlinxBackStackEntryMapper] logs when it can't name a back stack entry or encode + * its properties. * * Only decides what's logged, and how often. Whether a type is looked up or encoded again is up to * the mapper. */ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { + /** + * 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() @@ -233,6 +326,20 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { ) } + /** + * Logs [error] indicating that the app's kotlinx.serialization version is incompatible with the + * properties encoder. 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 [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. @@ -264,6 +371,95 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { ) } + /** + * 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). + * + * Serializer exceptions can contain route data in their messages or causes, so for those we log + * only the entry type and the failure category. A [LinkageError] is attached: it names the + * classes and members that couldn't be linked or initialized, not route data, as linking and + * class initialization don't see the entry being encoded. + */ + fun propertyFailure(type: Class<*>, error: Throwable) { + when (error) { + is DropArguments -> + 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, + "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.", + 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, + "Nav3 couldn't encode properties for type %s because a serializer threw. Recording " + + "names without arguments.", + 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 serializer threw something other than a [SerializationException] or [LinkageError]. */ + THROWING, + + /** A class a serializer needs couldn't be linked, initialized, or found. */ + UNLOADABLE, + } + companion object { /** diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt index afc4bda12b4..701aa1ec82a 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt @@ -2,8 +2,11 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter import io.sentry.util.ExceptionUtils import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable /** @@ -13,16 +16,19 @@ import kotlinx.serialization.Serializable * * **Disambiguating serializer errors from library incompatibility** * - * Without a check like this, `KotlinxBackStackEntryMapper` would have to infer an incompatible - * kotlinx.serialization version from [LinkageError]s thrown while handling the host app's own back - * stack entry types. But such errors can also come from the host app's serializer code, and should - * therefore only fail for the entry types that can't be deserialized. `ProbeClass` and - * `ProbeObject` don't execute any host app code, so a `LinkageError` while handling them means the - * app's kotlinx.serialization version is incompatible. + * A [LinkageError] while handling a host app's back stack entry may come from that entry's + * serializer, so it mustn't disable mapping for other types. The SDK-owned `ProbeClass` and + * `ProbeObject` run no host app code, letting us check kotlinx.serialization compatibility + * independently. * - * Note: Only a `LinkageError` is conclusive. Any other failure, or a probe type whose serializer - * can't be found, leaves the check inconclusive: it's reported to the caller's `onInconclusive` and - * otherwise ignored, as a real type that hits the same failure is handled and logged on its own. + * The checks use different failure policies: + * + * - [nameLookupLinkageError]: only a [LinkageError] establishes incompatibility. Other failures, + * including a missing probe serializer, are reported through `onInconclusive`. Mapping continues, + * and failures for real entry types are handled and logged individually. + * + * - [encoderIncompatibility]: any exception or incorrect output disables property encoding. A + * broken encoder can silently record wrong arguments, so recording none is safer. */ internal interface KotlinxCompatibilityProbe { @@ -38,6 +44,17 @@ internal interface KotlinxCompatibilityProbe { */ fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? + /** + * Encodes [ProbeClass] using the same path as [KotlinxBackStackEntryMapper], checks that it links + * and runs, and verifies its output matches the known fixture. + * + * Returns an error if encoding fails or produces unexpected arguments, and `null` otherwise. + * Unlike [nameLookupLinkageError], every failure disables property encoding. An incompatible + * kotlinx.serialization version may throw something other than [LinkageError] (e.g., + * [NullPointerException] under R8), or silently encode incorrect arguments. + */ + fun encoderIncompatibility(): Throwable? + /** Probes the app's kotlinx.serialization version using [ProbeClass] and [ProbeObject]. */ companion object : KotlinxCompatibilityProbe { @@ -67,6 +84,46 @@ internal interface KotlinxCompatibilityProbe { return error } + override fun encoderIncompatibility(): Throwable? = encoderFailureOf { + val writer = TreeArgumentWriter(ArgumentBudget()) + @Suppress("UNCHECKED_CAST") + KotlinxPropertiesEncoder.encode( + ProbeClass.serializer() as KSerializer, + ProbeClass(), + writer, + ) + // An incompatible kotlinx.serialization version can link and run yet mis-encode properties + // under R8 without throwing. Verifying the fixture's output disables such a silently + // corrupting encoder instead of letting wrong arguments reach Sentry. + if (writer.argumentsOrThrow() == EXPECTED_PROBE_ENCODING) { + null + } else { + EncoderProducedUnexpectedOutput() + } + } + + /** + * Runs [check], returning the failure it reports or throws, or `null` if it reports none. + * Rethrows fatal errors other than [LinkageError]. + * + * A [LinkageError] is returned rather than rethrown so that an encoder that can't link only + * disables property encoding. Rethrown, it would escape the mapper's constructor, and + * `BuiltInBackStackEntryMappers` would fall back to a mapper that records no names either. + */ + internal inline fun encoderFailureOf(check: () -> Throwable?): Throwable? = + try { + check() + } catch (e: LinkageError) { + // Caught before rethrowIfFatal, which rethrows LinkageErrors. + e + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because an incompatible kotlinx.serialization version can fail the encoder in many + // ways, not only with a LinkageError. Any failure disables property encoding but keeps + // names, as recording wrong arguments would be worse than recording none. + ExceptionUtils.rethrowIfFatal(t) + t + } + /** * Runs [check], returning any [LinkageError] and rethrowing fatal errors. Returns `null` if the * check succeeds or is inconclusive. @@ -107,6 +164,15 @@ internal interface KotlinxCompatibilityProbe { val counts: Map = mapOf("count" to 1), ) + /** + * [ProbeClass]'s expected encoding. + * + * A kotlinx.serialization version that encodes it to anything else mis-encodes properties and + * must not be used. None of the keys are on the sensitive denylist, so none are filtered. + */ + private val EXPECTED_PROBE_ENCODING: Map = + mapOf("name" to "probe", "values" to listOf(1), "counts" to mapOf("count" to 1)) + /** * A known serializable object used to test serializer lookup for the host app's object-based * back stack entries. This lookup reads the object's singleton instance. @@ -114,3 +180,14 @@ internal interface KotlinxCompatibilityProbe { @Serializable internal object ProbeObject } } + +/** + * Signals that the encoder produced unexpected arguments for the SDK-owned `ProbeClass`, indicating + * incompatible kotlinx.serialization behavior. + * + * Carries a fixed message with no (potentially sensitive) back stack entry data. + */ +internal class EncoderProducedUnexpectedOutput : + RuntimeException( + "The kotlinx.serialization properties encoder produced unexpected output for a known fixture.", + ) 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 new file mode 100644 index 00000000000..022d796deff --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -0,0 +1,42 @@ +# `io.sentry.compose.navigation3.internal.backstack.kotlinx` + +Package contains code that accesses kotlinx.serialization APIs. + +## Dependency isolation + +kotlinx.serialization is a `compileOnly` dependency of `sentry-android-navigation3` that we assume is present, as every Nav3 app depends on +it via `navigation3-runtime`. + +The kotlinx.serialization ***version***, however, is determined by the host app, and may be incompatible with the APIs we use. To protect +against crashes, only classes in the `kotlinx` subpackage may reference kotlinx.serialization APIs, and code outside is limited to a single +entry point, viz., `BuiltInBackStackEntryMappers.create`. That's where we catch the `LinkageError` thrown if an incompatible version can't +be linked. + +Creating a mapper also runs `KotlinxCompatibilityProbe`, which names and encodes SDK-owned `@Serializable` types. Those run no app code, +so a `LinkageError` from them shows that the app's version is incompatible. If naming fails, creating the mapper fails. If encoding fails, +`SerialNameAndProperties` keeps entry names but drops their arguments with `encoding_failed`. A `LinkageError` thrown while mapping an entry +then fails only that entry's type. + +To keep our isolation policy intact: + +- put any new classes that reference kotlinx.serialization in the `.kotlinx` subpackage and give them a `Kotlinx*` prefix; +- don't expose kotlinx.serialization types outside the `Kotlinx*` classes; and +- reference a `Kotlinx*` class from outside the subpackage only via `BuiltInBackStackEntryMappers.create`. + +In addition, the `.kotlinx` subpackage may ***not*** depend on Android framework APIs, AndroidX, or the `internal.lifecycle` package. + +## Minification + +`sentry-android-navigation3` doesn't ship any R8 rules for kotlinx.serialization. Serial names survive R8 minification because Kotlin's +serialization compiler plugin fixes them at compile time. `KotlinxBackStackEntryMapper`'s fallback for private `@Serializable` objects +relies on members preserved by kotlinx.serialization's own consumer rules. + +`KotlinxBackStackEntryMapper` only names classes whose `@Serializable` annotation is present at runtime. kotlinx.serialization's consumer +rules (from our 1.7.3 floor on) keep that annotation: `kotlinx-serialization-common.pro` keeps `RuntimeVisibleAnnotations`, and +`kotlinx-serialization-r8.pro` keeps every `@Serializable` class (allowing shrinking and obfuscation) so that R8 full mode doesn't strip +the annotation. kotlinx.serialization relies on the annotation itself, e.g., to pick sealed-class serializers, so an app that disables those +rules breaks kotlinx.serialization as well as our mappers. + +We also don't ship rules for `@Serializable` classes with named companion objects. kotlinx.serialization's rules only cover those 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 +named-companion class names in every host app. 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 dfe941ee2f8..f1fb8ffb807 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 { @@ -395,6 +425,113 @@ class SentryNavEffectTest { ) } + @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() @@ -853,6 +990,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 7bb5c0594d6..87290f35c05 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 @@ -49,8 +49,38 @@ class BuiltInBackStackEntryMappersTest { .inOrder() } + @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 `serialName and serialNameAndProperties return the same mapper on every access`() { + assertThat(BuiltInBackStackEntryMappers.serialName) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialName) + assertThat(BuiltInBackStackEntryMappers.serialNameAndProperties) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialNameAndProperties) + } + // BackStackEntryMapper's companion mappers + @Test + fun `BackStackEntryMapper SerialName and SerialNameAndProperties return the built-in mappers`() { + assertThat(BackStackEntryMapper.SerialName) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialName) + assertThat(BackStackEntryMapper.SerialNameAndProperties) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialNameAndProperties) + } + @Test fun `BackStackEntryMapper SerialName can serve as the mapper for any entry type`() { val homeMapper: BackStackEntryMapper = BackStackEntryMapper.SerialName @@ -68,6 +98,16 @@ class BuiltInBackStackEntryMappersTest { assertThat(classLoader.wasKotlinxMapperRequested).isTrue() } + @Test + fun `BackStackEntryMapper SerialNameAndProperties maps entries to null when the kotlinx mapper can't be loaded`() { + val classLoader = KotlinxMapperHidingClassLoader() + + val mapper = classLoader.companionMapper("getSerialNameAndProperties") + + assertThat(mapper.map(Detail("1"))).isNull() + assertThat(classLoader.wasKotlinxMapperRequested).isTrue() + } + @Test fun `BackStackEntryMapper SerialName maps entries to null when kotlinx serialization is missing`() { val classLoader = KotlinxMapperHidingClassLoader(hidesKotlinx = true) @@ -80,6 +120,18 @@ class BuiltInBackStackEntryMappersTest { assertThat(classLoader.wasKotlinxRequested).isTrue() } + @Test + fun `BackStackEntryMapper 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() + } + // First access from several threads @Test @@ -97,6 +149,21 @@ class BuiltInBackStackEntryMappersTest { assertThat(race.laterMapper).isSameInstanceAs(race.thisThreadMapper) } + @Test + fun `BackStackEntryMapper SerialNameAndProperties holds no lock while creating the mapper logs`() { + val race = raceOnFirstAccess("getSerialNameAndProperties") + + assertThat(race.otherThreadLoggerGotAppLock).isTrue() + } + + @Test + fun `BackStackEntryMapper SerialNameAndProperties returns the mapper published first to racing threads`() { + val race = raceOnFirstAccess("getSerialNameAndProperties") + + assertThat(race.otherThreadMapper).isSameInstanceAs(race.thisThreadMapper) + assertThat(race.laterMapper).isSameInstanceAs(race.thisThreadMapper) + } + // MIN_KOTLINX_SERIALIZATION_VERSION @Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInMapperArgumentLimitsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInMapperArgumentLimitsTest.kt new file mode 100644 index 00000000000..e28d6c756a1 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInMapperArgumentLimitsTest.kt @@ -0,0 +1,141 @@ +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.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy +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 BuiltInMapperArgumentLimitsTest { + + @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 the built-in mapper 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 = + BackStackConverter( + ForwardingBackStackEntryMapper { BackStackEntryMapper.SerialNameAndProperties }, + logger, + ) + .convert(backStack, RetentionPolicy.KEEP_FIRST) + + 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 even if 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. + 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) + + assertThat(readFirst).isEqualTo(written) + assertThat(written) + .containsExactly( + NormalizedSentryBackStackEntry("/Catalog", mapOf("itemIds" to List(150) { it })), + NormalizedSentryBackStackEntry("/Draft", argumentDropReason = ArgumentDropReason.MAX_COUNT), + NormalizedSentryBackStackEntry("/Cart", argumentDropReason = ArgumentDropReason.MAX_COUNT), + ) + .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/BuiltInMapperParityTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInMapperParityTest.kt new file mode 100644 index 00000000000..491f78d96e1 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInMapperParityTest.kt @@ -0,0 +1,373 @@ +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.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy +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 the same back stack once with [BackStackEntryMapper.SerialNameAndProperties] and once + * with a custom mapper that returns the equivalent plain map for each entry, and checks that both + * record the same arguments and drop reasons. + * + * Also converts back stacks with a custom mapper that wraps the built-in one and filters its + * arguments, as `BackStackEntryMapper.SerialNameAndProperties` documents, and checks that it + * records the same drop reasons as the built-in mapper. The exception is an entry over an + * update-wide limit, which drops only its own arguments through the wrapper. That the wrapper + * records the arguments it doesn't remove is covered by `SentryNavEffectTest`. + * + * Each back stack is ordered top first, as [BackStackObserver] converts it. + */ +class BuiltInMapperParityTest { + + @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("Search") private data class SearchRoute(val query: String) + + @Serializable @SerialName("Nested") private data class NestedRoute(val child: NestedRoute?) + + @Serializable + @SerialName("FilterCounts") + private data class FilterCountsRoute(val counts: Map) + + @Serializable(with = UnencodableSerializer::class) private class UnencodableRoute + + /** 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() + } + + /** Wraps the built-in mapper and removes the `email` argument, as its KDoc documents. */ + private val emailFilteringMapper = + BackStackEntryMapper { entry -> + BackStackEntryMapper.SerialNameAndProperties.map(entry)?.let { mapped -> + SentryBackStackEntry(mapped.name, mapped.arguments?.filterKeys { it != "email" }) + } + } + + private val cart = CartRoute(cartId = "c-1") + private val plainCart = SentryBackStackEntry("Cart", mapOf("cartId" to "c-1")) + + private val logger = mock() + + @Test + fun `both mappers record 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), + ), + ) + val backStack = listOf(order, cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val custom = convertWithPlainMapper(backStack, order to plainOrder, cart to plainCart) + + assertThat(custom).isEqualTo(builtIn) + assertThat(builtIn) + .containsExactly( + NormalizedSentryBackStackEntry( + "/Order", + 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), + ), + ), + NormalizedSentryBackStackEntry("/Cart", mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + @Test + fun `both mappers drop the arguments of an entry over the argument count limit, and of 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 plainCatalog = SentryBackStackEntry("Catalog", mapOf("prices" to prices)) + val backStack = listOf(catalog, cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val custom = convertWithPlainMapper(backStack, catalog to plainCatalog, cart to plainCart) + + assertThat(custom).isEqualTo(builtIn) + assertThat(builtIn) + .containsExactly( + NormalizedSentryBackStackEntry( + "/Catalog", + argumentDropReason = ArgumentDropReason.MAX_COUNT, + ), + NormalizedSentryBackStackEntry("/Cart", argumentDropReason = ArgumentDropReason.MAX_COUNT), + ) + .inOrder() + } + + @Test + fun `both mappers drop the arguments of an entry over the character limit, and of older entries`() { + // The query alone is one character over the limit of MAX_ARGUMENT_CHARACTERS per update. + val query = "q".repeat(MAX_ARGUMENT_CHARACTERS + 1) + val search = SearchRoute(query = query) + val plainSearch = SentryBackStackEntry("Search", mapOf("query" to query)) + val backStack = listOf(search, cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val custom = convertWithPlainMapper(backStack, search to plainSearch, cart to plainCart) + + assertThat(custom).isEqualTo(builtIn) + assertThat(builtIn) + .containsExactly( + NormalizedSentryBackStackEntry( + "/Search", + argumentDropReason = ArgumentDropReason.CHARACTER_LIMIT, + ), + NormalizedSentryBackStackEntry( + "/Cart", + argumentDropReason = ArgumentDropReason.CHARACTER_LIMIT, + ), + ) + .inOrder() + } + + @Test + fun `both mappers drop 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) + val plainNested = + SentryBackStackEntry("Nested", plainNestedArguments(levels = MAX_ARGUMENT_DEPTH + 1)) + val backStack = listOf(nested, cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val custom = convertWithPlainMapper(backStack, nested to plainNested, cart to plainCart) + + assertThat(custom).isEqualTo(builtIn) + assertThat(builtIn) + .containsExactly( + NormalizedSentryBackStackEntry( + "/Nested", + argumentDropReason = ArgumentDropReason.INVALID_STRUCTURE, + ), + NormalizedSentryBackStackEntry("/Cart", mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + @Test + fun `both mappers drop the arguments of an entry with duplicate map keys, but not of older entries`() { + val filterCounts = FilterCountsRoute(counts = mapOf(null to 1, "null" to 2)) + val plainFilterCounts = + SentryBackStackEntry("FilterCounts", mapOf("counts" to mapOf(null to 1, "null" to 2))) + val backStack = listOf(filterCounts, cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val custom = + convertWithPlainMapper(backStack, filterCounts to plainFilterCounts, cart to plainCart) + + assertThat(custom).isEqualTo(builtIn) + assertThat(builtIn) + .containsExactly( + NormalizedSentryBackStackEntry( + "/FilterCounts", + argumentDropReason = ArgumentDropReason.DUPLICATE_KEY, + ), + NormalizedSentryBackStackEntry("/Cart", mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + // A custom mapper that wraps the built-in one + + @Test + fun `a mapper that wraps the built-in one records the same encoding failure for an entry that can't be encoded`() { + val backStack = listOf(UnencodableRoute(), cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val wrapped = convert(backStack, emailFilteringMapper) + + assertThat(wrapped.serialize()).isEqualTo(builtIn.serialize()) + assertThat(wrapped.serialize()) + .containsExactly( + mapOf( + "entry" to "/Unencodable", + "entry_arguments" to mapOf("dropped_by_sentry" to "encoding_failed"), + ), + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + @Test + fun `a mapper that wraps the built-in one records the same drop reason for an entry nested past the depth limit`() { + val backStack = listOf(nestedRoute(levels = MAX_ARGUMENT_DEPTH + 1), cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val wrapped = convert(backStack, emailFilteringMapper) + + assertThat(wrapped.serialize()).isEqualTo(builtIn.serialize()) + assertThat(wrapped.serialize()) + .containsExactly( + mapOf( + "entry" to "/Nested", + "entry_arguments" to mapOf("dropped_by_sentry" to "invalid_structure"), + ), + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + @Test + fun `a mapper that wraps the built-in one records the same drop reason for an entry with duplicate map keys`() { + val backStack = listOf(FilterCountsRoute(counts = mapOf(null to 1, "null" to 2)), cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val wrapped = convert(backStack, emailFilteringMapper) + + assertThat(wrapped.serialize()).isEqualTo(builtIn.serialize()) + assertThat(wrapped.serialize()) + .containsExactly( + mapOf( + "entry" to "/FilterCounts", + "entry_arguments" to mapOf("dropped_by_sentry" to "duplicate_key"), + ), + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + @Test + fun `a mapper that wraps the built-in one drops only the arguments of an entry over the character limit`() { + val search = SearchRoute(query = "q".repeat(MAX_ARGUMENT_CHARACTERS + 1)) + val backStack = listOf(search, cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val wrapped = convert(backStack, emailFilteringMapper) + + assertThat(builtIn.last().argumentDropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(wrapped.serialize()) + .containsExactly( + mapOf( + "entry" to "/Search", + "entry_arguments" to mapOf("dropped_by_sentry" to "max_character_limit_exceeded"), + ), + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + @Test + fun `a mapper that wraps the built-in one drops only the arguments of an entry over the argument count limit`() { + val catalog = CatalogRoute(prices = (0..MAX_ARGUMENT_VALUES).associate { "item$it" to it }) + val backStack = listOf(catalog, cart) + + val builtIn = convertWithBuiltInMapper(backStack) + val wrapped = convert(backStack, emailFilteringMapper) + + assertThat(builtIn.last().argumentDropReason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(wrapped.serialize()) + .containsExactly( + mapOf( + "entry" to "/Catalog", + "entry_arguments" to mapOf("dropped_by_sentry" to "max_argument_count_exceeded"), + ), + mapOf("entry" to "/Cart", "entry_arguments" to mapOf("cartId" to "c-1")), + ) + .inOrder() + } + + private fun convertWithBuiltInMapper(backStack: List): List = + convert(backStack, BackStackEntryMapper.SerialNameAndProperties) + + /** Converts [backStack] with a custom mapper that returns each entry's paired plain entry. */ + private fun convertWithPlainMapper( + backStack: List, + vararg plainEntries: Pair, + ): List { + val plainEntriesByEntry = plainEntries.toMap() + return convert(backStack) { entry -> plainEntriesByEntry.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/KotlinxBackStackEntryMapperProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt index 8703282b6fc..823b20aee90 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt @@ -4,9 +4,12 @@ import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason import io.sentry.compose.navigation3.internal.backstack.kotlinx.FakeCompatibilityProbe.Inconclusive +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import kotlin.test.assertFailsWith import org.junit.Test +import org.mockito.kotlin.any import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq @@ -15,6 +18,7 @@ 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 [KotlinxCompatibilityProbe] finds. */ class KotlinxBackStackEntryMapperProbeTest { @@ -37,7 +41,7 @@ class KotlinxBackStackEntryMapperProbeTest { val thrown = assertFailsWith { - KotlinxBackStackEntryMapper(logger = { mock() }, probe = probe) + KotlinxBackStackEntryMapper(includeProperties = false, logger = { mock() }, probe = probe) } assertThat(thrown).isSameInstanceAs(error) @@ -50,7 +54,7 @@ class KotlinxBackStackEntryMapperProbeTest { val probe = FakeCompatibilityProbe(nameLookupError = NoSuchMethodError()) assertFailsWith { - KotlinxBackStackEntryMapper(logger = { logger }, probe = probe) + KotlinxBackStackEntryMapper(includeProperties = true, logger = { logger }, probe = probe) } verifyNoInteractions(logger) @@ -103,6 +107,215 @@ class KotlinxBackStackEntryMapperProbeTest { ) } + // Property encoding check + + @Test + fun `logs nothing when created with properties included for a kotlinx version the probe finds compatible`() { + val fixture = + KotlinxMapperFixture.create(includeProperties = true, probe = FakeCompatibilityProbe()) + + fixture.mapper + + verifyNoInteractions(fixture.logger) + } + + @Test + fun `checks the properties encoder once when created with properties included`() { + val probe = FakeCompatibilityProbe() + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + val mapper = fixture.mapper + + repeat(3) { mapper.mapAndReadArguments(Detail("$it")) } + + assertThat(probe.encodingChecks).isEqualTo(1) + } + + @Test + fun `never checks the properties encoder when properties are excluded`() { + // No incompatible check is logged, as the check isn't run when properties are excluded. + val probe = FakeCompatibilityProbe(encoderError = NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = false, probe = probe) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(probe.encodingChecks).isEqualTo(0) + verifyNoInteractions(fixture.logger) + } + + @Test + fun `keeps the name and records only the encoding failure when the properties encoder is incompatible`() { + val probe = FakeCompatibilityProbe(encoderError = NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + 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 probe's failure handling instead of returning it. + val probe = + object : KotlinxCompatibilityProbe { + override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? = + null + + override fun encoderIncompatibility(): Throwable? = + KotlinxCompatibilityProbe.encoderFailureOf { + throw NoSuchMethodError() + } + } + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + val mapper = fixture.mapper + + 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 probe = FakeCompatibilityProbe(encoderError = NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + 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 probe = FakeCompatibilityProbe(encoderError = NoSuchMethodError()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + val mapper = fixture.mapper + + mapper.mapAndReadArguments(Detail("1")) + mapper.mapAndWriteArguments(Detail("2")) + + assertThat(fixture.detailSerializer.serialized).isEmpty() + } + + @Test + fun `logs a warning with the error and compatibility advice when created for an incompatible properties encoder`() { + val error = NoSuchMethodError("encodeStructure") + val probe = FakeCompatibilityProbe(encoderError = error) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + + val message = argumentCaptor() + verify(fixture.logger, times(1)).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) + } + + @Test + fun `logs nothing more for entries mapped when the properties encoder is incompatible`() { + val error = NoSuchMethodError() + val probe = FakeCompatibilityProbe(encoderError = error) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + 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) + } + + @Test + fun `keeps the name and records only the encoding failure when the encoder fails without a LinkageError`() { + val probe = FakeCompatibilityProbe(encoderError = NullPointerException()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `records no arguments for objects when the encoder fails without a LinkageError`() { + val probe = FakeCompatibilityProbe(encoderError = NullPointerException()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + val mapper = fixture.mapper + + val mapped = mapper.map(Home) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Home", arguments = null)) + } + + @Test + fun `doesn't encode properties when the encoder fails without a LinkageError`() { + val probe = FakeCompatibilityProbe(encoderError = NullPointerException()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + val mapper = fixture.mapper + + mapper.mapAndReadArguments(Detail("1")) + mapper.mapAndWriteArguments(Detail("2")) + + assertThat(fixture.detailSerializer.serialized).isEmpty() + } + + @Test + fun `logs a warning with the error and compatibility advice when the encoder fails without a LinkageError`() { + val error = NullPointerException("encodeStructure") + val probe = FakeCompatibilityProbe(encoderError = error) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + + val message = argumentCaptor() + verify(fixture.logger, times(1)).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) + } + + @Test + fun `keeps the name and records only the encoding failure when the encoder produces unexpected output`() { + val probe = FakeCompatibilityProbe(encoderError = EncoderProducedUnexpectedOutput()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `logs a warning with the mismatch error and compatibility advice when the encoder produces unexpected output`() { + val error = EncoderProducedUnexpectedOutput() + val probe = FakeCompatibilityProbe(encoderError = error) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + + val message = argumentCaptor() + verify(fixture.logger, times(1)).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) + } + private companion object { const val NAME_LOOKUP_CAPABILITY = "name lookups" 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..ea4a5d6b257 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt @@ -0,0 +1,633 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.ArgumentSource +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +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.argumentCaptor +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() + } + + /** 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), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(Detail::class.java.name), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + 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 `keeps the name and records only the broken limit when an entry's properties exceed the argument limits`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail(overLimitId)) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.CHARACTER_LIMIT))) + } + + @Test + fun `keeps encoding a type's properties after one entry's properties exceeded the argument limits`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + mapper.mapAndReadArguments(Detail(overLimitId)) + + val mapped = mapper.map(Detail("2")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail", mapOf("id" to "2"))) + } + + @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), + ) + } + + @Test + fun `logs the over-limits warning separately from the unencodable warning for the same type`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + mapper.mapAndReadArguments(Detail(overLimitId)) + fixture.detailSerializer.error = SerializationException("unencodable") + + mapper.mapAndReadArguments(Detail("2")) + + 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), + argThat { contains(UNSUPPORTED_PROPERTIES) }, + eq(Detail::class.java.name), + ) + } + + @Test + fun `doesn't log that an entry's properties exceed the argument limits until its arguments are read`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + + mapper.map(Detail(overLimitId)) + + verifyNoInteractions(fixture.logger) + } + + // 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) + } + + @Test + fun `logs only the compatibility advice warning when a type's property encoding throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = AbstractMethodError() + val mapper = fixture.mapper + + mapper.mapAndReadArguments(Detail("1")) + + // A single warning, rather than the compatibility advice and the unencodable warning. + val message = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + any(), + message.capture(), + eq(Detail::class.java.name), + ) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `attaches the LinkageError to the warning for a type whose property encoding throws it`() { + // Unlike serializer exceptions, a LinkageError names the classes and members that couldn't be + // linked or initialized, not route data. + val error = NoClassDefFoundError("kotlinx/serialization/internal/Missing") + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = error + val mapper = fixture.mapper + + mapper.mapAndReadArguments(Detail("1")) + + val logged = argumentCaptor() + verify(fixture.logger) + .log(eq(SentryLevel.WARNING), logged.capture(), any(), eq(Detail::class.java.name)) + assertThat(logged.firstValue).isSameInstanceAs(error) + } + + // Property encoding that throws other exceptions + + @Test + fun `keeps the name and records only the encoding failure when a type's property encoding throws an exception`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = IllegalArgumentException("invalid id") + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) + } + + @Test + fun `keeps encoding a type's properties after its property encoding throws an exception once`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = IllegalArgumentException("invalid id") + 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 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), + argThat { contains(SERIALIZER_THREW) }, + eq(Detail::class.java.name), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + 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(TreeArgumentWriter(ArgumentBudget())) + } + + assertThat(fixture.detailSerializer.serialized).containsExactly(Detail("1"), Detail("1")) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + argThat { contains(SERIALIZER_THREW) }, + eq(Detail::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `keeps route data from serializer exception messages and causes out of warnings`() { + val detail = Detail("private-route-id") + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = + IllegalArgumentException("Invalid ID ${detail.id}", IllegalStateException(detail.id)) + val mapper = fixture.mapper + + mapper.mapAndReadArguments(detail) + + val message = argumentCaptor() + verify(fixture.logger) + .log(eq(SentryLevel.WARNING), message.capture(), eq(Detail::class.java.name)) + assertThat(message.firstValue).contains(SERIALIZER_THREW) + assertThat(message.firstValue).doesNotContain(detail.id) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `logs the serializer-threw warning separately from the LinkageError warning for the same type`() { + val fixture = KotlinxMapperFixture.create(includeProperties = true) + val mapper = fixture.mapper + fixture.detailSerializer.error = IllegalArgumentException("invalid id") + repeat(2) { mapper.mapAndReadArguments(Detail("thrown-$it")) } + val linkageError = AbstractMethodError() + fixture.detailSerializer.error = linkageError + + repeat(2) { mapper.mapAndReadArguments(Detail("unlinkable-$it")) } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + argThat { contains(SERIALIZER_THREW) }, + eq(Detail::class.java.name), + ) + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + eq(linkageError), + argThat { contains(INCOMPATIBLE_KOTLINX_ADVICE) }, + eq(Detail::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `propagates fatal errors thrown by property encoding when the arguments are read`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create(includeProperties = true) + fixture.detailSerializer.error = error + val mapper = fixture.mapper + val arguments = mapper.map(Detail("1"))?.arguments + + val thrown = assertFailsWith { arguments?.size } + + assertThat(thrown).isSameInstanceAs(error) + } + + // 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), 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" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt index b7fe764f3c1..954c43fa8ba 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt @@ -3,6 +3,7 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx import com.google.common.truth.Truth.assertThat import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.Companion.ProbeClass import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.Companion.ProbeObject +import kotlin.test.assertFailsWith import org.junit.Test /** @@ -23,6 +24,81 @@ class KotlinxCompatibilityProbeTest { assertThat(inconclusive).isEmpty() } + // encoderIncompatibility() + + @Test + fun `encoderIncompatibility() - returns null for a compatible kotlinx serialization version`() { + // A compatible version encodes the probe fixture to its expected output, so the probe's output + // verification matches and it reports no incompatibility. + val error = KotlinxCompatibilityProbe.encoderIncompatibility() + + assertThat(error).isNull() + } + + // encoderFailureOf() + + @Test + fun `encoderFailureOf() - returns null when the check reports no failure`() { + val failure = KotlinxCompatibilityProbe.encoderFailureOf { null } + + assertThat(failure).isNull() + } + + @Test + fun `encoderFailureOf() - returns the failure the check reports without throwing`() { + val error = EncoderProducedUnexpectedOutput() + + val failure = KotlinxCompatibilityProbe.encoderFailureOf { error } + + assertThat(failure).isSameInstanceAs(error) + } + + @Test + fun `encoderFailureOf() - returns a LinkageError the check throws instead of rethrowing it`() { + // Rethrown, the error would escape the mapper's constructor and disable name recording too. + val errors = listOf(NoSuchMethodError(), NoClassDefFoundError(), VerifyError()) + + val failures = errors.map { error -> + KotlinxCompatibilityProbe.encoderFailureOf { throw error } + } + + assertThat(failures).containsExactlyElementsIn(errors).inOrder() + } + + @Test + fun `encoderFailureOf() - returns a non-fatal exception the check throws`() { + val error = NullPointerException() + + val failure = KotlinxCompatibilityProbe.encoderFailureOf { throw error } + + assertThat(failure).isSameInstanceAs(error) + } + + @Test + fun `encoderFailureOf() - rethrows a fatal error the check throws that isn't a LinkageError`() { + val error = OutOfMemoryError() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.encoderFailureOf { throw error } + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `EncoderProducedUnexpectedOutput is a RuntimeException with a message that leaks no route data`() { + val error = EncoderProducedUnexpectedOutput() + + assertThat(error).isInstanceOf(RuntimeException::class.java) + assertThat(error) + .hasMessageThat() + .isEqualTo( + "The kotlinx.serialization properties encoder produced unexpected output for a known " + + "fixture.", + ) + } + // Probe types @Test @@ -37,4 +113,13 @@ class KotlinxCompatibilityProbeTest { .containsExactly(ProbeClass::class.qualifiedName, ProbeObject::class.qualifiedName) .inOrder() } + + @Test + fun `the properties encoder encodes every property of the probe's class`() { + // A probe type that failed to encode for another reason would make the check fail closed. + val encoded = encodeToMap(ProbeClass.serializer(), ProbeClass()) + + assertThat(encoded) + .containsExactly("name", "probe", "values", listOf(1), "counts", mapOf("count" to 1)) + } } 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 index 1d0f853c8d8..7cb9a36fe89 100644 --- 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 @@ -77,15 +77,17 @@ internal class ShapeThrowingDetailSerializer( /** * A [KotlinxCompatibilityProbe] that finds the app's kotlinx.serialization version compatible - * unless [nameLookupError] or [encodingError] is set, so that mapper tests don't depend on the real - * probe. Reports the name check inconclusive with [nameLookupInconclusive], if set, and the - * encoding check inconclusive with [encodingInconclusiveError], if set. Counts the checks of the - * properties encoder in [encodingChecks]. + * unless [nameLookupError] or [encoderError] is set, so that mapper tests don't depend on the real + * probe. Reports the name check inconclusive with [nameLookupInconclusive], if set. Any + * [encoderError], whether a [LinkageError] or not, makes the properties encoder unusable and + * disables property encoding. Counts the checks of the properties encoder in [encodingChecks]. */ internal class FakeCompatibilityProbe( private val nameLookupError: LinkageError? = null, + private val encoderError: Throwable? = null, private val nameLookupInconclusive: Inconclusive? = null, ) : KotlinxCompatibilityProbe { + var encodingChecks = 0 override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? { nameLookupError?.let { @@ -95,6 +97,11 @@ internal class FakeCompatibilityProbe( return null } + override fun encoderIncompatibility(): Throwable? { + encodingChecks++ + return encoderError + } + /** Why the name check is inconclusive: [error], or `null` if a probe serializer wasn't found. */ class Inconclusive(val error: Throwable?) } @@ -109,6 +116,7 @@ internal class FakeCompatibilityProbe( */ internal class KotlinxMapperFixture private constructor( + includeProperties: Boolean, useDefaultLookUp: Boolean, val probe: KotlinxCompatibilityProbe, ) { @@ -129,9 +137,10 @@ private constructor( val mapper = if (useDefaultLookUp) { - KotlinxBackStackEntryMapper(logger = { logger }, probe = probe) + KotlinxBackStackEntryMapper(includeProperties, logger = { logger }, probe = probe) } else { KotlinxBackStackEntryMapper( + includeProperties, lookUpSerializer = { lookedUpTypes += it lookUp(it) @@ -143,9 +152,10 @@ private constructor( companion object { fun create( + includeProperties: Boolean = false, useDefaultLookUp: Boolean = false, probe: KotlinxCompatibilityProbe = FakeCompatibilityProbe(), - ) = KotlinxMapperFixture(useDefaultLookUp, probe) + ) = KotlinxMapperFixture(includeProperties, useDefaultLookUp, probe) } }