From b91b558869e4bfa1b90dfed7f32155c7a1ae18df Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 20 Nov 2026 12:05:13 +0100 Subject: [PATCH 1/5] feat(nav3): Add the SerialNameAndProperties mapper --- CHANGELOG.md | 10 +- sentry-android-navigation3/README.md | 3 +- .../api/sentry-android-navigation3.api | 1 + .../navigation3/BackStackEntryMapper.kt | 85 ++- .../internal/backstack/ArgumentConversion.kt | 46 ++ .../backstack/BuiltInBackStackEntryMappers.kt | 18 +- .../navigation3/internal/backstack/README.md | 14 +- .../backstack/kotlinx/KotlinxArguments.kt | 157 ++++ .../kotlinx/KotlinxBackStackEntryMapper.kt | 216 +++++- .../kotlinx/KotlinxCompatibilityProbe.kt | 23 + .../internal/backstack/kotlinx/README.md | 46 ++ .../navigation3/internal/lifecycle/README.md | 5 + .../internal/lifecycle/StagedNavData.kt | 2 + .../navigation3/SentryNavEffectTest.kt | 152 ++++ .../backstack/ArgumentDuplicateKeysTest.kt | 25 - .../ArgumentNumberSerializationTest.kt | 49 -- .../BuiltInBackStackEntryMappersTest.kt | 67 ++ .../BuiltInMapperArgumentLimitsTest.kt | 141 ++++ .../backstack/BuiltInMapperParityTest.kt | 373 +++++++++ .../ForwardingBackStackEntryMapperTest.kt | 16 +- .../backstack/kotlinx/KotlinxArgumentsTest.kt | 711 ++++++++++++++++++ .../KotlinxBackStackEntryMapperProbeTest.kt | 152 +++- ...tlinxBackStackEntryMapperPropertiesTest.kt | 633 ++++++++++++++++ .../kotlinx/KotlinxCompatibilityProbeTest.kt | 27 + .../backstack/kotlinx/KotlinxMapperFixture.kt | 16 +- .../KotlinxUnencodableArgumentsTest.kt | 36 + 26 files changed, 2917 insertions(+), 107 deletions(-) create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentDuplicateKeysTest.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentNumberSerializationTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInMapperArgumentLimitsTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInMapperParityTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperPropertiesTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d44ea7dfd..4346733423 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,22 +10,22 @@ ### Features - Nav3: Add `BackStackEntryMapper.SerialName`, a convenience mapper that names back stack entries after their kotlinx.serialization serial names ([#PR_NUMBER](https://github.com/getsentry/sentry-java/pull/PR_NUMBER)) +- Nav3: Add `BackStackEntryMapper.SerialNameAndProperties`, which is like `SerialName` except that it also records the properties of each back stack entry as arguments ([#PR_NUMBER](https://github.com/getsentry/sentry-java/pull/PR_NUMBER)) ### Behavioral Changes - Nav3: If a back stack entry's arguments contain a map with two keys that are recorded as the same string (e.g., `1` and `"1"`), Sentry now drops that entry's arguments and records `dropped_by_sentry: duplicate_key`, instead of keeping only one of the values ([#PR_NUMBER](https://github.com/getsentry/sentry-java/pull/PR_NUMBER)) -### Dependencies - -- Nav3: `sentry-android-navigation3` no longer declares a dependency on `androidx.lifecycle:lifecycle-runtime-compose`. Nav3 apps already depend on it via `navigation3-ui`, so no app changes are necessary ([#PR_NUMBER](https://github.com/getsentry/sentry-java/pull/PR_NUMBER)) - ### Fixes - Nav3: `NaN` and infinite numbers in back stack entry arguments are now sent as the strings `"NaN"`, `"Infinity"`, and `"-Infinity"`, instead of causing the event they're attached to be dropped ([#PR_NUMBER](https://github.com/getsentry/sentry-java/pull/PR_NUMBER)) - - Kotlin now sees `Attachment.getBytes()`, `Device.getArchs()`, `Spring.getActiveProfiles()` and `JsonSerializationUtils.bytesFrom(...)` as nullable, because `@Nullable` now annotates the returned array instead of its elements ([#6558](https://github.com/getsentry/sentry-java/pull/6558)) - Shake-to-report no longer leaks the first Activity that resumes after `Sentry.init` ([#6686](https://github.com/getsentry/sentry-java/pull/6686)) +### Dependencies + +- Nav3: `sentry-android-navigation3` no longer declares a dependency on `androidx.lifecycle:lifecycle-runtime-compose`. Nav3 apps already depend on it via `navigation3-ui`, so no app changes are necessary ([#PR_NUMBER](https://github.com/getsentry/sentry-java/pull/PR_NUMBER)) + ## 8.65.0 ### Features diff --git a/sentry-android-navigation3/README.md b/sentry-android-navigation3/README.md index 2135233aef..6d819112df 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 04c3349cd4..04a7ba34aa 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 0ce6a4f534..b325c8ad1c 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/ArgumentConversion.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt index 96e2e7dc76..28467db5df 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt @@ -14,6 +14,52 @@ import java.util.IdentityHashMap * implementations are expected to materialize the provided info into a tree of Sentry arguments, * where the tree has a bounded size and height. * + * **The argument conversion subsystem** + * + * With Nav3, host apps manage their own nav back stack, which they implement as a list of + * arbitrarily typed entries. In order to be displayed in Sentry, each of those entries has to be + * mapped to a Sentry name (e.g., ProductDetailScreen) and zero or more arguments (e.g., productId). + * There are two ways for host apps to provide us with those mappings: + * + * 1. via a custom `BackStackEntryMapper`; or + * + * 2. via one of our own built-in mappers (viz., `BackStackEntryMapper.SerialName` or + * `BackStackEntryMapper.SerialNameAndProperties`). + * + * `ArgumentSink` and `ArgumentSource` create the seam that lets us support variable processing on + * the source side (the host app's logic vs built-in logic) but uniform processing on the sink side + * (argument pruning, protecting against constraint violation, and tree materialization). + * + * Here are the moving parts: + * ```text + * ArgumentSource + * Custom mapper Built-in mappers + * ┌────────────────────┐ ┌──────────────────┐ + * │ HostArgumentSource │ │ KotlinxArguments │ + * │ (plain host map) │ │ (drives encoder) │ + * └────────┬───────────┘ └────────┬─────────┘ + * │ │ via + * │ KotlinxPropertiesEncoder + SensitiveKeyFilter + * │ │ + * └──────────────┬──────────────┘ + * ▼ + * ┌───────────────────────────────┐ + * │ ArgumentSink │ + * └───────────────────────────────┘ + * ▲ sole impl + * ┌───────────────┴───────────────┐ + * │ TreeArgumentWriter │ + * │ │ ┌────────────────┐ + * │ Enforce + materialize: │ spends ──▶│ ArgumentBudget │ + * │ • builds the argument tree │ └────────────────┘ + * │ • prevents constraint │ ┌────────────────┐ + * │ violation (e.g., cycles) │ throws ──▶│ DropArguments │ + * └───────────────────────────────┘ └────────────────┘ + * + * Note: BackStackConverter.ArgumentSanitizer owns the ArgumentBudget and + * selects the ArgumentSource based on what the host app provides. + * ``` + * * Receives one back stack entry's arguments as a [source][ArgumentSource] produces them, enforcing * the argument limits as it goes. * 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 703f2d2e9b..1e164628f1 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 @@ -29,7 +29,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 d528413e16..29f5c2dc25 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 @@ -1,3 +1,15 @@ # `io.sentry.compose.navigation3.internal.backstack` -Converts host back stacks into bounded Sentry names and arguments. +Package contains code for generating Sentry data from a host app's back stack. + +## Conventions + +### Properties vs. arguments + +Code in this package uses the term "properties" for the fields and values it reads from a back stack entry and "arguments" for the values +a `BackStackEntryMapper` supplies for Sentry to record, i.e., `SentryBackStackEntry.arguments`. Arguments include the mapper's output before +sanitization, which may modify or drop them before Sentry records them. Hence +`SerialNameAndProperties` and `KotlinxPropertiesEncoder`, but `SentryBackStackEntry(arguments = ...)`. + +When a host app uses a built-in `BackStackEntryMapper`, we're responsible for mapping entry properties to corresponding arguments. When the +host app implements its own `BackStackEntryMapper`, it performs the mapping on its end and hands the resulting arguments to us. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt new file mode 100644 index 0000000000..7def27d1b5 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt @@ -0,0 +1,157 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY +import io.sentry.compose.navigation3.internal.backstack.ArgumentSink +import io.sentry.compose.navigation3.internal.backstack.ArgumentSource +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSource +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import io.sentry.util.ExceptionUtils +import kotlinx.serialization.KSerializer + +/** + * The [ArgumentSource] for our built-in `BackStackEntryMapper`s. + * + * It keeps a reference to the [backStackEntry] whose properties it reads, as well as the + * [serializer] needed to encode them, for as long as the map itself is reachable. (The SDK doesn't + * retain these maps past a back stack update, but a host app that keeps a mapper's result also + * keeps its entry.) + * + * Encoding is performed on demand and cached in order to: + * + * - guarantee a single, consistent snapshot for all consumers; and + * - avoid doing work for arguments that will be dropped or never read. + * + * If the arguments are dropped, reading them as a map returns only the drop reason. + * + * In general, all failures are reported to [onFailure]. The sole exception is an argument + * constraint violated while writing to the `ArgumentSanitizer`'s sink. The sanitizer reports that + * instead, as those limits can depend on what fraction of the [ArgumentBudget] the update's other + * entries spent. + */ +internal class KotlinxArguments( + private val backStackEntry: Any, + private val serializer: KSerializer, + private val onFailure: (Throwable) -> Unit, +) : AbstractMap(), ArgumentSource { + + private val copy: Lazy = + // PUBLICATION so that no lock is held while encoding runs the host app's serializers, which + // could otherwise deadlock on a lock held by the app. Readers that race on the first read may + // each encode, but all of them see the copy published first. + lazy(LazyThreadSafetyMode.PUBLICATION) { encodeCopy() } + + override val entries: Set> + get() = copy.value.arguments.entries + + /** + * Writes the entry's arguments to [sink], encoding its properties if needed. Uses the previously + * cached copy instead if it was encoded successfully. + * + * Throws [DropArguments] if the arguments can't be written, either with the reason for the + * constraint they violated, or with [ArgumentDropReason.ENCODING_FAILED] if encoding failed. + */ + override fun writeTo(sink: ArgumentSink) { + val cached = if (copy.isInitialized()) copy.value else null + if (cached != null && !cached.isDropped) { + cached.writeTo(sink) + } else { + // A failed copy used a separate budget. Encode again so values written before the failure + // consume the update's shared budget; rethrowing the cached failure would leave extra room + // for older entries' arguments. + encode(sink) + } + } + + @Suppress("ThrowsCount") + private fun encode(sink: ArgumentSink) { + try { + KotlinxPropertiesEncoder.encode(serializer, backStackEntry, sink) + } catch (e: DropArguments) { + // Prefer the sink's first failure because it determines whether older entries keep their + // arguments. + throw sink.failure ?: e + } catch (e: LinkageError) { + // Preserve the entry's name and drop its properties. The creation-time probe checks encoder + // compatibility but can't exercise every path. This LinkageError may be specific to the + // entry's serializers, so we keep the failure local to this type. + sink.failure?.let { throw it } + onFailure(e) + throw DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null) + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // App serializers and map-key toString() calls may throw anything. Catch broadly to log once + // per type. + ExceptionUtils.rethrowIfFatal(t) + + // A serializer may replace a constraint violation with its own exception. Prefer the sink's + // recorded failure because it determines whether older entries keep their arguments. + sink.failure?.let { throw it } + onFailure(t) + throw DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null) + } + } + + private fun encodeCopy(): EncodedCopy { + val sink = TreeArgumentWriter(ArgumentBudget()) + + return try { + encode(sink) + EncodedCopy(sink.argumentsOrThrow(), isDropped = false) + } catch (e: DropArguments) { + // encode already reported an encoding failure. + if (e.reason != ArgumentDropReason.ENCODING_FAILED) { + onFailure(e) + } + EncodedCopy(mapOf(ARGUMENT_DROP_REASON_KEY to e.reason.serializedValue), isDropped = true) + } + } + + /** Cached arguments encoded from a single back stack entry's properties. */ + private class EncodedCopy( + /** + * The encoded arguments, or, if they were dropped, only the drop reason under + * [ARGUMENT_DROP_REASON_KEY]. + * + * A host app mapper that copies or filters a dropped entry's arguments passes the reason on as + * an ordinary argument. Sentry then records it as it would for this mapper's own output, rather + * than recording no arguments and no reason. + */ + val arguments: Map, + /** + * Whether the back stack entry's arguments were dropped, because of an encoding failure or a + * violated argument constraint. + */ + val isDropped: Boolean, + ) : ArgumentSource { + + /** Writes the encoded arguments to [sink]. Only for a copy that wasn't [dropped][isDropped]. */ + override fun writeTo(sink: ArgumentSink) { + check(!isDropped) { "A dropped copy is encoded again instead of written." } + // The copy holds only plain maps, lists, and values the sink supports. + HostArgumentSource(arguments, onUnsupportedValue = {}).writeTo(sink) + } + } +} + +/** + * The arguments of a back stack entry whose properties can't be encoded because the app's + * kotlinx.serialization version doesn't support the properties encoder. + * + * Handles encoding failures like [KotlinxArguments]: map reads return `{"dropped_by_sentry": + * "encoding_failed"}`, and writes drop the entry's arguments with + * [ArgumentDropReason.ENCODING_FAILED]. + */ +internal object KotlinxUnencodableArguments : AbstractMap(), ArgumentSource { + + private val dropReason = + mapOf(ARGUMENT_DROP_REASON_KEY to ArgumentDropReason.ENCODING_FAILED.serializedValue) + + override val entries: Set> + get() = dropReason.entries + + override fun writeTo(sink: ArgumentSink) { + throw DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null) + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt index fef70e5bd0..9cba2abab8 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,22 @@ 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.encodingLinkageError { error -> + diagnostics.inconclusiveProbe(ENCODING_CAPABILITY, error) + } ?: 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 +90,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 +120,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 +146,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,28 +220,84 @@ 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 KotlinxArguments(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. */ private class SerializerLookup(val serializer: KSerializer<*>?, val error: Throwable?) private companion object { + private const val ENCODING_CAPABILITY = "property encoding" 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 +330,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: LinkageError) { + 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 +375,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 afc4bda12b..493592611b 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 /** @@ -38,6 +41,16 @@ internal interface KotlinxCompatibilityProbe { */ fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? + /** + * Encodes [ProbeClass] using the same path as [KotlinxBackStackEntryMapper]. + * + * Returns a [LinkageError] if the encoder can't link against the host app's kotlinx.serialization + * version, or `null` if encoding succeeds or the check is inconclusive. + * + * Calls [onInconclusive] for each inconclusive result, passing the cause. + */ + fun encodingLinkageError(onInconclusive: (Throwable) -> Unit): LinkageError? + /** Probes the app's kotlinx.serialization version using [ProbeClass] and [ProbeObject]. */ companion object : KotlinxCompatibilityProbe { @@ -67,6 +80,16 @@ internal interface KotlinxCompatibilityProbe { return error } + override fun encodingLinkageError(onInconclusive: (Throwable) -> Unit): LinkageError? = + probe(onInconclusive) { + @Suppress("UNCHECKED_CAST") + KotlinxPropertiesEncoder.encode( + ProbeClass.serializer() as KSerializer, + ProbeClass(), + TreeArgumentWriter(ArgumentBudget()), + ) + } + /** * Runs [check], returning any [LinkageError] and rethrowing fatal errors. Returns `null` if the * check succeeds or is inconclusive. 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 0000000000..19bad76b37 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -0,0 +1,46 @@ +# `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. + +`nav3-backstack-entry-mapper-r8-check` verifies our built-in `SerialName` and `SerialNameAndProperties` mappers behave +correctly despite R8 minification. It does so against the kotlinx.serialization version we use for compilation, along with newer versions, +and in both R8 full and compat modes. See its README for more details. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md index c7fe450590..d4161499e1 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md @@ -7,6 +7,11 @@ This package is meant to encapsulate knowledge about the possibility of multiple raises. Addressing those concerns is complicated. Confining them here makes them easier to reason about and easier to swap for alternative logic should we someday need to. +## Dependencies + +This package may ***not*** depend on any other `io.sentry.compose.navigation3` package, Compose, or +`androidx.navigation3`. It may use Android framework and AndroidX Lifecycle APIs directly. + ## Limitations Support for multiple `SentryNavEffect`s is restricted to the scenarios documented in the diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt index 3480162101..ae1750f00d 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt @@ -93,7 +93,9 @@ internal class StagedNavData { * Clears the screen and nav context this instance published, unless something else has replaced * them in [realScope] since. */ + @Suppress("AvoidReferentialEquality") fun clearPublishedStateFrom(realScope: IScope) { + // Identity tracks the screen we published; equal but distinct host replacements must survive. if (publishedScreen != null && realScope.screen === publishedScreen) { realScope.screen = null } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt index dfe941ee2f..f1fb8ffb80 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/ArgumentDuplicateKeysTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentDuplicateKeysTest.kt deleted file mode 100644 index 1cab62669c..0000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentDuplicateKeysTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack - -import com.google.common.truth.Truth.assertThat -import io.sentry.NoOpLogger -import org.junit.Test - -class ArgumentDuplicateKeysTest { - @Test - fun `stringified key collisions drop only that entry`() { - val sanitizer = - BackStackConverter.ArgumentSanitizer( - NoOpLogger.getInstance(), - BackStackConverter.WarningState(), - ) - val result = - sanitizer.sanitizeEntry( - mapOf("nested" to linkedMapOf(1 to "first", "1" to "second")), - ) - assertThat(result.values).isEmpty() - assertThat(result.dropReason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) - val next = sanitizer.sanitizeEntry(mapOf("id" to 123)) - assertThat(next.dropReason).isNull() - assertThat(next.values).containsExactly("id", 123) - } -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentNumberSerializationTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentNumberSerializationTest.kt deleted file mode 100644 index 36da2db3c8..0000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentNumberSerializationTest.kt +++ /dev/null @@ -1,49 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack - -import com.google.common.truth.Truth.assertThat -import io.sentry.JsonSerializer -import io.sentry.NoOpLogger -import io.sentry.SentryOptions -import io.sentry.compose.navigation3.BackStackEntryMapper -import io.sentry.compose.navigation3.SentryBackStackEntry -import java.io.StringWriter -import org.junit.Test - -class ArgumentNumberSerializationTest { - @Test - fun `non-finite numbers produce valid event JSON`() { - val mapper = - BackStackEntryMapper { - SentryBackStackEntry( - "Home", - mapOf( - "price" to Double.NaN, - "limits" to floatArrayOf(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), - ), - ) - } - val converter = - BackStackConverter(ForwardingBackStackEntryMapper { mapper }, NoOpLogger.getInstance()) - val entry = - converter.convert(listOf(Any()), BackStackConverter.RetentionPolicy.KEEP_FIRST).single() - val json = StringWriter() - JsonSerializer(SentryOptions()).serialize(entry.serialize(), json) - assertThat(json.toString()) - .isEqualTo( - """{"entry":"/Home","entry_arguments":{"price":"NaN","limits":["Infinity","-Infinity"]}}""", - ) - } - - @Test - fun `non-finite number text spends the character budget`() { - val sanitizer = - BackStackConverter.ArgumentSanitizer( - NoOpLogger.getInstance(), - BackStackConverter.WarningState(), - ) - val values = - mapOf("x" to "a".repeat(ArgumentConstraints.MAX_ARGUMENT_CHARACTERS - 3), "n" to Double.NaN) - assertThat(sanitizer.sanitizeEntry(values).dropReason) - .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } -} 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 7bb5c0594d..87290f35c0 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 0000000000..e28d6c756a --- /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 0000000000..491f78d96e --- /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/ForwardingBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt index 6f56285b49..74208ca05d 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt @@ -30,14 +30,16 @@ class ForwardingBackStackEntryMapperTest { } @Test - fun `mapper returns entry without allocating arguments map when arguments are omitted`() { - val sut = ForwardingBackStackEntryMapper { - BackStackEntryMapper { SentryBackStackEntry(it.id) } - } + fun `map() - forwards to the mapper current when map is called`() { + var mapper = BackStackEntryMapper { SentryBackStackEntry("first") } + val sut = ForwardingBackStackEntryMapper { mapper } + val first = sut.map(HomeScreen()) + mapper = BackStackEntryMapper { SentryBackStackEntry("second") } + + val second = sut.map(HomeScreen()) - val mapped = sut.map(HomeScreen()) - assertThat(mapped).isEqualTo(SentryBackStackEntry("home")) - assertThat(mapped?.arguments).isNull() + assertThat(first).isEqualTo(SentryBackStackEntry("first")) + assertThat(second).isEqualTo(SentryBackStackEntry("second")) } @Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt new file mode 100644 index 0000000000..08958bdf59 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt @@ -0,0 +1,711 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import io.sentry.compose.navigation3.internal.backstack.budgetWithCharactersRemaining +import io.sentry.compose.navigation3.internal.backstack.budgetWithValuesRemaining +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.thread +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +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 org.junit.Test + +class KotlinxArgumentsTest { + + @Serializable data class Values(val values: List) + + @Serializable data class MutableDetail(var id: String) + + /** + * Delegates to [delegate], but wraps a [DropArguments] it throws in an exception of its own, as a + * serializer that catches and rethrows everything might. + */ + private class WrappingSerializer( + private val delegate: KSerializer, + private val wrap: (DropArguments) -> Throwable, + ) : KSerializer by delegate { + override fun serialize(encoder: Encoder, value: T) { + try { + delegate.serialize(encoder, value) + } catch (e: DropArguments) { + throw wrap(e) + } + } + } + + /** + * Writes [text], recording a [DropArguments] that throws in [caught], then encodes the link with + * [LinkSerializer], so a chain long enough breaks the encoder's nesting limit after the sink's. + */ + private class NestsAfterCaughtLimitSerializer(private val text: String) : KSerializer { + var caught: DropArguments? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.NestsAfterCaughtLimit", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + try { + encoder.encodeString(text) + } catch (e: DropArguments) { + caught = e + } + encoder.encodeSerializableValue(LinkSerializer, value) + } + + override fun deserialize(decoder: Decoder): Link = throw UnsupportedOperationException() + } + + /** + * Encodes a [Detail] whose id is the number of this serializer's call, so that each encoding of + * an entry differs. Runs [beforeEncoding] with that number first. + */ + private class NumberingDetailSerializer(private val beforeEncoding: (call: Int) -> Unit) : + KSerializer { + private val calls = AtomicInteger() + + override val descriptor: SerialDescriptor = Detail.serializer().descriptor + + override fun serialize(encoder: Encoder, value: Detail) { + val call = calls.incrementAndGet() + beforeEncoding(call) + Detail.serializer().serialize(encoder, Detail("encoding-$call")) + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + /** Delegates to [delegate], then throws [error], as a serializer that fails late might. */ + private class ThrowsAfterEncodingSerializer(private val delegate: KSerializer) : + KSerializer by delegate { + val error = IllegalStateException("thrown after encoding") + + override fun serialize(encoder: Encoder, value: T) { + delegate.serialize(encoder, value) + throw error + } + } + + private val failures = mutableListOf() + + private val detailSerializer = RecordingSerializer(Detail.serializer()) + private val mutableDetailSerializer = RecordingSerializer(MutableDetail.serializer()) + + /** A value over the argument character limit. */ + private val overLimitId = "x".repeat(MAX_ARGUMENT_CHARACTERS + 1) + + private val encodingFailed = droppedBy(ArgumentDropReason.ENCODING_FAILED) + + /** A link chain whose serializers nest one call more than the encoder allows. */ + private val tooDeeplyLinked = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) + + // Reading as a map + + @Test + fun `reads as the entry's encoded properties`() { + val arguments = argumentsOf(detailSerializer, Detail("1")) + + assertThat(arguments.entries.associate { it.key to it.value }).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `doesn't encode the entry until its arguments are read`() { + argumentsOf(detailSerializer, Detail("1")) + + assertThat(detailSerializer.serialized).isEmpty() + } + + @Test + fun `encodes the entry when its arguments are first read through hashCode()`() { + val arguments = argumentsOf(detailSerializer, Detail("1")) + + val hashCode = arguments.hashCode() + + assertThat(hashCode).isEqualTo(mapOf("id" to "1").hashCode()) + assertThat(detailSerializer.serialized).containsExactly(Detail("1")) + } + + @Test + fun `encodes the entry once across repeated reads`() { + val arguments = argumentsOf(detailSerializer, Detail("1")) + + arguments.entries + arguments.size + arguments["id"] + arguments.containsKey("id") + arguments.equals(mapOf("id" to "1")) + + assertThat(detailSerializer.serialized).containsExactly(Detail("1")) + } + + @Test + fun `equals a plain map with the same entries`() { + val arguments = argumentsOf(detailSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(mapOf("id" to "1")) + assertThat(mapOf("id" to "1")).isEqualTo(arguments) + assertThat(arguments.hashCode()).isEqualTo(mapOf("id" to "1").hashCode()) + } + + @Test + fun `doesn't equal a plain map with other entries`() { + val arguments = argumentsOf(detailSerializer, Detail("1")) + + assertThat(arguments).isNotEqualTo(mapOf("id" to "2")) + assertThat(mapOf("id" to "2")).isNotEqualTo(arguments) + } + + @Test + fun `reads each instance's arguments with a budget of its own`() { + // Each entry has 151 values, so two entries wouldn't fit in one budget. + val first = argumentsOf(Values.serializer(), Values(List(150) { it })) + val second = argumentsOf(Values.serializer(), Values(List(150) { it })) + + assertThat(first).isEqualTo(mapOf("values" to List(150) { it })) + assertThat(second).isEqualTo(mapOf("values" to List(150) { it })) + } + + // Reading from several threads + + @Test + fun `doesn't block a read on another thread's encoding that waits for a lock the reader holds`() { + // Models a deadlock: the reader holds a lock of the app's, and the serializer encoding on + // another thread needs it. + val appLock = ReentrantLock() + val encodingStarted = CountDownLatch(1) + var otherThreadGotLock = false + val serializer = NumberingDetailSerializer { call -> + if (call == 1) { + encodingStarted.countDown() + otherThreadGotLock = appLock.tryLock(TIMEOUT_SECONDS, TimeUnit.SECONDS) + if (otherThreadGotLock) appLock.unlock() + } + } + val arguments = argumentsOf(serializer, Detail("1")) + appLock.lock() + val otherRead = readOnAnotherThread(arguments) + assertThat(encodingStarted.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue() + + val read = + try { + arguments.toMap() + } finally { + appLock.unlock() + } + + assertThat(otherRead.await()).isEqualTo(read) + assertThat(otherThreadGotLock).isTrue() + } + + @Test + fun `reads the copy published first on every thread when reads race on the first read`() { + val encodingStarted = CountDownLatch(1) + val firstReadDone = CountDownLatch(1) + var otherThreadSawFirstRead = false + val serializer = NumberingDetailSerializer { call -> + // The other thread's encoding, the first call, waits until this thread's read returns. + if (call == 1) { + encodingStarted.countDown() + otherThreadSawFirstRead = firstReadDone.await(TIMEOUT_SECONDS, TimeUnit.SECONDS) + } + } + val arguments = argumentsOf(serializer, Detail("1")) + val otherRead = readOnAnotherThread(arguments) + assertThat(encodingStarted.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue() + + val read = arguments.toMap() + firstReadDone.countDown() + + assertThat(read).isEqualTo(mapOf("id" to "encoding-2")) + assertThat(otherRead.await()).isEqualTo(read) + assertThat(arguments.toMap()).isEqualTo(read) + assertThat(otherThreadSawFirstRead).isTrue() + } + + // Reading failures + + @Test + fun `reads as only the broken limit when the entry breaks an argument limit`() { + val arguments = argumentsOf(detailSerializer, Detail(overLimitId)) + + assertThat(arguments).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `reports the broken limit to onFailure when read`() { + val arguments = argumentsOf(detailSerializer, Detail(overLimitId)) + + arguments.size + + assertThat(failures).hasSize(1) + assertThat((failures.single() as DropArguments).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `reads as only the encoding failure and reports a serializer's exception once across reads`() { + val error = IllegalStateException("boom") + detailSerializer.error = error + val arguments = argumentsOf(detailSerializer, Detail("1")) + + val reads = List(3) { arguments.toMap() } + + assertThat(reads).containsExactly(encodingFailed, encodingFailed, encodingFailed) + assertThat(failures).containsExactly(error) + } + + @Test + fun `reads as only the encoding failure and reports a serializer's LinkageError once across reads`() { + val error = NoClassDefFoundError("missing") + detailSerializer.error = error + val arguments = argumentsOf(detailSerializer, Detail("1")) + + val reads = List(3) { arguments.toMap() } + + assertThat(reads).containsExactly(encodingFailed, encodingFailed, encodingFailed) + assertThat(failures).containsExactly(error) + } + + @Test + fun `reads as only the broken limit and reports it when a serializer replaced it with its own exception`() { + val serializer = WrappingSerializer(Detail.serializer()) { SerializationException("replaced") } + val arguments = argumentsOf(serializer, Detail(overLimitId)) + + val read = arguments.toMap() + + assertThat(read).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + assertThat(failures).hasSize(1) + assertThat((failures.single() as DropArguments).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `reads as only the nesting limit and reports it when a serializer replaced it with its own exception`() { + val serializer = WrappingSerializer(LinkSerializer) { SerializationException("replaced") } + val arguments = argumentsOf(serializer, tooDeeplyLinked) + + val read = arguments.toMap() + + assertThat(read).isEqualTo(droppedBy(ArgumentDropReason.INVALID_STRUCTURE)) + assertThat(failures).hasSize(1) + assertThat((failures.single() as DropArguments).reason) + .isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `reads as only the sink's limit and reports it when the encoder's nesting limit follows it`() { + val serializer = NestsAfterCaughtLimitSerializer(overLimitId) + val arguments = + argumentsOf(serializer, linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING)) + + val read = arguments.toMap() + + assertThat(read).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + assertThat(failures).hasSize(1) + assertThat((failures.single() as DropArguments).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `propagates fatal errors when read, without reporting them`() { + val error = OutOfMemoryError() + detailSerializer.error = error + val arguments = argumentsOf(detailSerializer, Detail("1")) + + val thrown = assertFailsWith { arguments.size } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(failures).isEmpty() + } + + // writeTo() + + @Test + fun `writeTo() - writes the entry's properties to the sink`() { + val sink = TreeArgumentWriter(ArgumentBudget()) + + argumentsOf(detailSerializer, Detail("1")).writeTo(sink) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `writeTo() - encodes the entry each time it's written`() { + val arguments = argumentsOf(detailSerializer, Detail("1")) + + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + + assertThat(detailSerializer.serialized).containsExactly(Detail("1"), Detail("1")) + } + + @Test + fun `writeTo() - spends the sink's budget`() { + // Each entry has 151 values, so two entries don't fit in one budget. + val budget = ArgumentBudget() + argumentsOf(Values.serializer(), Values(List(150) { it })).writeTo(TreeArgumentWriter(budget)) + val second = argumentsOf(Values.serializer(), Values(List(150) { it })) + + val thrown = assertFailsWith { second.writeTo(TreeArgumentWriter(budget)) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + } + + @Test + fun `writeTo() - propagates a broken limit unchanged, without reporting it`() { + val sink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + + val thrown = + assertFailsWith { + argumentsOf(detailSerializer, Detail("1")).writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(assertFailsWith { sink.argumentsOrThrow() }) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - reports a serializer's exception and drops the arguments as an unlogged encoding failure`() { + val error = IllegalStateException("boom") + detailSerializer.error = error + + val thrown = + assertFailsWith { + argumentsOf(detailSerializer, Detail("1")).writeTo(TreeArgumentWriter(ArgumentBudget())) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(thrown.warning).isNull() + assertThat(failures).containsExactly(error) + } + + @Test + fun `writeTo() - reports a serializer's LinkageError and drops the arguments as an unlogged encoding failure`() { + val error = AbstractMethodError() + detailSerializer.error = error + + val thrown = + assertFailsWith { + argumentsOf(detailSerializer, Detail("1")).writeTo(TreeArgumentWriter(ArgumentBudget())) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(thrown.warning).isNull() + assertThat(failures).containsExactly(error) + } + + @Test + fun `writeTo() - propagates fatal errors without reporting them`() { + val error = OutOfMemoryError() + detailSerializer.error = error + + val thrown = + assertFailsWith { + argumentsOf(detailSerializer, Detail("1")).writeTo(TreeArgumentWriter(ArgumentBudget())) + } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - rethrows a broken limit that a serializer wrapped, without reporting it`() { + val serializer = + WrappingSerializer(Detail.serializer()) { SerializationException("wrapped", it) } + val sink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + + val thrown = + assertFailsWith { + argumentsOf(serializer, Detail("1")).writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - rethrows the sink's limit that a serializer replaced with its own exception, unreported`() { + val serializer = WrappingSerializer(Detail.serializer()) { SerializationException("replaced") } + val sink = TreeArgumentWriter(ArgumentBudget()) + + val thrown = + assertFailsWith { + argumentsOf(serializer, Detail(overLimitId)).writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - rethrows the sink's limit that a serializer replaced with a LinkageError, unreported`() { + val serializer = WrappingSerializer(Detail.serializer()) { NoClassDefFoundError("replaced") } + val sink = TreeArgumentWriter(ArgumentBudget()) + + val thrown = + assertFailsWith { + argumentsOf(serializer, Detail(overLimitId)).writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - rethrows the nesting limit that a serializer replaced with its own exception, unreported`() { + val serializer = WrappingSerializer(LinkSerializer) { SerializationException("replaced") } + val sink = TreeArgumentWriter(ArgumentBudget()) + + val thrown = + assertFailsWith { + argumentsOf(serializer, tooDeeplyLinked).writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - rethrows the nesting limit that a serializer replaced with a LinkageError, unreported`() { + val serializer = WrappingSerializer(LinkSerializer) { NoClassDefFoundError("replaced") } + val sink = TreeArgumentWriter(ArgumentBudget()) + + val thrown = + assertFailsWith { + argumentsOf(serializer, tooDeeplyLinked).writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - rethrows the sink's limit when the encoder's nesting limit follows it, unreported`() { + val serializer = NestsAfterCaughtLimitSerializer(overLimitId) + val sink = TreeArgumentWriter(ArgumentBudget()) + + val thrown = + assertFailsWith { + argumentsOf(serializer, linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING)) + .writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(failures).isEmpty() + } + + // writeTo() after the arguments are read + + @Test + fun `writeTo() - writes the copy read as a map rather than the entry's current properties`() { + val entry = MutableDetail("1") + val arguments = argumentsOf(mutableDetailSerializer, entry) + arguments.size + entry.id = "2" + val sink = TreeArgumentWriter(ArgumentBudget()) + + arguments.writeTo(sink) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `writeTo() - doesn't encode the entry again after its arguments are read`() { + val arguments = argumentsOf(mutableDetailSerializer, MutableDetail("1")) + arguments.size + + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + + assertThat(mutableDetailSerializer.serialized).hasSize(1) + } + + @Test + fun `writeTo() - encodes the entry's current properties when its arguments weren't read`() { + val entry = MutableDetail("1") + val arguments = argumentsOf(mutableDetailSerializer, entry) + entry.id = "2" + val sink = TreeArgumentWriter(ArgumentBudget()) + + arguments.writeTo(sink) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to "2")) + } + + @Test + fun `reads a copy encoded separately from what writeTo() wrote`() { + val entry = MutableDetail("1") + val arguments = argumentsOf(mutableDetailSerializer, entry) + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + entry.id = "2" + + val read = arguments.toMap() + + assertThat(read).isEqualTo(mapOf("id" to "2")) + assertThat(mutableDetailSerializer.serialized).hasSize(2) + } + + @Test + fun `writeTo() - spends the sink's value budget when writing the copy read`() { + // The entry has 151 values, which fit in its own budget but not in the 100 the sink has left. + val arguments = argumentsOf(Values.serializer(), Values(List(150) { it })) + arguments.size + val sink = TreeArgumentWriter(budgetWithValuesRemaining(100)) + + val thrown = assertFailsWith { arguments.writeTo(sink) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(thrown.warning).isEqualTo(DropArguments.MAX_COUNT_WARNING) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - spends the sink's character budget when writing the copy read`() { + val arguments = argumentsOf(detailSerializer, Detail("123")) + arguments.size + val sink = TreeArgumentWriter(budgetWithCharactersRemaining(4)) + + val thrown = assertFailsWith { arguments.writeTo(sink) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(thrown.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - encodes again and drops the arguments for the sink's limit when the copy read broke a limit`() { + val arguments = argumentsOf(detailSerializer, Detail(overLimitId)) + arguments.size + val sink = TreeArgumentWriter(ArgumentBudget()) + + val thrown = assertFailsWith { arguments.writeTo(sink) } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(thrown.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + assertThat(detailSerializer.serialized).hasSize(2) + // Only the read reports the limit; the sink's owner reports the one writeTo() broke. + assertThat(failures).hasSize(1) + } + + @Test + fun `writeTo() - encodes the entry again and reports a serializer's exception again when the copy read failed`() { + val error = IllegalStateException("boom") + detailSerializer.error = error + val arguments = argumentsOf(detailSerializer, Detail("1")) + arguments.size + + val thrown = + assertFailsWith { + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(thrown.warning).isNull() + assertThat(detailSerializer.serialized).hasSize(2) + // The mapper's onFailure logs once per type, so reporting each encoding adds no warnings. + assertThat(failures).containsExactly(error, error) + } + + @Test + fun `writeTo() - drops the arguments for the sink's limit that encoding again breaks when the copy read failed`() { + // The entry's 151 values fit in the copy's own budget, so the copy failed only once its + // serializer threw. Encoding again overflows the 100 values the sink has left first. + val serializer = ThrowsAfterEncodingSerializer(Values.serializer()) + val arguments = argumentsOf(serializer, Values(List(150) { it })) + arguments.size + val sink = TreeArgumentWriter(budgetWithValuesRemaining(100)) + + val thrown = assertFailsWith { arguments.writeTo(sink) } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(failures).containsExactly(serializer.error) + } + + @Test + fun `writeTo() - writes the entry's properties when encoding again succeeds after the copy read failed`() { + detailSerializer.error = IllegalStateException("boom") + detailSerializer.failsFor = { detailSerializer.serialized.size == 1 } + val arguments = argumentsOf(detailSerializer, Detail("1")) + arguments.size + val sink = TreeArgumentWriter(ArgumentBudget()) + + arguments.writeTo(sink) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `reads as only the drop reason of the copy read after writeTo() encodes the entry again`() { + detailSerializer.error = IllegalStateException("boom") + detailSerializer.failsFor = { detailSerializer.serialized.size == 1 } + val arguments = argumentsOf(detailSerializer, Detail("1")) + arguments.size + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + + val read = arguments.toMap() + + assertThat(read).isEqualTo(encodingFailed) + } + + /** + * Reads [arguments] as a map on a new thread. The returned read's [OtherThreadRead.await] fails + * rather than hangs if the thread doesn't finish in time. + */ + private fun readOnAnotherThread(arguments: Map): OtherThreadRead { + val read = OtherThreadRead() + read.thread = + thread(name = "other-reader") { + try { + read.result = arguments.toMap() + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + read.error = t + } + } + return read + } + + /** A read of the arguments on another thread, whose result [await] returns. */ + private class OtherThreadRead { + lateinit var thread: Thread + @Volatile var result: Map? = null + @Volatile var error: Throwable? = null + + fun await(): Map? { + thread.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS * 2)) + assertThat(thread.isAlive).isFalse() + error?.let { throw it } + return result + } + } + + @Suppress("UNCHECKED_CAST") + private fun argumentsOf(serializer: KSerializer, entry: T): KotlinxArguments = + KotlinxArguments(entry, serializer as KSerializer) { failures += it } + + private companion object { + /** Bounds every wait, so that a deadlock fails the test rather than hanging it. */ + const val TIMEOUT_SECONDS = 5L + } +} 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 8703282b6f..804a3c4d45 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,9 +107,153 @@ 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`() { + // Neither an incompatible nor an inconclusive check is logged, as neither is run. + val probe = + FakeCompatibilityProbe( + encodingError = NoSuchMethodError(), + encodingInconclusiveError = IllegalStateException(), + ) + 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(encodingError = 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 `records no arguments for objects when the properties encoder is incompatible`() { + val probe = FakeCompatibilityProbe(encodingError = 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(encodingError = 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(encodingError = 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(encodingError = 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 `records encoded properties when the encoding check is inconclusive`() { + val probe = FakeCompatibilityProbe(encodingInconclusiveError = IllegalStateException()) + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail", mapOf("id" to "1"))) + } + + @Test + fun `logs at debug level with the error when the encoding check is inconclusive`() { + val error = IllegalStateException("check failed") + val probe = FakeCompatibilityProbe(encodingInconclusiveError = error) + + val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) + + val message = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.DEBUG), + eq(error), + message.capture(), + eq(ENCODING_CAPABILITY), + eq(PROBE_THREW), + ) + assertThat(message.firstValue).startsWith(INCONCLUSIVE_PROBE) + } + private companion object { const val NAME_LOOKUP_CAPABILITY = "name lookups" + const val ENCODING_CAPABILITY = "property encoding" + const val INCONCLUSIVE_PROBE = "Nav3 couldn't verify kotlinx.serialization support for %s" const val PROBE_THREW = "the compatibility probe threw (see the attached error)" 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 0000000000..ea4a5d6b25 --- /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 b7fe764f3c..cc53138726 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 @@ -23,6 +23,24 @@ class KotlinxCompatibilityProbeTest { assertThat(inconclusive).isEmpty() } + // encodingLinkageError() + + @Test + fun `encodingLinkageError() - returns null for a compatible kotlinx serialization version`() { + val error = KotlinxCompatibilityProbe.encodingLinkageError {} + + assertThat(error).isNull() + } + + @Test + fun `encodingLinkageError() - finds a compatible kotlinx serialization version conclusively`() { + val inconclusive = mutableListOf() + + KotlinxCompatibilityProbe.encodingLinkageError { inconclusive += it } + + assertThat(inconclusive).isEmpty() + } + // Probe types @Test @@ -37,4 +55,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 inconclusive. + 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 1d0f853c8d..d7f6ac5a31 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 @@ -84,8 +84,11 @@ internal class ShapeThrowingDetailSerializer( */ internal class FakeCompatibilityProbe( private val nameLookupError: LinkageError? = null, + private val encodingError: LinkageError? = null, private val nameLookupInconclusive: Inconclusive? = null, + private val encodingInconclusiveError: Throwable? = null, ) : KotlinxCompatibilityProbe { + var encodingChecks = 0 override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? { nameLookupError?.let { @@ -95,6 +98,12 @@ internal class FakeCompatibilityProbe( return null } + override fun encodingLinkageError(onInconclusive: (Throwable) -> Unit): LinkageError? { + encodingChecks++ + encodingInconclusiveError?.let(onInconclusive) + return encodingError + } + /** Why the name check is inconclusive: [error], or `null` if a probe serializer wasn't found. */ class Inconclusive(val error: Throwable?) } @@ -109,6 +118,7 @@ internal class FakeCompatibilityProbe( */ internal class KotlinxMapperFixture private constructor( + includeProperties: Boolean, useDefaultLookUp: Boolean, val probe: KotlinxCompatibilityProbe, ) { @@ -129,9 +139,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 +154,10 @@ private constructor( companion object { fun create( + includeProperties: Boolean = false, useDefaultLookUp: Boolean = false, probe: KotlinxCompatibilityProbe = FakeCompatibilityProbe(), - ) = KotlinxMapperFixture(useDefaultLookUp, probe) + ) = KotlinxMapperFixture(includeProperties, useDefaultLookUp, probe) } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt new file mode 100644 index 0000000000..4d0c81cd77 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt @@ -0,0 +1,36 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.ArgumentSink +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import org.junit.Assert.assertThrows +import org.junit.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.verifyNoInteractions + +class KotlinxUnencodableArgumentsTest { + + @Test + fun `reads as only the encoding failure`() { + val arguments: Map = KotlinxUnencodableArguments + + assertThat(arguments) + .containsExactly( + ArgumentDropReason.ARGUMENT_DROP_REASON_KEY, + ArgumentDropReason.ENCODING_FAILED.serializedValue, + ) + } + + @Test + fun `writeTo() - drops the arguments as an unlogged encoding failure without writing to the sink`() { + val sink = mock() + + val thrown = + assertThrows(DropArguments::class.java) { KotlinxUnencodableArguments.writeTo(sink) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(thrown.warning).isNull() + verifyNoInteractions(sink) + } +} From 79e45837f275526a8c6053dae196064b1934c7a2 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 20 Nov 2026 12:47:13 +0100 Subject: [PATCH 2/5] fix(nav3): Fail closed when the property-encoding probe can't confirm the encoder The built-in SerialNameAndProperties mapper's compatibility probe treated only a LinkageError from the property encoder as conclusive; any other failure was inconclusive and property encoding proceeded anyway. An API-incompatible kotlinx.serialization version can fail the encoder without a LinkageError (for instance, a NullPointerException under R8), so the probe passed and the mapper went on to record wrong arguments. Now any failure of the encode probe disables property encoding and keeps names, since recording wrong arguments is worse than recording none. --- .../kotlinx/KotlinxBackStackEntryMapper.kt | 8 +-- .../kotlinx/KotlinxCompatibilityProbe.kt | 35 +++++++--- .../KotlinxBackStackEntryMapperProbeTest.kt | 69 +++++++++++-------- .../kotlinx/KotlinxCompatibilityProbeTest.kt | 17 ++--- .../backstack/kotlinx/KotlinxMapperFixture.kt | 16 ++--- 5 files changed, 79 insertions(+), 66 deletions(-) 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 9cba2abab8..523953d95d 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 @@ -75,10 +75,7 @@ internal class KotlinxBackStackEntryMapper( private val isEncodingIncompatible: Boolean = includeProperties && run { - val error = - probe.encodingLinkageError { error -> - diagnostics.inconclusiveProbe(ENCODING_CAPABILITY, error) - } ?: return@run false + val error = probe.encoderIncompatibility() ?: return@run false diagnostics.incompatibleEncoder(error) true } @@ -275,7 +272,6 @@ internal class KotlinxBackStackEntryMapper( private class SerializerLookup(val serializer: KSerializer<*>?, val error: Throwable?) private companion object { - private const val ENCODING_CAPABILITY = "property encoding" private const val NAME_LOOKUP_CAPABILITY = "name lookups" private val UNRESOLVED = CachedType(serializer = null, name = null) } @@ -334,7 +330,7 @@ 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: LinkageError) { + fun incompatibleEncoder(error: Throwable) { logger() .log( WARNING, 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 493592611b..3fef617630 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 @@ -23,9 +23,12 @@ import kotlinx.serialization.Serializable * `ProbeObject` don't execute any host app code, so a `LinkageError` while handling them means the * app's kotlinx.serialization version is incompatible. * - * Note: Only a `LinkageError` is conclusive. Any other failure, or a probe type whose serializer - * can't be found, leaves the check inconclusive: it's reported to the caller's `onInconclusive` and - * otherwise ignored, as a real type that hits the same failure is handled and logged on its own. + * Note: For the name lookup check ([nameLookupLinkageError]), only a `LinkageError` is conclusive. + * Any other failure, or a probe type whose serializer can't be found, leaves it 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 encoder check ([encoderIncompatibility]) + * instead treats any failure as conclusive, because a broken encoder can record wrong arguments + * without throwing, and recording wrong arguments is worse than recording none. */ internal interface KotlinxCompatibilityProbe { @@ -42,14 +45,16 @@ internal interface KotlinxCompatibilityProbe { fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? /** - * Encodes [ProbeClass] using the same path as [KotlinxBackStackEntryMapper]. + * Encodes [ProbeClass] using the same path as [KotlinxBackStackEntryMapper] and checks that it + * links and runs. * - * Returns a [LinkageError] if the encoder can't link against the host app's kotlinx.serialization - * version, or `null` if encoding succeeds or the check is inconclusive. - * - * Calls [onInconclusive] for each inconclusive result, passing the cause. + * Returns the error that makes the properties encoder unusable, or `null` if encoding succeeds. + * Unlike [nameLookupLinkageError], any failure is conclusive: an incompatible + * kotlinx.serialization version can fail the encoder without a [LinkageError] (for instance, an + * API-incompatible encoder can throw a [NullPointerException] under R8), and the caller disables + * property encoding on any failure here rather than risk recording wrong arguments. */ - fun encodingLinkageError(onInconclusive: (Throwable) -> Unit): LinkageError? + fun encoderIncompatibility(): Throwable? /** Probes the app's kotlinx.serialization version using [ProbeClass] and [ProbeObject]. */ companion object : KotlinxCompatibilityProbe { @@ -80,14 +85,22 @@ internal interface KotlinxCompatibilityProbe { return error } - override fun encodingLinkageError(onInconclusive: (Throwable) -> Unit): LinkageError? = - probe(onInconclusive) { + override fun encoderIncompatibility(): Throwable? = + try { @Suppress("UNCHECKED_CAST") KotlinxPropertiesEncoder.encode( ProbeClass.serializer() as KSerializer, ProbeClass(), TreeArgumentWriter(ArgumentBudget()), ) + null + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because an incompatible kotlinx.serialization version can fail the encoder in any + // way, not only with a LinkageError. Any failure disables property encoding and keeps + // names, + // as recording wrong arguments would be worse than recording none. + ExceptionUtils.rethrowIfFatal(t) + t } /** 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 804a3c4d45..1f9a2a7cf7 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 @@ -132,12 +132,8 @@ class KotlinxBackStackEntryMapperProbeTest { @Test fun `never checks the properties encoder when properties are excluded`() { - // Neither an incompatible nor an inconclusive check is logged, as neither is run. - val probe = - FakeCompatibilityProbe( - encodingError = NoSuchMethodError(), - encodingInconclusiveError = IllegalStateException(), - ) + // 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 @@ -150,7 +146,7 @@ class KotlinxBackStackEntryMapperProbeTest { @Test fun `keeps the name and records only the encoding failure when the properties encoder is incompatible`() { - val probe = FakeCompatibilityProbe(encodingError = NoSuchMethodError()) + val probe = FakeCompatibilityProbe(encoderError = NoSuchMethodError()) val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) val mapper = fixture.mapper @@ -166,7 +162,7 @@ class KotlinxBackStackEntryMapperProbeTest { @Test fun `records no arguments for objects when the properties encoder is incompatible`() { - val probe = FakeCompatibilityProbe(encodingError = NoSuchMethodError()) + val probe = FakeCompatibilityProbe(encoderError = NoSuchMethodError()) val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) val mapper = fixture.mapper @@ -177,7 +173,7 @@ class KotlinxBackStackEntryMapperProbeTest { @Test fun `doesn't encode properties when the properties encoder is incompatible`() { - val probe = FakeCompatibilityProbe(encodingError = NoSuchMethodError()) + val probe = FakeCompatibilityProbe(encoderError = NoSuchMethodError()) val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) val mapper = fixture.mapper @@ -190,7 +186,7 @@ class KotlinxBackStackEntryMapperProbeTest { @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(encodingError = error) + val probe = FakeCompatibilityProbe(encoderError = error) val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) val message = argumentCaptor() @@ -206,7 +202,7 @@ class KotlinxBackStackEntryMapperProbeTest { @Test fun `logs nothing more for entries mapped when the properties encoder is incompatible`() { val error = NoSuchMethodError() - val probe = FakeCompatibilityProbe(encodingError = error) + val probe = FakeCompatibilityProbe(encoderError = error) val fixture = KotlinxMapperFixture.create(includeProperties = true, probe = probe) val mapper = fixture.mapper @@ -220,40 +216,59 @@ class KotlinxBackStackEntryMapperProbeTest { } @Test - fun `records encoded properties when the encoding check is inconclusive`() { - val probe = FakeCompatibilityProbe(encodingInconclusiveError = IllegalStateException()) + 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", mapOf("id" to "1"))) + assertThat(mapped) + .isEqualTo(SentryBackStackEntry("Detail", droppedBy(ArgumentDropReason.ENCODING_FAILED))) } @Test - fun `logs at debug level with the error when the encoding check is inconclusive`() { - val error = IllegalStateException("check failed") - val probe = FakeCompatibilityProbe(encodingInconclusiveError = error) + 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.DEBUG), - eq(error), - message.capture(), - eq(ENCODING_CAPABILITY), - eq(PROBE_THREW), + 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).startsWith(INCONCLUSIVE_PROBE) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) } private companion object { const val NAME_LOOKUP_CAPABILITY = "name lookups" - const val ENCODING_CAPABILITY = "property encoding" - const val INCONCLUSIVE_PROBE = "Nav3 couldn't verify kotlinx.serialization support for %s" const val PROBE_THREW = "the compatibility probe threw (see the attached error)" 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 cc53138726..28cda10b44 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 @@ -23,24 +23,15 @@ class KotlinxCompatibilityProbeTest { assertThat(inconclusive).isEmpty() } - // encodingLinkageError() + // encoderIncompatibility() @Test - fun `encodingLinkageError() - returns null for a compatible kotlinx serialization version`() { - val error = KotlinxCompatibilityProbe.encodingLinkageError {} + fun `encoderIncompatibility() - returns null for a compatible kotlinx serialization version`() { + val error = KotlinxCompatibilityProbe.encoderIncompatibility() assertThat(error).isNull() } - @Test - fun `encodingLinkageError() - finds a compatible kotlinx serialization version conclusively`() { - val inconclusive = mutableListOf() - - KotlinxCompatibilityProbe.encodingLinkageError { inconclusive += it } - - assertThat(inconclusive).isEmpty() - } - // Probe types @Test @@ -58,7 +49,7 @@ class KotlinxCompatibilityProbeTest { @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 inconclusive. + // A probe type that failed to encode for another reason would make the check fail closed. val encoded = encodeToMap(ProbeClass.serializer(), ProbeClass()) assertThat(encoded) 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 d7f6ac5a31..7cb9a36fe8 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,16 +77,15 @@ 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 encodingError: LinkageError? = null, + private val encoderError: Throwable? = null, private val nameLookupInconclusive: Inconclusive? = null, - private val encodingInconclusiveError: Throwable? = null, ) : KotlinxCompatibilityProbe { var encodingChecks = 0 @@ -98,10 +97,9 @@ internal class FakeCompatibilityProbe( return null } - override fun encodingLinkageError(onInconclusive: (Throwable) -> Unit): LinkageError? { + override fun encoderIncompatibility(): Throwable? { encodingChecks++ - encodingInconclusiveError?.let(onInconclusive) - return encodingError + return encoderError } /** Why the name check is inconclusive: [error], or `null` if a probe serializer wasn't found. */ From 340b10452d5fa0003813040f93dc88dcadcf1e73 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 20 Nov 2026 12:54:00 +0100 Subject: [PATCH 3/5] fix(nav3): Verify the probe's encoded output to catch silent argument corruption The property-encoding compatibility probe ran the encoder but ignored its output, so a binary-incompatible kotlinx.serialization version that links and runs yet mis-encodes under R8 (observed renaming {id=1} to {value=1} and dropping a route as a duplicate key) passed the probe, and the mapper then recorded wrong arguments. The probe now compares the encoded ProbeClass fixture to its known-good output and disables property encoding when they differ, keeping names. The mismatch signal carries only a fixed message, never route data. --- .../kotlinx/KotlinxCompatibilityProbe.kt | 50 ++++++++++++++----- .../KotlinxBackStackEntryMapperProbeTest.kt | 28 +++++++++++ .../kotlinx/KotlinxCompatibilityProbeTest.kt | 15 ++++++ 3 files changed, 81 insertions(+), 12 deletions(-) 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 3fef617630..23d8e9ad1a 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 @@ -45,14 +45,15 @@ internal interface KotlinxCompatibilityProbe { fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? /** - * Encodes [ProbeClass] using the same path as [KotlinxBackStackEntryMapper] and checks that it - * links and runs. + * Encodes [ProbeClass] using the same path as [KotlinxBackStackEntryMapper], checks that it links + * and runs, and verifies its output matches the known fixture. * - * Returns the error that makes the properties encoder unusable, or `null` if encoding succeeds. - * Unlike [nameLookupLinkageError], any failure is conclusive: an incompatible + * Returns the error that makes the properties encoder unusable, or `null` if encoding succeeds + * and matches. Unlike [nameLookupLinkageError], any failure is conclusive: an incompatible * kotlinx.serialization version can fail the encoder without a [LinkageError] (for instance, an - * API-incompatible encoder can throw a [NullPointerException] under R8), and the caller disables - * property encoding on any failure here rather than risk recording wrong arguments. + * API-incompatible encoder can throw a [NullPointerException] under R8) or mis-encode without + * throwing at all, and the caller disables property encoding on any failure here rather than risk + * recording wrong arguments. */ fun encoderIncompatibility(): Throwable? @@ -87,18 +88,25 @@ internal interface KotlinxCompatibilityProbe { override fun encoderIncompatibility(): Throwable? = try { + val writer = TreeArgumentWriter(ArgumentBudget()) @Suppress("UNCHECKED_CAST") KotlinxPropertiesEncoder.encode( ProbeClass.serializer() as KSerializer, ProbeClass(), - TreeArgumentWriter(ArgumentBudget()), + writer, ) - null + // 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() + } } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { - // Broad because an incompatible kotlinx.serialization version can fail the encoder in any - // way, not only with a LinkageError. Any failure disables property encoding and keeps - // names, - // as recording wrong arguments would be worse than recording none. + // 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 } @@ -148,5 +156,23 @@ internal interface KotlinxCompatibilityProbe { * back stack entries. This lookup reads the object's singleton instance. */ @Serializable internal object ProbeObject + + /** + * [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)) } } + +/** + * Signals that the properties encoder ran but produced output that didn't match the SDK's own + * `ProbeClass` fixture, so the app's kotlinx.serialization version mis-encodes properties. Carries + * only a fixed message, never route data: the fixture is the SDK's own. + */ +internal class EncoderProducedUnexpectedOutput : + RuntimeException( + "The kotlinx.serialization properties encoder produced unexpected output for a known fixture.", + ) 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 1f9a2a7cf7..1632a609b4 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 @@ -266,6 +266,34 @@ class KotlinxBackStackEntryMapperProbeTest { 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/KotlinxCompatibilityProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt index 28cda10b44..ead239a2a0 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 @@ -27,11 +27,26 @@ class KotlinxCompatibilityProbeTest { @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() } + @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 From 95786cbd99366bfb65a596faa994f5c51b64ffc0 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 20 Nov 2026 13:17:00 +0100 Subject: [PATCH 4/5] Refine --- .../kotlinx/KotlinxCompatibilityProbe.kt | 58 +++++++++---------- 1 file changed, 29 insertions(+), 29 deletions(-) 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 23d8e9ad1a..cc2a27d773 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 @@ -16,19 +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: For the name lookup check ([nameLookupLinkageError]), only a `LinkageError` is conclusive. - * Any other failure, or a probe type whose serializer can't be found, leaves it 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 encoder check ([encoderIncompatibility]) - * instead treats any failure as conclusive, because a broken encoder can record wrong arguments - * without throwing, and recording wrong arguments is worse than recording none. + * 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 { @@ -48,12 +48,10 @@ internal interface KotlinxCompatibilityProbe { * Encodes [ProbeClass] using the same path as [KotlinxBackStackEntryMapper], checks that it links * and runs, and verifies its output matches the known fixture. * - * Returns the error that makes the properties encoder unusable, or `null` if encoding succeeds - * and matches. Unlike [nameLookupLinkageError], any failure is conclusive: an incompatible - * kotlinx.serialization version can fail the encoder without a [LinkageError] (for instance, an - * API-incompatible encoder can throw a [NullPointerException] under R8) or mis-encode without - * throwing at all, and the caller disables property encoding on any failure here rather than risk - * recording wrong arguments. + * 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? @@ -152,25 +150,27 @@ internal interface KotlinxCompatibilityProbe { ) /** - * 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. + * [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. */ - @Serializable internal object ProbeObject + private val EXPECTED_PROBE_ENCODING: Map = + mapOf("name" to "probe", "values" to listOf(1), "counts" to 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. + * 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. */ - private val EXPECTED_PROBE_ENCODING: Map = - mapOf("name" to "probe", "values" to listOf(1), "counts" to mapOf("count" to 1)) + @Serializable internal object ProbeObject } } /** - * Signals that the properties encoder ran but produced output that didn't match the SDK's own - * `ProbeClass` fixture, so the app's kotlinx.serialization version mis-encodes properties. Carries - * only a fixed message, never route data: the fixture is the SDK's own. + * 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( From a6a8dad9f5b301ade4dfe7d6e17588eb4965a5cc Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 20 Nov 2026 13:26:11 +0100 Subject: [PATCH 5/5] fix(nav3): Keep names when the property encoder can't link The encoding probe's broad catch passed LinkageErrors to ExceptionUtils.rethrowIfFatal, which rethrows them. The error then escaped the mapper's constructor, and BuiltInBackStackEntryMappers fell back to a mapper that records no names, instead of only disabling property encoding. The probe now returns a LinkageError before the fatal-error check, so an encoder that can't link keeps names and records encoding_failed, as other encoder failures do. --- .../kotlinx/KotlinxCompatibilityProbe.kt | 47 +++++++++++------ .../KotlinxBackStackEntryMapperProbeTest.kt | 22 ++++++++ .../kotlinx/KotlinxCompatibilityProbeTest.kt | 52 +++++++++++++++++++ 3 files changed, 105 insertions(+), 16 deletions(-) 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 cc2a27d773..701aa1ec82 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 @@ -84,23 +84,38 @@ internal interface KotlinxCompatibilityProbe { return error } - override fun encoderIncompatibility(): Throwable? = + 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 { - 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() - } + 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 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 1632a609b4..823b20aee9 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 @@ -160,6 +160,28 @@ class KotlinxBackStackEntryMapperProbeTest { .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()) 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 ead239a2a0..954c43fa8b 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 /** @@ -34,6 +35,57 @@ class KotlinxCompatibilityProbeTest { 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()