diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt index 4b45d7c5b21..c91b3b6f541 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt @@ -5,7 +5,7 @@ import org.jetbrains.annotations.ApiStatus // Keep the default low, as every captured entry may require argument extraction and recursive // sanitization when navigation changes are observed. -private const val DEFAULT_MAX_CAPTURED_BACK_STACK_ENTRIES = 5 +internal const val DEFAULT_MAX_CAPTURED_BACK_STACK_ENTRIES = 5 /** * Configuration info for a [SentryNavEffect]. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConstraints.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConstraints.kt deleted file mode 100644 index 42b428c7108..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConstraints.kt +++ /dev/null @@ -1,45 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack - -internal object ArgumentConstraints { - - /** - * Max combined length of map keys and text values visited in one back stack update. - * - * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries - * are preserved. - * - * Caps payload size in the presence of large individual arguments. - */ - const val MAX_ARGUMENT_CHARACTERS = 4_096 - - /** - * Max depth of an argument value within one back stack entry. Root arguments have depth 1; each - * nested map or list adds one level. - * - * For instance, `mapOf("id" to 123)` reaches a depth of 1; `mapOf("items" to listOf("apple", - * "banana"))` reaches a depth of 2. - * - * If exceeded, all arguments for that back stack entry are dropped. - */ - const val MAX_ARGUMENT_DEPTH = 10 - - /** - * Max number of argument values visited in one back stack update. Each scalar or nested container - * counts as one value; map keys and each entry's root argument map are excluded. - * - * For instance, `mapOf("id" to 123)` consumes 1 value; `mapOf("profile" to mapOf("id" to 123, - * "name" to "Ada"))` consumes 3 values. - * - * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries - * are preserved. - * - * For instance, suppose we have the following back stack: - * - * - /Checkout -> Top of the stack and processed first - * - /ProductDetail -> Processed second and exceeds the `MAX_ARGUMENT_VALUES` budget - * - /Home - * - * Then /ProductDetail and /Home will have no arguments, but /Checkout will. - */ - const val MAX_ARGUMENT_VALUES = 200 -} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index e15194da1c2..8935568e792 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt @@ -5,11 +5,14 @@ import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES -import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY -import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY +import io.sentry.compose.navigation3.internal.contract.BACK_STACK_ENTRY_ARGUMENTS_KEY +import io.sentry.compose.navigation3.internal.contract.BACK_STACK_ENTRY_KEY +import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.util.ExceptionUtils import java.util.IdentityHashMap @@ -139,27 +142,36 @@ internal class BackStackConverter( ) /** - * Sanitizes a back stack entry's arguments and writes them in a serializable form. It bounds - * depth and total value count, and it rejects cyclic structures. + * Sanitizes the arguments the [entryMapper] returns for back stack entries and returns them in a + * [serializable form][SanitizedArguments.values]. It bounds depth and total value count, and it + * rejects cyclic structures. * - * One instance is shared across every entry in a single [convert] call, so the value budget is - * enforced across the whole update. Once the budget is spent, the overflowing entry and every - * older entry are dropped, while newer (already-processed) entries are preserved. + * One instance is shared across every entry in a single [convert] call, so the value and + * character budgets span the whole update. */ internal class ArgumentSanitizer( private val logger: ILogger, private val warningState: WarningState, ) { - private val activeContainers = IdentityHashMap() private var remainingValues = MAX_ARGUMENT_VALUES private var remainingCharacters = MAX_ARGUMENT_CHARACTERS private var dropReason: ArgumentDropReason? = null + /** The maps and lists currently being sanitized, so that one containing itself is rejected. */ + private val activeContainers = IdentityHashMap() + /** - * Sanitizes one entry's arguments, or returns an empty map to drop them, either because the - * structure is cyclic or too deeply nested (this entry only), or because the shared per-update - * value budget is spent (this entry and every older one). + * Sanitizes one entry's raw argument inputs and returns the result. + * + * [SanitizedArguments.values] will be empty if [raw] is empty or if the arguments were dropped. + * Arguments can be dropped if: + * + * - a previously processed entry exceeded the shared value or character budget; + * - an argument constraint is violated; or + * - conversion fails. + * + * [SanitizedArguments.dropReason] will be non-null if and only if arguments are dropped. */ @Suppress("TooGenericExceptionCaught") fun sanitizeEntry(raw: Map): SanitizedArguments { @@ -169,7 +181,7 @@ internal class BackStackConverter( return try { SanitizedArguments(sanitizeMap(raw, depth = 0)) - } catch (drop: DropSubtree) { + } catch (drop: DropArguments) { if (drop.reason.exhaustsUpdateBudget) { dropReason = drop.reason } @@ -180,131 +192,112 @@ internal class BackStackConverter( ExceptionUtils.rethrowIfFatal(t) logger.log(WARNING, STRUCTURE_WARNING, t) SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) - } - } - - private fun sanitizeMap(value: Map<*, *>, depth: Int): Map { - enter(value) - try { - val sanitized = mutableMapOf() - for ((key, childValue) in value) { - val keyString = key.toString() - consumeCharacters(keyString.length) - if (sanitized.containsKey(keyString)) { - // Types only b/c key strings may contain host data. Collisions are rare, so we re-scan - // instead of tracking original keys for every map. - val otherKey = value.keys.firstOrNull { it !== key && it.toString() == keyString } - throw DropSubtree( - "A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same " + - "string as another key (${otherKey?.let { it::class.simpleName }}). " + - "Dropping this entry's arguments.", - ArgumentDropReason.DUPLICATE_KEY, - ) - } - sanitized[keyString] = sanitizeValue(childValue, depth + 1) - } - return sanitized } finally { - exit(value) + // A drop or failure leaves the containers it was inside of open. + activeContainers.clear() } } - private fun sanitizeCollection(value: Collection<*>, depth: Int): List { - enter(value) - try { - // The value budget bounds allocation instead of the caller-provided collection size. - val sanitized = mutableListOf() - for (childValue in value) { - sanitized += sanitizeValue(childValue, depth + 1) + /** Sanitizes [map], whose values are at [depth] + 1. The entry's root map has depth 0. */ + private fun sanitizeMap(map: Map<*, *>, depth: Int): Map { + enter(map) + val sanitized = LinkedHashMap() + for ((key, value) in map) { + val name = spendText(key.toString()) + if (sanitized.containsKey(name)) { + throw duplicateKey(map, key, name) } - return sanitized - } finally { - exit(value) + sanitized[name] = sanitizeValue(value, depth + 1) } + activeContainers.remove(map) + return sanitized } private fun sanitizeValue(value: Any?, depth: Int): Any? { - visit(depth) - val collection = value?.asSanitizableCollectionOrNull() + // A value at depth n is nested in n containers, counting the entry's root map. + if (depth > MAX_ARGUMENT_DEPTH) { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING) + } + if (--remainingValues < 0) { + throw DropArguments(ArgumentDropReason.MAX_COUNT, MAX_COUNT_WARNING) + } - return when { - value is Map<*, *> -> sanitizeMap(value, depth) - collection != null -> sanitizeCollection(collection, depth) - else -> sanitizeScalar(value) + if (value is Map<*, *>) { + return sanitizeMap(value, depth) } + val collection = value?.asCollectionOrNull() ?: return sanitizeScalar(value) + + enter(value) + // Iterated without reading the collection's size, which the host app controls. + val sanitized = ArrayList() + for (element in collection) { + sanitized += sanitizeValue(element, depth + 1) + } + activeContainers.remove(value) + return sanitized } private fun sanitizeScalar(value: Any?): Any? = when (value) { null, is Boolean -> value - is Number -> - if (value.isNonFinite()) { - value.toString().also { consumeCharacters(it.length) } - } else value - is String -> value.also { consumeCharacters(it.length) } - is CharSequence, - is Char -> value.toString().also { consumeCharacters(it.length) } - is Enum<*> -> value.name.also { consumeCharacters(it.length) } + // JSON has no NaN or infinity, and Sentry's JSON writer throws for them, which would drop + // the whole event these arguments are attached to. We record them as strings instead. + is Number -> if (value.isNonFinite()) spendText(value.toString()) else value + is CharSequence -> spendText(value) + is Char -> spendText(value.toString()) + is Enum<*> -> spendText(value.name) else -> { warningState.logUnsupportedValueWarning(value::class.simpleName, logger) - value.toString().also { consumeCharacters(it.length) } + spendText(value.toString()) } } - private fun Any.asSanitizableCollectionOrNull(): Collection<*>? = - when (this) { - is Collection<*> -> this - is Array<*> -> asList() - is BooleanArray -> asList() - is ByteArray -> asList() - is ShortArray -> asList() - is IntArray -> asList() - is LongArray -> asList() - is FloatArray -> asList() - is DoubleArray -> asList() - is CharArray -> asList() - else -> null - } - /** - * Records a visit to one value, enforcing the per-entry depth cap and the shared per-update - * value budget. Throws [DropSubtree] to abort the current subtree when either is exceeded. + * Returns [text] as a [String] after spending its characters. + * + * Checks [text]'s length before converting it, so that host app text that doesn't fit isn't + * copied, and again after, in case a custom [CharSequence]'s length doesn't match its text. */ - private fun visit(depth: Int) { - if (depth > MAX_ARGUMENT_DEPTH) { - throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE) - } - if (--remainingValues < 0) { - throw DropSubtree(MAX_COUNT_WARNING, ArgumentDropReason.MAX_COUNT) - } + private fun spendText(text: CharSequence): String { + checkFits(text.length) + val string = text.toString() + checkFits(string.length) + remainingCharacters -= string.length + return string } - private fun consumeCharacters(count: Int) { - if (count > remainingCharacters) { - throw DropSubtree(MAX_CHARACTER_WARNING, ArgumentDropReason.CHARACTER_LIMIT) + private fun checkFits(characters: Int) { + if (characters > remainingCharacters) { + throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, MAX_CHARACTER_WARNING) } - remainingCharacters -= count } private fun enter(container: Any) { if (activeContainers.put(container, Unit) != null) { - throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE) + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING) } } - private fun exit(container: Any) { - activeContainers.remove(container) + /** + * Names only the colliding keys' types, as the keys themselves may contain host data. + * Collisions are rare, so we re-scan [map] instead of tracking the original keys of every map. + */ + private fun duplicateKey(map: Map<*, *>, key: Any?, name: String): DropArguments { + val otherKey = map.keys.firstOrNull { it !== key && it.toString() == name } + return DropArguments( + ArgumentDropReason.DUPLICATE_KEY, + "A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same string " + + "as another key (${otherKey?.let { it::class.simpleName }}). Dropping this entry's " + + "arguments.", + ) } /** - * Control-flow signal to abort sanitization of the current subtree. Internal to - * [ArgumentSanitizer]. - * - * [reason] distinguishes entry-local drops from update-wide budget exhaustion. Overrides + * Control-flow signal to drop an entry's arguments, logging [warning]. Overrides * [fillInStackTrace] to skip stack-trace capture. */ - private class DropSubtree(val warning: String, val reason: ArgumentDropReason) : + private class DropArguments(val reason: ArgumentDropReason, val warning: String) : RuntimeException() { override fun fillInStackTrace(): Throwable = this } @@ -387,8 +380,6 @@ internal data class NormalizedSentryBackStackEntry( companion object { - const val UNKNOWN_ENTRY_NAME = "/unknown" - /** * Trims [name] and adds a "/" prefix if one isn't already present. * @@ -426,32 +417,32 @@ internal data class NormalizedSentryBackStackEntry( * ``` */ fun serialize(): Map = buildMap { - put("entry", name) - argumentsWithMetadata().takeIf { it.isNotEmpty() }?.let { put("entry_arguments", it) } + put(BACK_STACK_ENTRY_KEY, name) + argumentsWithMetadata() + .takeIf { it.isNotEmpty() } + ?.let { put(BACK_STACK_ENTRY_ARGUMENTS_KEY, it) } } } internal fun List.serialize(): List> = map(NormalizedSentryBackStackEntry::serialize) -/** Why host-provided arguments were unavailable in emitted nav state. */ -internal enum class ArgumentDropReason( - val serializedValue: String, - val exhaustsUpdateBudget: Boolean = false, -) { - - CHARACTER_LIMIT("max_character_limit_exceeded", exhaustsUpdateBudget = true), - DUPLICATE_KEY("duplicate_key"), - INVALID_STRUCTURE("invalid_structure"), - MAPPING_FAILED("mapping_failed"), - MAX_COUNT("max_argument_count_exceeded", exhaustsUpdateBudget = true), - SANITIZATION_FAILED("sanitization_failed"); - - companion object { - const val ARGUMENT_DROP_REASON_KEY = "dropped_by_sentry" +/** Returns this collection, or this array as a list, or `null` if it's neither. */ +private fun Any.asCollectionOrNull(): Collection<*>? = + when (this) { + is Collection<*> -> this + is Array<*> -> asList() + is BooleanArray -> asList() + is ByteArray -> asList() + is ShortArray -> asList() + is IntArray -> asList() + is LongArray -> asList() + is FloatArray -> asList() + is DoubleArray -> asList() + is CharArray -> asList() + else -> null } -} -/** Whether this is a NaN or infinite Double or Float. */ +/** Whether this is a NaN or infinite `Double` or `Float`. */ private fun Number.isNonFinite(): Boolean = (this is Double && !isFinite()) || (this is Float && !isFinite()) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt index 988000c6b67..9dbd999ffea 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt @@ -15,10 +15,15 @@ import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.Reten import io.sentry.compose.navigation3.internal.backstack.PreparedChange.BackStackHasNewTop import io.sentry.compose.navigation3.internal.backstack.PreparedChange.BackStackHasSameTop import io.sentry.compose.navigation3.internal.backstack.PreparedChange.BackStackIsEmpty +import io.sentry.compose.navigation3.internal.contract.BACK_STACK_KEY +import io.sentry.compose.navigation3.internal.contract.BREADCRUMB_FROM_ARGUMENTS_KEY +import io.sentry.compose.navigation3.internal.contract.BREADCRUMB_FROM_KEY +import io.sentry.compose.navigation3.internal.contract.BREADCRUMB_TO_ARGUMENTS_KEY +import io.sentry.compose.navigation3.internal.contract.BREADCRUMB_TO_KEY +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_CONTEXT_KEY +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_OP import io.sentry.compose.navigation3.internal.lifecycle.INavScope import io.sentry.compose.navigation3.internal.lifecycle.INavScopes -import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_CONTEXT_KEY -import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_OP import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo import io.sentry.compose.navigation3.internal.lifecycle.NavScopes @@ -293,10 +298,6 @@ private data class BackStackData( /** A helper class for updating [nav context][NAVIGATION_CONTEXT_KEY]. */ private class NavContext(private val options: SentryNavOptions) { - private companion object { - private const val BACKSTACK_KEY = "Back Stack" - } - fun update(scope: INavScope, backStackEntries: List) { if (backStackEntries.isEmpty()) { clear(scope) @@ -327,9 +328,9 @@ private class NavContext(private val options: SentryNavOptions) { emptyMap() } - /** Builds the `{"backstack": [...]}` map bound under [NAVIGATION_CONTEXT_KEY]. */ + /** Builds the `{"Back Stack": [...]}` map bound under [NAVIGATION_CONTEXT_KEY]. */ private fun List.toBackStackMap(): Map = - mapOf(BACKSTACK_KEY to serialize()) + mapOf(BACK_STACK_KEY to serialize()) } /** A helper class for updating the tracked screen name. */ @@ -361,21 +362,21 @@ private class NavBreadcrumbs(private val scopes: INavScopes) { category = NAVIGATION_OP fromEntry?.let { entry -> - data["from"] = entry.name + data[BREADCRUMB_FROM_KEY] = entry.name entry .argumentsWithMetadata() .takeIf { it.isNotEmpty() } ?.let { arguments -> - data["from_arguments"] = arguments + data[BREADCRUMB_FROM_ARGUMENTS_KEY] = arguments } } - data["to"] = toEntry.name + data[BREADCRUMB_TO_KEY] = toEntry.name toEntry .argumentsWithMetadata() .takeIf { it.isNotEmpty() } ?.let { arguments -> - data["to_arguments"] = arguments + data[BREADCRUMB_TO_ARGUMENTS_KEY] = arguments } level = INFO diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt new file mode 100644 index 00000000000..2d24339cfc4 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt @@ -0,0 +1,96 @@ +package io.sentry.compose.navigation3.internal.contract + +/* + * Internal properties that are part of our public contract because they're displayed in + * the Sentry UI or define observable behavior. + */ + +// The context containing the captured navigation back stack. +internal const val NAVIGATION_CONTEXT_KEY = "Navigation" +internal const val BACK_STACK_KEY = "Back Stack" + +// Fields in a serialized back stack entry. +internal const val BACK_STACK_ENTRY_KEY = "entry" +internal const val BACK_STACK_ENTRY_ARGUMENTS_KEY = "entry_arguments" + +// The transaction data field containing the destination's arguments. +internal const val TRANSACTION_ARGUMENTS_KEY = "arguments" + +// Fields in a navigation breadcrumb. +internal const val BREADCRUMB_FROM_KEY = "from" +internal const val BREADCRUMB_TO_KEY = "to" +internal const val BREADCRUMB_FROM_ARGUMENTS_KEY = "from_arguments" +internal const val BREADCRUMB_TO_ARGUMENTS_KEY = "to_arguments" + +internal const val NAVIGATION_OP = "navigation" +internal const val NAVIGATION_TRANSACTION_ORIGIN = "auto.navigation.nav3" + +/** The string displayed in the Sentry UI if the name of a back stack entry can't be determined. */ +internal const val UNKNOWN_ENTRY_NAME = "/unknown" + +/** + * Why host-provided arguments were unavailable in emitted nav state. + * + * Recorded under [ARGUMENT_DROP_REASON_KEY]. + */ +internal enum class ArgumentDropReason( + val serializedValue: String, + val exhaustsUpdateBudget: Boolean = false, +) { + + CHARACTER_LIMIT("max_character_limit_exceeded", exhaustsUpdateBudget = true), + DUPLICATE_KEY("duplicate_key"), + INVALID_STRUCTURE("invalid_structure"), + MAPPING_FAILED("mapping_failed"), + MAX_COUNT("max_argument_count_exceeded", exhaustsUpdateBudget = true), + SANITIZATION_FAILED("sanitization_failed"); + + companion object { + + const val ARGUMENT_DROP_REASON_KEY = "dropped_by_sentry" + } +} + +internal object ArgumentConstraints { + + /** + * Max combined length of map keys and text values visited in one back stack update. + * + * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries + * are preserved. + * + * Caps payload size in the presence of large individual arguments. + */ + const val MAX_ARGUMENT_CHARACTERS = 4_096 + + /** + * Max depth of an argument value within one back stack entry. Root arguments have depth 1; each + * nested map or list adds one level. + * + * For instance, `mapOf("id" to 123)` reaches a depth of 1; `mapOf("items" to listOf("apple", + * "banana"))` reaches a depth of 2. + * + * If exceeded, all arguments for that back stack entry are dropped. + */ + const val MAX_ARGUMENT_DEPTH = 10 + + /** + * Max number of argument values visited in one back stack update. Each scalar or nested container + * counts as one value; map keys and each entry's root argument map are excluded. + * + * For instance, `mapOf("id" to 123)` consumes 1 value; `mapOf("profile" to mapOf("id" to 123, + * "name" to "Ada"))` consumes 3 values. + * + * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries + * are preserved. + * + * For instance, suppose we have the following back stack: + * + * - /Checkout -> Top of the stack and processed first + * - /ProductDetail -> Processed second and exceeds the `MAX_ARGUMENT_VALUES` budget + * - /Home + * + * Then /ProductDetail and /Home will have no arguments, but /Checkout will. + */ + const val MAX_ARGUMENT_VALUES = 200 +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavScopes.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavScopes.kt index d7b1e46554d..85ff54f3862 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavScopes.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavScopes.kt @@ -8,9 +8,7 @@ import io.sentry.IScopes import io.sentry.PropagationContext import io.sentry.SentryLevel import io.sentry.SentryOptions - -/** The key under which nav context (i.e., the captured back stack) is stored in a scope. */ -internal const val NAVIGATION_CONTEXT_KEY: String = "Navigation" +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_CONTEXT_KEY /** * An [INavScopes] implementation that lets us coordinate updates to navigation state across diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequest.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequest.kt index ffe39e13d56..4797418f3db 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequest.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequest.kt @@ -6,13 +6,13 @@ import io.sentry.ITransaction import io.sentry.SentryOptions import io.sentry.TransactionContext import io.sentry.TransactionOptions +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_OP +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_TRANSACTION_ORIGIN +import io.sentry.compose.navigation3.internal.contract.TRANSACTION_ARGUMENTS_KEY import io.sentry.protocol.App import io.sentry.protocol.Contexts import io.sentry.protocol.TransactionNameSource -/** The operation of nav transactions, and the type and category of nav breadcrumbs. */ -internal const val NAVIGATION_OP: String = "navigation" - /** * Everything needed to start a nav transaction for a destination. * @@ -23,6 +23,7 @@ internal const val NAVIGATION_OP: String = "navigation" * transaction finishes. Each [start] creates a new transaction for the same destination. */ internal class NavTransactionRequest( + /** The name of the nav transaction. */ val name: String, /** Builds the options for each transaction started from this request. */ private val newOptions: () -> TransactionOptions, @@ -40,8 +41,6 @@ internal class NavTransactionRequest( companion object { - private const val TRANSACTION_ORIGIN = "auto.navigation.nav3" - /** Creates a request whose transaction options are read when each transaction starts. */ fun forDestination( name: String, @@ -59,10 +58,11 @@ internal class NavTransactionRequest( val deadlineTimeoutMillis = options.deadlineTimeout it.deadlineTimeout = if (deadlineTimeoutMillis <= 0) null else deadlineTimeoutMillis it.isTrimEnd = true - it.origin = TRANSACTION_ORIGIN + it.origin = NAVIGATION_TRANSACTION_ORIGIN } }, - data = if (arguments.isNotEmpty()) mapOf("arguments" to arguments) else emptyMap(), + data = + if (arguments.isNotEmpty()) mapOf(TRANSACTION_ARGUMENTS_KEY to arguments) else emptyMap(), contexts = contexts, viewNames = viewNames, ) 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 ae1750f00dc..78633a4ef4b 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 @@ -2,6 +2,7 @@ package io.sentry.compose.navigation3.internal.lifecycle import io.sentry.IScope import io.sentry.PropagationContext +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_CONTEXT_KEY /** * Holds nav data (i.e., the screen name and nav context) staged for publication to a shared diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentDuplicateKeysTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentDuplicateKeysTest.kt deleted file mode 100644 index 9e7c0e82e09..00000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentDuplicateKeysTest.kt +++ /dev/null @@ -1,40 +0,0 @@ -package io.sentry.compose.navigation3 - -import com.google.common.truth.Truth.assertThat -import io.sentry.ILogger -import io.sentry.SentryLevel.WARNING -import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason -import io.sentry.compose.navigation3.internal.backstack.BackStackConverter -import org.junit.Test -import org.mockito.kotlin.eq -import org.mockito.kotlin.mock -import org.mockito.kotlin.verify - -class ArgumentDuplicateKeysTest { - - private val logger = mock() - - @Test - fun `stringified key collisions drop only that entry`() { - val sanitizer = BackStackConverter.ArgumentSanitizer(logger, 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) - verify(logger) - .log( - eq(WARNING), - eq( - "A Nav3 map key (String) stringifies to the same string as another key (Int). " + - "Dropping this entry's arguments.", - ), - ) - - 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/ArgumentNumberSerializationTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentNumberSerializationTest.kt deleted file mode 100644 index d4ed9e7262d..00000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ArgumentNumberSerializationTest.kt +++ /dev/null @@ -1,74 +0,0 @@ -package io.sentry.compose.navigation3 - -import com.google.common.truth.Truth.assertThat -import io.sentry.Breadcrumb -import io.sentry.JsonSerializer -import io.sentry.NoOpLogger -import io.sentry.SentryEvent -import io.sentry.SentryOptions -import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason -import io.sentry.compose.navigation3.internal.backstack.BackStackConverter -import io.sentry.compose.navigation3.internal.backstack.ForwardingBackStackEntryMapper -import java.io.StringWriter -import org.junit.Test - -class ArgumentNumberSerializationTest { - @Test - fun `non-finite numbers produce valid navigation argument 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(4_096 - 3), "n" to Double.NaN) - assertThat(sanitizer.sanitizeEntry(values).dropReason) - .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - - @Test - fun `non-finite navigation arguments keep the containing SentryEvent serializable`() { - val mapper = - BackStackEntryMapper { - SentryBackStackEntry("Home", mapOf("price" to Double.NaN)) - } - val converter = - BackStackConverter(ForwardingBackStackEntryMapper { mapper }, NoOpLogger.getInstance()) - val entry = - converter.convert(listOf(Any()), BackStackConverter.RetentionPolicy.KEEP_FIRST).single() - val event = - SentryEvent().apply { - contexts["navigation"] = mapOf("backstack" to listOf(entry.serialize())) - breadcrumbs = listOf(Breadcrumb().apply { data["to_arguments"] = entry.arguments }) - } - val json = StringWriter() - - JsonSerializer(SentryOptions()).serialize(event, json) - - assertThat(json.toString()).contains(""""entry_arguments":{"price":"NaN"}""") - assertThat(json.toString()).contains(""""to_arguments":{"price":"NaN"}""") - } -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt index 2ba320a31e8..4b82a1df66e 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -4,7 +4,7 @@ import com.google.common.truth.Truth.assertThat import java.io.File import org.junit.Test -/** Enforces the lifecycle package's dependency boundary. */ +/** Enforces internal dependency rules for `sentry-android-navigation3`. */ class PackageBoundariesTest { private val sources: List = @@ -15,19 +15,39 @@ class PackageBoundariesTest { .toList() @Test - fun `the lifecycle package has no imports from other Sentry navigation3 packages, Compose, or AndroidX Nav3`() { + fun `the lifecycle package imports only the contract package from other Sentry navigation3 packages`() { val lifecycleSources = sources.filter { it.packageName.isIn(LIFECYCLE) } val violations = lifecycleSources.importsMatching { - (it.isIn(ROOT) && !it.isIn(LIFECYCLE)) || - it.isIn("androidx.navigation3") || - (it.isIn("androidx") && "compose" in it.split('.')) + it.isIn(ROOT) && !it.isIn(LIFECYCLE) && !it.isIn(CONTRACT) } assertThat(lifecycleSources).isNotEmpty() assertThat(violations).isEmpty() } + @Test + fun `the lifecycle package has no imports from Compose or AndroidX Nav3`() { + val lifecycleSources = sources.filter { it.packageName.isIn(LIFECYCLE) } + + val violations = lifecycleSources.importsMatching { + it.isIn("androidx.navigation3") || (it.isIn("androidx") && "compose" in it.split('.')) + } + + assertThat(lifecycleSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `the contract package has no imports from other Sentry navigation3 packages`() { + val contractSources = sources.filter { it.packageName.isIn(CONTRACT) } + + val violations = contractSources.importsMatching { it.isIn(ROOT) && !it.isIn(CONTRACT) } + + assertThat(contractSources).isNotEmpty() + assertThat(violations).isEmpty() + } + // Check that the import reader finds the declarations the rules inspect. @Test @@ -89,6 +109,7 @@ class PackageBoundariesTest { const val SOURCE_ROOT = "src/main/kotlin" const val ROOT = "io.sentry.compose.navigation3" const val LIFECYCLE = "$ROOT.internal.lifecycle" + const val CONTRACT = "$ROOT.internal.contract" /** Whether this name is [packageName] or lies inside it. */ fun String.isIn(packageName: String): Boolean = diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt index a0ca7269f85..24c1b461d59 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt @@ -40,7 +40,7 @@ import io.sentry.android.core.ActivityLifecycleIntegration import io.sentry.android.core.BuildInfoProvider import io.sentry.android.core.SentryAndroidOptions import io.sentry.android.core.performance.AppStartMetrics -import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_CONTEXT_KEY +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_CONTEXT_KEY import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator import org.junit.After import org.junit.Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt index a07a1b41a69..15e30b16f49 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt @@ -7,6 +7,13 @@ import org.junit.Test class SentryNavOptionsTest { + @Test + fun `captures up to five back stack entries by default`() { + val options = SentryNavOptions() + + assertThat(options.maxCapturedBackStackEntries).isEqualTo(5) + } + @Test fun `accepts positive max captured backstack entries`() { val options = SentryNavOptions { maxCapturedBackStackEntries = 1 } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt index d9f0f76864a..d1b4a185615 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt @@ -3,15 +3,20 @@ package io.sentry.compose.navigation3.internal.backstack import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel.WARNING -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.ArgumentSanitizer import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.SanitizedArguments import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.WarningState +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import java.math.BigDecimal +import java.util.AbstractCollection import kotlin.test.assertFailsWith import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -23,6 +28,39 @@ class ArgumentSanitizerTest { override fun toString(): String = "opaque-value" } + private enum class PrivacyMode { + PUBLIC, + PRIVATE; + + override fun toString(): String = name.lowercase() + } + + private class UserId(private val value: String) { + override fun toString(): String = value + } + + private class OpaqueIterable : Iterable { + override fun iterator(): Iterator = listOf("a").iterator() + + override fun toString(): String = "opaque-iterable" + } + + private class OpaqueSequence : Sequence { + override fun iterator(): Iterator = listOf("a").iterator() + + override fun toString(): String = "opaque-sequence" + } + + private class CountingValue { + var toStringCalls = 0 + private set + + override fun toString(): String { + toStringCalls++ + return "counting-value" + } + } + private class ThrowingValue(val failure: IllegalStateException = IllegalStateException("boom")) { @Suppress("ExceptionRaisedInUnexpectedLocation") override fun toString(): String = throw failure } @@ -32,6 +70,28 @@ class ArgumentSanitizerTest { private val laterArguments = mapOf("id" to "123") + /** Sanitizes an entry that leaves only [remaining] values of the shared budget. */ + private fun spendValuesExcept(remaining: Int) { + // A list and its elements. + val spent = + sanitizer.sanitizeEntry(mapOf("v" to List(MAX_ARGUMENT_VALUES - remaining - 1) { 0 })) + check(spent.dropReason == null) + } + + /** Sanitizes an entry that leaves only [remaining] characters of the shared budget. */ + private fun spendCharactersExcept(remaining: Int) { + val spent = + sanitizer.sanitizeEntry(mapOf("" to "x".repeat(MAX_ARGUMENT_CHARACTERS - remaining))) + check(spent.dropReason == null) + } + + /** Returns a root map whose [leaf] is nested in [levels] more maps, i.e., at depth levels + 1. */ + private fun nested(levels: Int, leaf: Any?): Map { + var value: Any? = leaf + repeat(levels) { value = mapOf("n" to value) } + return mapOf("n" to value) + } + private companion object { private const val UNSUPPORTED_VALUE_WARNING = "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + @@ -57,8 +117,199 @@ class ArgumentSanitizerTest { assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), dropReason = null)) } + @Test + fun `sanitizeEntry() - keeps arguments in the order of the map`() { + val arguments = linkedMapOf("b" to 1, "a" to 2, "c" to 3) + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized.values.keys).containsExactly("b", "a", "c").inOrder() + } + + @Test + fun `sanitizeEntry() - records map keys by toString()`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", UserId("u") to "b"))) + + assertThat(sanitized.values).isEqualTo(mapOf("nested" to mapOf("1" to "a", "u" to "b"))) + } + + // Containers + + @Test + fun `sanitizeEntry() - records collections and object arrays as lists`() { + val sanitized = + sanitizer.sanitizeEntry( + mapOf("set" to linkedSetOf("a", "b"), "array" to arrayOf(1, "x", null)), + ) + + assertThat(sanitized.values) + .isEqualTo(mapOf("set" to listOf("a", "b"), "array" to listOf(1, "x", null))) + } + + @Test + fun `sanitizeEntry() - records primitive arrays as lists of their elements`() { + val sanitized = + sanitizer.sanitizeEntry( + mapOf( + "booleans" to booleanArrayOf(true), + "bytes" to byteArrayOf(1), + "shorts" to shortArrayOf(2), + "ints" to intArrayOf(3), + "longs" to longArrayOf(4), + "floats" to floatArrayOf(5f), + "doubles" to doubleArrayOf(6.0), + "chars" to charArrayOf('c'), + ), + ) + + assertThat(sanitized.values) + .isEqualTo( + mapOf( + "booleans" to listOf(true), + "bytes" to listOf(1.toByte()), + "shorts" to listOf(2.toShort()), + "ints" to listOf(3), + "longs" to listOf(4L), + "floats" to listOf(5f), + "doubles" to listOf(6.0), + "chars" to listOf("c"), + ), + ) + } + + @Test + fun `sanitizeEntry() - records a map inside a list`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("items" to listOf(mapOf(1 to "a")))) + + assertThat(sanitized.values).isEqualTo(mapOf("items" to listOf(mapOf("1" to "a")))) + } + + @Test + fun `sanitizeEntry() - doesn't read the size of a collection`() { + val values = + object : AbstractCollection() { + var wasSizeRead = false + + override val size: Int + get() { + wasSizeRead = true + return Int.MAX_VALUE + } + + override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() + } + + val sanitized = sanitizer.sanitizeEntry(mapOf("values" to values)) + + assertThat(sanitized.values).isEqualTo(mapOf("values" to listOf(1, 2))) + assertThat(values.wasSizeRead).isFalse() + } + + @Test + fun `sanitizeEntry() - records the same container in sibling positions twice`() { + val shared = listOf(1) + + val sanitized = sanitizer.sanitizeEntry(mapOf("a" to shared, "b" to shared)) + + assertThat(sanitized.values).isEqualTo(mapOf("a" to listOf(1), "b" to listOf(1))) + } + + @Test + fun `sanitizeEntry() - records the same key in a nested map and its parent`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("id" to 1, "nested" to mapOf("id" to 2))) + + assertThat(sanitized.values).isEqualTo(mapOf("id" to 1, "nested" to mapOf("id" to 2))) + } + + // Scalars + + @Test + fun `sanitizeEntry() - records null, Boolean, and finite Number values unchanged`() { + val bigDecimal = BigDecimal("1.25") + + val sanitized = + sanitizer.sanitizeEntry(mapOf("null" to null, "boolean" to true, "big" to bigDecimal)) + + assertThat(sanitized.values) + .isEqualTo(mapOf("null" to null, "boolean" to true, "big" to bigDecimal)) + } + + @Test + fun `sanitizeEntry() - records CharSequence and Char values as Strings`() { + val sanitized = + sanitizer.sanitizeEntry(mapOf("builder" to StringBuilder("text"), "char" to 'c')) + + assertThat(sanitized.values).isEqualTo(mapOf("builder" to "text", "char" to "c")) + } + + @Test + fun `sanitizeEntry() - records non-finite Double and Float values as Strings`() { + val sanitized = + sanitizer.sanitizeEntry( + mapOf( + "nan" to Double.NaN, + "infinity" to Double.POSITIVE_INFINITY, + "negativeInfinity" to Float.NEGATIVE_INFINITY, + ), + ) + + assertThat(sanitized.values) + .isEqualTo(mapOf("nan" to "NaN", "infinity" to "Infinity", "negativeInfinity" to "-Infinity")) + } + + @Test + fun `sanitizeEntry() - records enums by name rather than toString()`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("mode" to PrivacyMode.PRIVATE)) + + assertThat(sanitized.values).isEqualTo(mapOf("mode" to "PRIVATE")) + } + // Unsupported values + @Test + fun `sanitizeEntry() - records an unsupported value by toString()`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) + + assertThat(sanitized.values).isEqualTo(mapOf("opaque" to "opaque-value")) + } + + @Test + fun `sanitizeEntry() - records an Iterable that isn't a Collection and a Sequence as unsupported values`() { + val sanitized = + sanitizer.sanitizeEntry(mapOf("iterable" to OpaqueIterable(), "sequence" to OpaqueSequence())) + + assertThat(sanitized.values) + .isEqualTo(mapOf("iterable" to "opaque-iterable", "sequence" to "opaque-sequence")) + } + + @Test + fun `sanitizeEntry() - doesn't log supported values as unsupported`() { + sanitizer.sanitizeEntry( + mapOf( + "string" to "s", + "number" to 1, + "enum" to PrivacyMode.PUBLIC, + "list" to listOf(1), + "array" to intArrayOf(1), + "map" to mapOf("k" to "v"), + ), + ) + + verify(logger, never()).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), any()) + } + + @Test + fun `sanitizeEntry() - logs an unsupported value of an anonymous type with a null type name`() { + val anonymous = + object { + override fun toString(): String = "anonymous" + } + + sanitizer.sanitizeEntry(mapOf("anonymous" to anonymous)) + + verify(logger).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), isNull()) + } + @Test fun `sanitizeEntry() - logs the unsupported value warning with the value type`() { sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) @@ -95,6 +346,34 @@ class ArgumentSanitizerTest { verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) } + @Test + fun `sanitizeEntry() - drops arguments for invalid structure and logs the structure warning`() { + val cyclic = mutableListOf() + cyclic.add(cyclic) + + val sanitized = sanitizer.sanitizeEntry(mapOf("cyclic" to cyclic)) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING)) + } + + @Test + fun `sanitizeEntry() - drops arguments for a duplicate map key and logs the warning naming the key types`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", "1" to "b"))) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.DUPLICATE_KEY)) + verify(logger) + .log( + eq(WARNING), + eq( + "A Nav3 map key (String) stringifies to the same string as another key (Int). " + + "Dropping this entry's arguments.", + ), + ) + } + @Test fun `an entry whose own map contains itself is dropped without writing its contents again`() { // The entry's own map is the cycle check's root, so "self" is rejected as soon as it begins, @@ -114,6 +393,250 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(rest)) } + @Test + fun `sanitizeEntry() - describes a duplicate key by the types of the colliding keys rather than their values`() { + sanitizer.sanitizeEntry( + mapOf("nested" to linkedMapOf(UserId("ada@example.com") to "a", "ada@example.com" to "b")), + ) + + verify(logger) + .log( + eq(WARNING), + eq( + "A Nav3 map key (String) stringifies to the same string as another key (UserId). " + + "Dropping this entry's arguments.", + ), + ) + } + + @Test + fun `sanitizeEntry() - describes a null or anonymous map key that collides with another key as null`() { + val anonymous = + object { + override fun toString(): String = "id" + } + + sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf("null" to "a", null to "b"))) + sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf("id" to "a", anonymous to "b"))) + + verify(logger, times(2)) + .log( + eq(WARNING), + eq( + "A Nav3 map key (null) stringifies to the same string as another key (String). " + + "Dropping this entry's arguments.", + ), + ) + } + + @Test + fun `sanitizeEntry() - drops arguments for a duplicate key whose value is a container`() { + val withMap = + sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to mapOf("k" to "v")))) + val withList = + sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to listOf(1)))) + + assertThat(withMap.dropReason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + assertThat(withList.dropReason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `sanitizeEntry() - drops arguments for a duplicate key, not the value limit, with no values left`() { + // Enough for the nested map and "a" only. + spendValuesExcept(remaining = 2) + + val sanitized = sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to "b"))) + + assertThat(sanitized.dropReason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `sanitizeEntry() - doesn't spend a value for a duplicate key`() { + // Enough for the nested map, "a", and the later entry's value. + spendValuesExcept(remaining = 3) + sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to "b"))) + + val later = sanitizer.sanitizeEntry(mapOf("one" to 1)) + + assertThat(later).isEqualTo(SanitizedArguments(mapOf("one" to 1))) + } + + @Test + fun `sanitizeEntry() - doesn't convert a value under a duplicate key`() { + val value = CountingValue() + + sanitizer.sanitizeEntry(mapOf("nested" to linkedMapOf(1 to "a", "1" to value))) + + assertThat(value.toStringCalls).isEqualTo(0) + } + + // Depth + + @Test + fun `sanitizeEntry() - records a scalar and a container at the maximum depth`() { + val scalarAtMax = nested(MAX_ARGUMENT_DEPTH - 1, leaf = 1) + val containerAtMax = nested(MAX_ARGUMENT_DEPTH - 1, leaf = emptyList()) + + val scalar = sanitizer.sanitizeEntry(scalarAtMax) + val container = sanitizer.sanitizeEntry(containerAtMax) + + assertThat(scalar).isEqualTo(SanitizedArguments(scalarAtMax)) + assertThat(container).isEqualTo(SanitizedArguments(containerAtMax)) + } + + @Test + fun `sanitizeEntry() - drops arguments for invalid structure past the maximum depth`() { + val sanitized = sanitizer.sanitizeEntry(nested(MAX_ARGUMENT_DEPTH, leaf = 1)) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + } + + @Test + fun `sanitizeEntry() - doesn't convert a value past the maximum depth`() { + val value = CountingValue() + + sanitizer.sanitizeEntry(nested(MAX_ARGUMENT_DEPTH, leaf = value)) + + assertThat(value.toStringCalls).isEqualTo(0) + } + + @Test + fun `sanitizeEntry() - counts depth only through containers a value is nested in`() { + // Each sibling reaches the maximum depth on its own, which together they'd exceed. + val arguments = + mapOf( + "first" to nested(MAX_ARGUMENT_DEPTH - 2, leaf = 1), + "second" to nested(MAX_ARGUMENT_DEPTH - 2, leaf = 2), + ) + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized).isEqualTo(SanitizedArguments(arguments)) + } + + // Cycles + + @Test + fun `sanitizeEntry() - drops arguments for invalid structure when a map contains itself`() { + val cyclic = mutableMapOf() + cyclic["self"] = cyclic + + val sanitized = sanitizer.sanitizeEntry(mapOf("cyclic" to cyclic)) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + } + + @Test + fun `sanitizeEntry() - drops arguments for invalid structure when an array contains itself`() { + val cyclic = arrayOfNulls(1) + cyclic[0] = cyclic + + val sanitized = sanitizer.sanitizeEntry(mapOf("cyclic" to cyclic)) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + } + + // Value and character budgets + + @Test + fun `sanitizeEntry() - spends one value per scalar and container but none for the root map or keys`() { + // "list" and its 2 elements, and "scalar": 4 values. + sanitizer.sanitizeEntry(mapOf("list" to listOf(1, 2), "scalar" to 3)) + val rest = mapOf("values" to List(MAX_ARGUMENT_VALUES - 4 - 1) { it }) + + val later = sanitizer.sanitizeEntry(rest) + + assertThat(later).isEqualTo(SanitizedArguments(rest)) + } + + @Test + fun `sanitizeEntry() - doesn't convert a value over the value budget`() { + spendValuesExcept(remaining = 0) + val value = CountingValue() + + // A fresh sanitizer would record it, so the shared budget is what stops it. + val sanitized = sanitizer.sanitizeEntry(mapOf("counting" to value)) + + assertThat(sanitized.dropReason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(value.toStringCalls).isEqualTo(0) + verify(logger, never()).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), any()) + } + + @Test + fun `sanitizeEntry() - records text exactly as long as the remaining characters`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("" to "x".repeat(MAX_ARGUMENT_CHARACTERS))) + + assertThat(sanitized.dropReason).isNull() + } + + @Test + fun `sanitizeEntry() - spends the characters of keys and of every text value`() { + // The values spend "cd" + "NaN" + "PUBLIC" + "e" + "opaque-value" = 2 + 3 + 6 + 1 + 12 = 24 + // characters, and the keys 2 + 0 + 1 + 2 + 3 = 8, for 32 in all. + sanitizer.sanitizeEntry( + linkedMapOf( + "ab" to "cd", + "" to Double.NaN, + " " to PrivacyMode.PUBLIC, + " " to 'e', + " " to OpaqueValue(), + ), + ) + val rest = mapOf("" to "x".repeat(MAX_ARGUMENT_CHARACTERS - 32)) + + val later = sanitizer.sanitizeEntry(rest) + val overflowing = sanitizer.sanitizeEntry(mapOf("" to "y")) + + assertThat(later).isEqualTo(SanitizedArguments(rest)) + assertThat(overflowing.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `sanitizeEntry() - doesn't spend characters for finite numbers, Booleans, or null`() { + sanitizer.sanitizeEntry(mapOf("" to 12345, " " to true, " " to null)) + // The keys above spend 0 + 1 + 2 = 3 characters. + val rest = mapOf("" to "x".repeat(MAX_ARGUMENT_CHARACTERS - 3)) + + val later = sanitizer.sanitizeEntry(rest) + val overflowing = sanitizer.sanitizeEntry(mapOf("" to "y")) + + assertThat(later).isEqualTo(SanitizedArguments(rest)) + assertThat(overflowing.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `sanitizeEntry() - doesn't convert text whose reported length doesn't fit`() { + spendCharactersExcept(remaining = 1) + val text = CountingText(length = 2, text = "ab") + + val sanitized = sanitizer.sanitizeEntry(mapOf("" to text)) + + assertThat(sanitized.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(text.toStringCalls).isEqualTo(0) + } + + @Test + fun `sanitizeEntry() - drops text longer than its reported length when its text doesn't fit`() { + spendCharactersExcept(remaining = 1) + + val sanitized = sanitizer.sanitizeEntry(mapOf("" to CountingText(length = 1, text = "ab"))) + + assertThat(sanitized.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `sanitizeEntry() - spends the characters of text rather than its reported length`() { + spendCharactersExcept(remaining = 2) + sanitizer.sanitizeEntry(mapOf("" to CountingText(length = 0, text = "ab"))) + + val later = sanitizer.sanitizeEntry(mapOf("" to "c")) + + assertThat(later.dropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + // Budgets shared across entries @Test @@ -153,7 +676,7 @@ class ArgumentSanitizerTest { } @Test - fun `sanitizeEntry() - logs the structure warning with the exception when a value throws`() { + fun `sanitizeEntry() - logs a warning with the exception when a value throws`() { val throwing = ThrowingValue() sanitizer.sanitizeEntry(mapOf("throwing" to throwing)) @@ -237,3 +760,22 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) } } + +/** + * Host app text that reports [length], which may differ from [text]'s, and counts its conversions + * to a `String` in [toStringCalls]. + */ +internal class CountingText(override val length: Int, private val text: String) : CharSequence { + var toStringCalls = 0 + private set + + override fun get(index: Int): Char = text[index] + + override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = + text.subSequence(startIndex, endIndex) + + override fun toString(): String { + toStringCalls++ + return text + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index d07f3733118..99ab485ca97 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -9,11 +9,10 @@ import io.sentry.SentryLevel.WARNING import io.sentry.SentryOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy -import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import java.io.StringWriter -import java.util.AbstractCollection import kotlin.test.assertFailsWith import org.junit.Test import org.mockito.kotlin.any @@ -41,39 +40,15 @@ class BackStackConverterTest { private val logger = mock() - private companion object { - const val BLANK_NAME_WARNING = - "Nav3 backStackEntryMapper returned a blank name. Using /unknown." - const val MAPPER_FAILURE_WARNING = - "Nav3 backStackEntryMapper threw. Using /unknown without arguments." - const val UNSUPPORTED_VALUE_WARNING = - "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + - "collections, or arrays from BackStackEntryMapper." - } - private val defaultEntryMapper = BackStackEntryMapper { entry -> SentryBackStackEntry(entry::class.simpleName ?: "") } - private fun getSut( - entryMapper: BackStackEntryMapper = defaultEntryMapper, - ): BackStackConverter = - BackStackConverter( - entryMapper = ForwardingBackStackEntryMapper { entryMapper }, - logger = logger, - ) - - private fun entryInfo(entry: Any, arguments: Map? = null): SentryBackStackEntry = - SentryBackStackEntry(entry::class.simpleName ?: "", arguments) - - private fun BackStackConverter.convert(entry: Any): NormalizedSentryBackStackEntry = - convert(listOf(entry), RetentionPolicy.KEEP_FIRST).single() - @Test - fun `convert returns normalized back stack entries`() { - val sut = - getSut( + fun `convert() - returns normalized back stack entries`() { + val converter = + newConverter( entryMapper = { entry -> entryInfo( entry, @@ -88,7 +63,7 @@ class BackStackConverterTest { ) val routes = - sut.convert( + converter.convert( listOf( SettingsScreen(section = "privacy"), ProfileScreen(userId = "123", marketingId = "987"), @@ -113,11 +88,11 @@ class BackStackConverterTest { } @Test - fun `convert with KEEP_FIRST returns entries in back stack order`() { - val sut = getSut() + fun `convert() - with KEEP_FIRST returns entries in back stack order`() { + val converter = newConverter() val routes = - sut.convert( + converter.convert( listOf(SettingsScreen("privacy"), ProfileScreen("123"), HomeScreen()), RetentionPolicy.KEEP_FIRST, ) @@ -132,11 +107,11 @@ class BackStackConverterTest { } @Test - fun `convert with KEEP_LAST returns entries in back stack order`() { - val sut = getSut() + fun `convert() - with KEEP_LAST returns entries in back stack order`() { + val converter = newConverter() val routes = - sut.convert( + converter.convert( listOf(SettingsScreen("privacy"), ProfileScreen("123"), HomeScreen()), RetentionPolicy.KEEP_LAST, ) @@ -151,19 +126,173 @@ class BackStackConverterTest { } @Test - fun `convert returns an empty list if provided back stack is empty`() { - val sut = getSut() + fun `convert() - returns an empty list if provided back stack is empty`() { + val converter = newConverter() + + assertThat(converter.convert(emptyList(), RetentionPolicy.KEEP_FIRST)).isEmpty() + } + + @Test + fun `convert() - trims mapper name`() { + val converter = newConverter(entryMapper = { SentryBackStackEntry(name = " /profile ") }) - assertThat(sut.convert(emptyList(), RetentionPolicy.KEEP_FIRST)).isEmpty() + assertThat(converter.convert(ProfileScreen("123"))) + .isEqualTo(NormalizedSentryBackStackEntry(name = "/profile")) + } + + @Test + fun `convert() - adds leading slash to mapper name if absent`() { + val converter = newConverter(entryMapper = { SentryBackStackEntry(name = "profile") }) + + assertThat(converter.convert(ProfileScreen("123"))) + .isEqualTo(NormalizedSentryBackStackEntry(name = "/profile")) } @Test - fun `convert with KEEP_FIRST preserves arguments nearest index zero when sanitization budget is exceeded`() { + fun `convert() - preserves leading slash in mapper name if already present`() { + val converter = newConverter(entryMapper = { SentryBackStackEntry(name = "/profile") }) + + assertThat(converter.convert(ProfileScreen("123"))) + .isEqualTo(NormalizedSentryBackStackEntry(name = "/profile")) + } + + @Test + fun `convert() - returns unknown name with arguments if mapper name is blank`() { + val converter = + newConverter(entryMapper = { SentryBackStackEntry(" ", mapOf("userId" to "123")) }) + + assertThat(converter.convert(HomeScreen())) + .isEqualTo( + NormalizedSentryBackStackEntry( + name = "/unknown", + arguments = mapOf("userId" to "123"), + ), + ) + verify(logger) + .log( + eq(WARNING), + eq(BLANK_NAME_WARNING), + ) + } + + @Test + fun `convert() - returns the reason arguments were dropped if mapper name is blank`() { + val converter = + newConverter( + entryMapper = { SentryBackStackEntry(" ", mapOf("values" to List(999) { it })) }, + ) + + assertThat(converter.convert(HomeScreen())) + .isEqualTo( + NormalizedSentryBackStackEntry( + name = "/unknown", + argumentDropReason = ArgumentDropReason.MAX_COUNT, + ), + ) + } + + @Test + fun `convert() - logs the blank name warning once per back stack update`() { + val converter = newConverter(entryMapper = { SentryBackStackEntry(" ") }) + + converter.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + + verify(logger, times(1)).log(eq(WARNING), eq(BLANK_NAME_WARNING)) + } + + @Test + fun `convert() - logs the blank name warning again in a later back stack update`() { + val converter = newConverter(entryMapper = { SentryBackStackEntry(" ") }) + converter.convert(HomeScreen()) + clearInvocations(logger) + + converter.convert(HomeScreen()) + + verify(logger, times(1)).log(eq(WARNING), eq(BLANK_NAME_WARNING)) + } + + @Test + fun `convert() - returns unknown name without arguments if mapper returns null`() { + val converter = newConverter(entryMapper = { null }) + + assertThat(converter.convert(HomeScreen())) + .isEqualTo(NormalizedSentryBackStackEntry(UNKNOWN_ENTRY_NAME)) + } + + @Test + fun `convert() - returns unknown name with the mapping failed drop reason if mapper throws`() { + val converter = newConverter(entryMapper = { error("boom") }) + + assertThat(converter.convert(HomeScreen())) + .isEqualTo( + NormalizedSentryBackStackEntry( + UNKNOWN_ENTRY_NAME, + argumentDropReason = ArgumentDropReason.MAPPING_FAILED, + ), + ) + verify(logger) + .log( + eq(WARNING), + eq(MAPPER_FAILURE_WARNING), + any(), + ) + } + + @Test + fun `convert() - logs the mapper failure warning once per back stack update`() { + val converter = newConverter(entryMapper = { error("boom") }) + + converter.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + + verify(logger, times(1)).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + } + + @Test + fun `convert() - logs the mapper failure warning again in a later back stack update`() { + val converter = newConverter(entryMapper = { error("boom") }) + converter.convert(HomeScreen()) + clearInvocations(logger) + + converter.convert(HomeScreen()) + + verify(logger, times(1)).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + } + + @Test + fun `convert() - rethrows fatal errors thrown by the mapper`() { + val converter = newConverter(entryMapper = { throw StackOverflowError("fatal") }) + + assertFailsWith { converter.convert(HomeScreen()) } + verify(logger, never()).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + } + + @Test + fun `convert() - returns the mapper's arguments sanitized`() { + val converter = + newConverter( + entryMapper = { entry -> + entryInfo(entry, mapOf("mode" to PrivacyMode.PRIVATE, "ids" to intArrayOf(1, 2))) + }, + ) + + assertThat(converter.convert(HomeScreen()).arguments) + .isEqualTo(mapOf("mode" to "PRIVATE", "ids" to listOf(1, 2))) + } + + @Test + fun `convert() - returns empty arguments if mapper omits them`() { + val converter = newConverter() + + assertThat(converter.convert(HomeScreen()).arguments).isEmpty() + } + + @Test + fun `convert() - with KEEP_FIRST preserves arguments nearest index zero when sanitization budget is exceeded`() { val first = SettingsScreen("privacy") val middle = ProfileScreen("123") val last = HomeScreen() - val sut = - getSut( + val converter = + newConverter( entryMapper = { key -> entryInfo( key, @@ -177,7 +306,7 @@ class BackStackConverterTest { }, ) - val routes = sut.convert(listOf(first, middle, last), RetentionPolicy.KEEP_FIRST) + val routes = converter.convert(listOf(first, middle, last), RetentionPolicy.KEEP_FIRST) assertThat(routes) .containsExactly( @@ -195,12 +324,12 @@ class BackStackConverterTest { } @Test - fun `convert with KEEP_LAST preserves arguments nearest lastIndex when sanitization budget is exceeded`() { + fun `convert() - with KEEP_LAST preserves arguments nearest lastIndex when sanitization budget is exceeded`() { val first = HomeScreen() val middle = ProfileScreen("123") val last = SettingsScreen("privacy") - val sut = - getSut( + val converter = + newConverter( entryMapper = { key -> entryInfo( key, @@ -214,7 +343,7 @@ class BackStackConverterTest { }, ) - val routes = sut.convert(listOf(first, middle, last), RetentionPolicy.KEEP_LAST) + val routes = converter.convert(listOf(first, middle, last), RetentionPolicy.KEEP_LAST) assertThat(routes) .containsExactly( @@ -232,12 +361,12 @@ class BackStackConverterTest { } @Test - fun `convert with KEEP_FIRST treats entries as distinct by position even if structurally equal`() { + fun `convert() - with KEEP_FIRST treats entries as distinct by position even if structurally equal`() { val first = ProductScreen("sku-1") val middle = ProfileScreen("123") val last = ProductScreen("sku-1") - val sut = - getSut( + val converter = + newConverter( entryMapper = { entry -> entryInfo( entry, @@ -250,7 +379,7 @@ class BackStackConverterTest { }, ) - val routes = sut.convert(listOf(first, middle, last), RetentionPolicy.KEEP_FIRST) + val routes = converter.convert(listOf(first, middle, last), RetentionPolicy.KEEP_FIRST) assertThat(routes) .containsExactly( @@ -268,12 +397,12 @@ class BackStackConverterTest { } @Test - fun `convert with KEEP_LAST treats entries as distinct by position even if structurally equal`() { + fun `convert() - with KEEP_LAST treats entries as distinct by position even if structurally equal`() { val first = ProductScreen("sku-1") val middle = ProfileScreen("123") val last = ProductScreen("sku-1") - val sut = - getSut( + val converter = + newConverter( entryMapper = { entry -> entryInfo( entry, @@ -286,7 +415,7 @@ class BackStackConverterTest { }, ) - val routes = sut.convert(listOf(first, middle, last), RetentionPolicy.KEEP_LAST) + val routes = converter.convert(listOf(first, middle, last), RetentionPolicy.KEEP_LAST) assertThat(routes) .containsExactly( @@ -304,227 +433,27 @@ class BackStackConverterTest { } @Test - fun `convert trims mapper name`() { - val sut = getSut(entryMapper = { SentryBackStackEntry(name = " /profile ") }) - - assertThat(sut.convert(ProfileScreen("123"))) - .isEqualTo(NormalizedSentryBackStackEntry(name = "/profile")) - } - - @Test - fun `convert adds leading slash to mapper name if absent`() { - val sut = getSut(entryMapper = { SentryBackStackEntry(name = "profile") }) - - assertThat(sut.convert(ProfileScreen("123"))) - .isEqualTo(NormalizedSentryBackStackEntry(name = "/profile")) - } - - @Test - fun `convert preserves leading slash in mapper name if already present`() { - val sut = getSut(entryMapper = { SentryBackStackEntry(name = "/profile") }) - - assertThat(sut.convert(ProfileScreen("123"))) - .isEqualTo(NormalizedSentryBackStackEntry(name = "/profile")) - } - - @Test - fun `convert returns unknown name if mapper name is blank`() { - val sut = getSut(entryMapper = { SentryBackStackEntry(" ", mapOf("userId" to "123")) }) - - assertThat(sut.convert(HomeScreen())) - .isEqualTo( - NormalizedSentryBackStackEntry(name = "/unknown", arguments = mapOf("userId" to "123")), - ) - verify(logger) - .log( - eq(WARNING), - eq(BLANK_NAME_WARNING), - ) - } - - @Test - fun `convert logs the blank name warning once per back stack update`() { - val sut = getSut(entryMapper = { SentryBackStackEntry(" ") }) - - sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) - - verify(logger, times(1)).log(eq(WARNING), eq(BLANK_NAME_WARNING)) - } - - @Test - fun `convert returns unknown name without arguments if mapper returns null`() { - val sut = getSut(entryMapper = { null }) - - assertThat(sut.convert(HomeScreen())) - .isEqualTo(NormalizedSentryBackStackEntry(UNKNOWN_ENTRY_NAME)) - } - - @Test - fun `convert returns unknown name without arguments if mapper throws`() { - val sut = getSut(entryMapper = { error("boom") }) - - assertThat(sut.convert(HomeScreen())) - .isEqualTo( - NormalizedSentryBackStackEntry( - UNKNOWN_ENTRY_NAME, - argumentDropReason = ArgumentDropReason.MAPPING_FAILED, - ), - ) - verify(logger) - .log( - eq(WARNING), - eq(MAPPER_FAILURE_WARNING), - any(), - ) - } - - @Test - fun `convert logs the mapper failure warning once per back stack update`() { - val sut = getSut(entryMapper = { error("boom") }) - - sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) - - verify(logger, times(1)).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) - } - - @Test - fun `convert rethrows fatal errors thrown by the mapper`() { - val sut = getSut(entryMapper = { throw StackOverflowError("fatal") }) + fun `convert() - starts each back stack update with a fresh argument budget`() { + val converter = + newConverter(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(150) { it })) }) - assertFailsWith { sut.convert(HomeScreen()) } - verify(logger, never()).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) - } + converter.convert(HomeScreen()) + val entry = converter.convert(HomeScreen()) - @Test - fun `convert returns arguments in proper serializable form`() { - val text = StringBuilder("hello") - val sut = - getSut( - entryMapper = { entry -> - entryInfo( - entry, - mapOf( - "str" to "hello", - "charSequence" to text, - "char" to 'x', - "num" to 42, - "bool" to true, - "enum" to PrivacyMode.PRIVATE, - "nil" to null, - "nested" to mapOf("inner" to "value"), - "tags" to listOf("a", "b", "c"), - "array" to arrayOf("a", 1, false, PrivacyMode.PUBLIC, 'z'), - "ints" to intArrayOf(1, 2, 3), - "chars" to charArrayOf('a', 'b'), - "bytes" to byteArrayOf(4, 5), - ), - ) - }, - ) - - assertThat(sut.convert(HomeScreen()).arguments) - .isEqualTo( - mapOf( - "str" to "hello", - "charSequence" to "hello", - "char" to "x", - "num" to 42, - "bool" to true, - "enum" to "PRIVATE", - "nil" to null, - "nested" to mapOf("inner" to "value"), - "tags" to listOf("a", "b", "c"), - "array" to listOf("a", 1, false, "PUBLIC", "z"), - "ints" to listOf(1, 2, 3), - "chars" to listOf("a", "b"), - "bytes" to listOf(4.toByte(), 5.toByte()), - ), - ) - } - - @Test - fun `convert sanitizes arguments with nested supported containers recursively`() { - val sut = - getSut( - entryMapper = { entry -> - entryInfo( - entry, - mapOf( - "nested" to - mapOf( - "items" to - arrayOf( - StringBuilder("x"), - listOf('y', PrivacyMode.PRIVATE), - booleanArrayOf(true, false), - charArrayOf('q'), - ), - ), - ), - ) - }, - ) - - assertThat(sut.convert(HomeScreen()).arguments) - .isEqualTo( - mapOf( - "nested" to - mapOf("items" to listOf("x", listOf("y", "PRIVATE"), listOf(true, false), listOf("q"))), - ), - ) - } - - @Test - fun `convert coerces arguments with unsupported values to strings`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" - } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("bad" to OpaqueValue())) }) - - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("bad" to "opaque-value")) - } - - @Test - fun `convert logs an unsupported value warning once per back stack update`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" - } - - val sut = - getSut( - entryMapper = { entry -> - entryInfo( - entry, - when (entry) { - is HomeScreen -> mapOf("bad" to OpaqueValue()) - is ProfileScreen -> mapOf("alsoBad" to OpaqueValue()) - else -> emptyMap() - }, - ) - }, - ) - - sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) - - verify(logger, times(1)) - .log( - eq(WARNING), - eq(UNSUPPORTED_VALUE_WARNING), - eq("OpaqueValue"), - ) + assertThat(entry.arguments).isEqualTo(mapOf("values" to List(150) { it })) + assertThat(entry.argumentDropReason).isNull() } @Test - fun `convert hides state reads during argument sanitization from snapshot observation`() { + fun `convert() - hides state reads during argument sanitization from snapshot observation`() { val arguments = mutableStateMapOf("state" to "value") - val sut = getSut(entryMapper = { entry -> entryInfo(entry, arguments) }) + val converter = newConverter(entryMapper = { entry -> entryInfo(entry, arguments) }) val observedReads = mutableListOf() val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) val converted = try { - snapshot.enter { sut.convert(HomeScreen()) } + snapshot.enter { converter.convert(HomeScreen()) } } finally { snapshot.dispose() } @@ -534,17 +463,18 @@ class BackStackConverterTest { } @Test - fun `convert logs the unsupported value warning again in a later back stack update`() { + fun `convert() - logs the unsupported value warning again in a later back stack update`() { class OpaqueValue { override fun toString(): String = "opaque-value" } - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("bad" to OpaqueValue())) }) + val converter = + newConverter(entryMapper = { entry -> entryInfo(entry, mapOf("bad" to OpaqueValue())) }) - sut.convert(HomeScreen()) + converter.convert(HomeScreen()) clearInvocations(logger) - sut.convert(HomeScreen()) + converter.convert(HomeScreen()) verify(logger, times(1)) .log( @@ -555,141 +485,9 @@ class BackStackConverterTest { } @Test - fun `convert returns empty arguments for cyclic structures`() { - val cyclic = mutableMapOf() - cyclic["self"] = cyclic - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("cyclic" to cyclic)) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert returns empty arguments for deeply nested structures`() { - var nested: Any? = "value" - repeat(25) { nested = listOf(nested) } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("nested" to nested)) }) - - val entry = sut.convert(ProfileScreen("123")) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert drops oversized arguments`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(1_001) { it })) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.MAX_COUNT) - } - - @Test - fun `convert drops arguments when character budget is exceeded`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to "x".repeat(4_097))) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - - @Test - fun `convert starts each back stack update with a fresh argument budget`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(150) { it })) }) - - sut.convert(HomeScreen()) - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEqualTo(mapOf("values" to List(150) { it })) - assertThat(entry.argumentDropReason).isNull() - } - - @Test - fun `convert reports sanitization failures`() { - class ThrowingValue { - override fun toString(): String = error("boom") - } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to ThrowingValue())) }) - - val converted = sut.convert(HomeScreen()) - - assertThat(converted.arguments).isEmpty() - assertThat(converted.argumentDropReason).isEqualTo(ArgumentDropReason.SANITIZATION_FAILED) - } - - @Test - fun `arguments do not use caller collection size for allocation`() { - val values = - object : AbstractCollection() { - var wasSizeRead = false - - override val size: Int - get() { - wasSizeRead = true - return 2 - } - - override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() - } - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to values)) }) - - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("values" to listOf(1, 2))) - assertThat(values.wasSizeRead).isFalse() - } - - @Test - fun `omitted arguments normalize to an empty map`() { - val sut = getSut() - - assertThat(sut.convert(HomeScreen()).arguments).isEmpty() - } - - @Test - fun `serialize returns entries in serialized form`() { - val sut = - getSut( - entryMapper = { entry -> - entryInfo( - entry, - when (entry) { - is HomeScreen -> mapOf("tab" to entry.id) - is ProfileScreen -> emptyMap() - is SettingsScreen -> mapOf("section" to entry.section) - else -> emptyMap() - }, - ) - }, - ) - - val routes = - sut.convert( - listOf(SettingsScreen("privacy"), ProfileScreen("123")), - RetentionPolicy.KEEP_FIRST, - ) - - assertThat(routes.map(NormalizedSentryBackStackEntry::serialize)) - .containsExactly( - mapOf("entry" to "/SettingsScreen", "entry_arguments" to mapOf("section" to "privacy")), - mapOf("entry" to "/ProfileScreen"), - ) - .inOrder() - } - - @Test - fun `converted entries with non-finite number arguments serialize to valid JSON through Sentry's JSON serializer`() { - val sut = - getSut( + fun `serialization integration - non-finite number arguments serialize to valid JSON through JsonSerializer`() { + val converter = + newConverter( entryMapper = { entry -> entryInfo( entry, @@ -700,7 +498,7 @@ class BackStackConverterTest { ) }, ) - val serializedEntry = sut.convert(HomeScreen()).serialize() + val serializedEntry = converter.convert(HomeScreen()).serialize() val json = StringWriter() JsonSerializer(SentryOptions()).serialize(serializedEntry, json) @@ -711,20 +509,27 @@ class BackStackConverterTest { ) } - @Test - fun `serialize includes the reason arguments were dropped`() { - val entry = - NormalizedSentryBackStackEntry( - name = "/HomeScreen", - argumentDropReason = ArgumentDropReason.MAX_COUNT, - ) + private fun newConverter( + entryMapper: BackStackEntryMapper = defaultEntryMapper, + ): BackStackConverter = + BackStackConverter( + entryMapper = ForwardingBackStackEntryMapper { entryMapper }, + logger = logger, + ) - assertThat(entry.serialize()) - .isEqualTo( - mapOf( - "entry" to "/HomeScreen", - "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "max_argument_count_exceeded"), - ), - ) + private fun entryInfo(entry: Any, arguments: Map? = null): SentryBackStackEntry = + SentryBackStackEntry(entry::class.simpleName ?: "", arguments) + + private fun BackStackConverter.convert(entry: Any): NormalizedSentryBackStackEntry = + convert(listOf(entry), RetentionPolicy.KEEP_FIRST).single() + + private companion object { + const val BLANK_NAME_WARNING = + "Nav3 backStackEntryMapper returned a blank name. Using /unknown." + const val MAPPER_FAILURE_WARNING = + "Nav3 backStackEntryMapper threw. Using /unknown without arguments." + const val UNSUPPORTED_VALUE_WARNING = + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper." } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserverTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserverTest.kt index 250a0c0ab08..32d16db41a4 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserverTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserverTest.kt @@ -21,8 +21,8 @@ import io.sentry.TransactionOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.SentryNavOptions -import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY -import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_CONTEXT_KEY +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY +import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo import io.sentry.compose.navigation3.internal.lifecycle.NavScopes @@ -683,18 +683,17 @@ class BackStackObserverTest { assertThat(fixture.startedTransactions).hasSize(2) val profileTransaction = fixture.startedTransactions.last() assertThat(profileTransaction.isFinished).isFalse() - assertThat(profileTransaction.name).isEqualTo(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) + assertThat(profileTransaction.name).isEqualTo(UNKNOWN_ENTRY_NAME) assertThat(fixture.scope.transaction).isSameInstanceAs(profileTransaction) - assertThat(fixture.scope.screen).isEqualTo(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) - assertThat(fixture.scope.contexts.app?.viewNames) - .isEqualTo(listOf(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME)) + assertThat(fixture.scope.screen).isEqualTo(UNKNOWN_ENTRY_NAME) + assertThat(fixture.scope.contexts.app?.viewNames).isEqualTo(listOf(UNKNOWN_ENTRY_NAME)) assertThat(fixture.breadcrumbs).hasSize(2) assertThat(fixture.breadcrumbs.last().data) - .containsExactly("from", "/home", "to", NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) + .containsExactly("from", "/home", "to", UNKNOWN_ENTRY_NAME) assertThat(fixture.scope.navigationBackStack()) .isEqualTo( listOf( - mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), + mapOf("entry" to UNKNOWN_ENTRY_NAME), mapOf("entry" to "/home"), ), ) @@ -706,20 +705,19 @@ class BackStackObserverTest { assertThat(fixture.startedTransactions).hasSize(3) val cartTransaction = fixture.startedTransactions.last() assertThat(cartTransaction.isFinished).isFalse() - assertThat(cartTransaction.name).isEqualTo(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) + assertThat(cartTransaction.name).isEqualTo(UNKNOWN_ENTRY_NAME) assertThat(cartTransaction.getData("arguments")) .isEqualTo(mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed")) assertThat(fixture.scope.transaction).isSameInstanceAs(cartTransaction) - assertThat(fixture.scope.screen).isEqualTo(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) - assertThat(fixture.scope.contexts.app?.viewNames) - .isEqualTo(listOf(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME)) + assertThat(fixture.scope.screen).isEqualTo(UNKNOWN_ENTRY_NAME) + assertThat(fixture.scope.contexts.app?.viewNames).isEqualTo(listOf(UNKNOWN_ENTRY_NAME)) assertThat(fixture.breadcrumbs).hasSize(3) assertThat(fixture.breadcrumbs.last().data) .containsExactly( "from", - NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, + UNKNOWN_ENTRY_NAME, "to", - NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, + UNKNOWN_ENTRY_NAME, "to_arguments", mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed"), ) @@ -727,10 +725,10 @@ class BackStackObserverTest { .isEqualTo( listOf( mapOf( - "entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, + "entry" to UNKNOWN_ENTRY_NAME, "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed"), ), - mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), + mapOf("entry" to UNKNOWN_ENTRY_NAME), mapOf("entry" to "/home"), ), ) @@ -751,7 +749,7 @@ class BackStackObserverTest { assertThat(fixture.breadcrumbs.last().data) .containsExactly( "from", - NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, + UNKNOWN_ENTRY_NAME, "from_arguments", mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed"), "to", @@ -762,10 +760,10 @@ class BackStackObserverTest { listOf( mapOf("entry" to "/settings"), mapOf( - "entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, + "entry" to UNKNOWN_ENTRY_NAME, "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed"), ), - mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), + mapOf("entry" to UNKNOWN_ENTRY_NAME), mapOf("entry" to "/home"), ), ) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserverTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserverTest.kt index c0054136029..44339c1e40d 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserverTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserverTest.kt @@ -19,8 +19,8 @@ import io.sentry.TransactionOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.SentryNavOptions +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_CONTEXT_KEY import io.sentry.compose.navigation3.internal.lifecycle.INavStatePublisher -import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_CONTEXT_KEY import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo import io.sentry.protocol.TransactionNameSource diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt new file mode 100644 index 00000000000..d1296706461 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt @@ -0,0 +1,71 @@ +package io.sentry.compose.navigation3.internal.contract + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY +import org.junit.Test + +/** Pins the strings the Sentry UI displays, so that renaming one fails a test. */ +class NavDataContractTest { + + @Test + fun `navigation context keys match the displayed names`() { + assertThat(NAVIGATION_CONTEXT_KEY).isEqualTo("Navigation") + assertThat(BACK_STACK_KEY).isEqualTo("Back Stack") + } + + @Test + fun `back stack entry keys match the displayed names`() { + assertThat(BACK_STACK_ENTRY_KEY).isEqualTo("entry") + assertThat(BACK_STACK_ENTRY_ARGUMENTS_KEY).isEqualTo("entry_arguments") + } + + @Test + fun `transaction arguments key matches the displayed name`() { + assertThat(TRANSACTION_ARGUMENTS_KEY).isEqualTo("arguments") + } + + @Test + fun `breadcrumb keys match the displayed names`() { + assertThat(BREADCRUMB_FROM_KEY).isEqualTo("from") + assertThat(BREADCRUMB_TO_KEY).isEqualTo("to") + assertThat(BREADCRUMB_FROM_ARGUMENTS_KEY).isEqualTo("from_arguments") + assertThat(BREADCRUMB_TO_ARGUMENTS_KEY).isEqualTo("to_arguments") + } + + @Test + fun `navigation operation and transaction origin match the displayed values`() { + assertThat(NAVIGATION_OP).isEqualTo("navigation") + assertThat(NAVIGATION_TRANSACTION_ORIGIN).isEqualTo("auto.navigation.nav3") + } + + @Test + fun `unknown entry name matches the displayed name`() { + assertThat(UNKNOWN_ENTRY_NAME).isEqualTo("/unknown") + } + + @Test + fun `argument drop reason key matches the displayed name`() { + assertThat(ARGUMENT_DROP_REASON_KEY).isEqualTo("dropped_by_sentry") + } + + @Test + fun `each argument drop reason serializes to its displayed value`() { + val serializedValues = ArgumentDropReason.entries.associateWith { it.serializedValue } + + assertThat(serializedValues) + .containsExactly( + ArgumentDropReason.CHARACTER_LIMIT, + "max_character_limit_exceeded", + ArgumentDropReason.DUPLICATE_KEY, + "duplicate_key", + ArgumentDropReason.INVALID_STRUCTURE, + "invalid_structure", + ArgumentDropReason.MAPPING_FAILED, + "mapping_failed", + ArgumentDropReason.MAX_COUNT, + "max_argument_count_exceeded", + ArgumentDropReason.SANITIZATION_FAILED, + "sanitization_failed", + ) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavScopeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavScopeTest.kt index e51f3f59150..5d3eb8eef56 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavScopeTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavScopeTest.kt @@ -13,6 +13,7 @@ import io.sentry.SentryOptions import io.sentry.SpanStatus import io.sentry.TransactionContext import io.sentry.TransactionOptions +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_CONTEXT_KEY import org.junit.Assert.assertThrows import org.junit.Test import org.mockito.kotlin.any diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequestTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequestTest.kt index 6e2f5419cd2..b4e223107c3 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequestTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequestTest.kt @@ -8,6 +8,7 @@ import io.sentry.Scope import io.sentry.SentryOptions import io.sentry.TransactionContext import io.sentry.TransactionOptions +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_CONTEXT_KEY import io.sentry.protocol.App import io.sentry.protocol.Contexts import io.sentry.protocol.TransactionNameSource @@ -20,7 +21,7 @@ import org.mockito.kotlin.whenever class NavTransactionRequestTest { - private val navigationContext = mapOf("backstack" to listOf(mapOf("route" to "/Checkout"))) + private val navigationContext = mapOf("Back Stack" to listOf(mapOf("entry" to "/Checkout"))) private val scope = Scope(SentryOptions()) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavDataTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavDataTest.kt index 4fb69c7e853..517b9500f7b 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavDataTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavDataTest.kt @@ -3,6 +3,7 @@ package io.sentry.compose.navigation3.internal.lifecycle import com.google.common.truth.Truth.assertThat import io.sentry.Scope import io.sentry.SentryOptions +import io.sentry.compose.navigation3.internal.contract.NAVIGATION_CONTEXT_KEY import org.junit.Test class StagedNavDataTest {