From 4839dcda3afb20e7f6f6d6eb16b2bde8445ae91a Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 11:32:02 +0100 Subject: [PATCH 1/2] ref(nav3): Write back stack entry arguments through an ArgumentSink Bring back the ArgumentSink seam so that a custom mapper's map and the SerialNameAndProperties encoder that follows write their arguments through the same TreeArgumentWriter, which enforces every size and structural limit in one place. ArgumentSanitizer now adapts a custom mapper's map with HostArgumentSource instead of recursing through it directly. Behavior is unchanged: the existing ArgumentSanitizerTest passes, apart from its warnings moving to DropArguments. Duplicate keys are rejected in key(), before a value is spent or computed, which keeps the order of checks the direct recursion had. Co-Authored-By: Claude Opus 5.5 --- .../internal/backstack/BackStackConverter.kt | 190 +----- .../internal/common/ArgumentProtocol.kt | 221 +++++++ .../internal/common/HostArgumentSource.kt | 124 ++++ .../internal/common/TreeArgumentSink.kt | 136 ++++ .../backstack/ArgumentSanitizerTest.kt | 559 +--------------- .../internal/common/ArgumentBudgetTest.kt | 125 ++++ .../internal/common/ArgumentBudgets.kt | 12 + .../internal/common/HostArgumentSourceTest.kt | 591 +++++++++++++++++ .../internal/common/TreeArgumentSinkTest.kt | 622 ++++++++++++++++++ 9 files changed, 1869 insertions(+), 711 deletions(-) create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSource.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgetTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgets.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt 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 9285537508..4bd7f27ab2 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,10 +5,11 @@ 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.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.HostArgumentSource +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter -import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS -import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH -import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.internal.contract.BACK_STACK_ENTRY_ARGUMENTS_KEY @@ -18,7 +19,6 @@ import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY import io.sentry.util.ExceptionUtils -import java.util.IdentityHashMap /** * Converts the host app back stack into a list of [NormalizedSentryBackStackEntry]s. @@ -151,8 +151,10 @@ internal class BackStackConverter( /** * 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. + * [serializable form][SanitizedArguments.values]. + * + * Each entry's arguments are written by a [HostArgumentSource] into a [TreeArgumentSink], which + * bounds depth and total value count, and rejects cyclic structures. * * One instance is shared across every entry in a single [convert] call, so the value and * character budgets span the whole update. @@ -162,13 +164,9 @@ internal class BackStackConverter( private val warningState: WarningState, ) { - private var remainingValues = MAX_ARGUMENT_VALUES - private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + private val budget = ArgumentBudget() 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 raw argument inputs and returns the result. * @@ -187,142 +185,34 @@ internal class BackStackConverter( return SanitizedArguments(emptyMap(), reason) } + val source = HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } + val sink = TreeArgumentSink(budget) + + // A constraint violation the sink recorded takes precedence over whatever the source threw, + // as the source may have caught it and thrown something else, and it decides whether older + // entries keep their arguments. return try { - SanitizedArguments(sanitizeMap(raw, depth = 0)) - } catch (drop: DropArguments) { - if (drop.reason.exhaustsUpdateBudget) { - dropReason = drop.reason - } - logger.log(WARNING, drop.warning) - SanitizedArguments(emptyMap(), drop.reason) + source.writeTo(sink) + SanitizedArguments(sink.argumentsOrThrow()) + } catch (drop: DropArgumentsException) { + drop(sink.failure ?: drop) } catch (t: Throwable) { // Extracted maps may invoke host app code while iterating or stringifying values. ExceptionUtils.rethrowIfFatal(t) - logger.log(WARNING, STRUCTURE_WARNING, t) - SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) - } finally { - // A drop or failure leaves the containers it was inside of open. - activeContainers.clear() - } - } - - /** 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) - } - sanitized[name] = sanitizeValue(value, depth + 1) - } - activeContainers.remove(map) - return sanitized - } - - private fun sanitizeValue(value: Any?, depth: Int): Any? { - // 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) - } - - 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 - // 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) - spendText(value.toString()) + sink.failure?.let { + return drop(it) } - } - - /** - * 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 spendText(text: CharSequence): String { - checkFits(text.length) - val string = text.toString() - checkFits(string.length) - remainingCharacters -= string.length - return string - } - - private fun checkFits(characters: Int) { - if (characters > remainingCharacters) { - throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, MAX_CHARACTER_WARNING) + logger.log(WARNING, DropArgumentsException.STRUCTURE_WARNING, t) + SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) } } - private fun enter(container: Any) { - if (activeContainers.put(container, Unit) != null) { - throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING) + private fun drop(drop: DropArgumentsException): SanitizedArguments { + if (drop.reason.exhaustsUpdateBudget) { + dropReason = drop.reason } - } - - /** - * 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 drop an entry's arguments, logging [warning]. Overrides - * [fillInStackTrace] to skip stack-trace capture. - */ - private class DropArguments(val reason: ArgumentDropReason, val warning: String) : - RuntimeException() { - override fun fillInStackTrace(): Throwable = this - } - - companion object { - - const val MAX_CHARACTER_WARNING = - "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + - "this and older entries." - - const val MAX_COUNT_WARNING = - "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + - "and older entries." - - const val STRUCTURE_WARNING = - "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + - "entry's arguments." + logger.log(WARNING, drop.warning) + return SanitizedArguments(emptyMap(), drop.reason) } } @@ -380,9 +270,7 @@ internal data class NormalizedSentryBackStackEntry( val name: String, /** Sanitized [SentryBackStackEntry.arguments] (i.e., bounded in size and depth). */ val arguments: Map = emptyMap(), - /** - * The reason why the SDK dropped host-provided arguments, or null if no arguments were dropped. - */ + /** The reason why the SDK dropped the entry's arguments, or null if no arguments were dropped. */ val argumentDropReason: ArgumentDropReason? = null, /** Why the entry was recorded as [UNKNOWN_ENTRY_NAME], or `null` if it has a name. */ val unknownEntryReason: UnknownEntryReason? = null, @@ -451,23 +339,3 @@ internal fun NormalizedSentryBackStackEntry.transactionData(): Map internal fun List.serialize(): List> = map(NormalizedSentryBackStackEntry::serialize) - -/** 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`. */ -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/common/ArgumentProtocol.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt new file mode 100644 index 0000000000..353b0b1a6c --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt @@ -0,0 +1,221 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason + +/** + * The core protocol for the subsystem that converts properties of back stack entries into Sentry + * arguments. + * + * An [ArgumentSource] pushes information about one back stack entry's properties into a sink as the + * source produces them. Sink implementations are expected to materialize the provided info into a + * tree of arguments, where the tree has a bounded size and height. + * + * Sinks must throw a [DropArgumentsException] if a write violates a constraint or [reject] is + * called. Every write thereafter will throw the same exception. + * + * **The argument conversion subsystem** + * + * With Nav3, host apps manage their own nav back stack, which they implement as a list of + * arbitrarily typed entries. In order to be displayed in Sentry, each of those entries has to be + * mapped to a Sentry name (e.g., ProductDetailScreen) and zero or more arguments (e.g., + * productId="123abc"). There are two ways for host apps to provide us with those mappings: + * + * 1. via a custom `BackStackEntryMapper`; or + * + * 2. via one of our own built-in mappers (viz., `BackStackEntryMapper.SerialName` or + * `BackStackEntryMapper.SerialNameAndProperties`). + * + * `ArgumentSink` and `ArgumentSource` create the seam that lets us support differentiated + * processing on the source side (the host app's logic vs built-in logic) but uniform processing on + * the sink side (argument pruning, protecting against constraint violation, and tree + * materialization). + * + * Here are the moving parts: + * ```text + * ArgumentSource + * Custom mapper Built-in mappers + * ┌────────────────────┐ ┌───────────────────────┐ + * │ HostArgumentSource │ │ KotlinxArgumentSource │ + * │ (plain host map) │ │ (drives encoder) │ + * └────────┬───────────┘ └────────┬──────────────┘ + * │ │ via + * │ KotlinxPropertiesEncoder + SensitiveKeyFilter + * │ │ + * └──────────────┬──────────────┘ + * ▼ + * ┌───────────────────────────────┐ + * │ ArgumentSink │ + * └───────────────────────────────┘ + * ▲ implements + * ┌───────────────┴───────────────┐ + * │ TreeArgumentSink │ + * │ │ ┌────────────────────────┐ + * │ Enforce + materialize: │ spends ──▶│ ArgumentBudget │ + * │ • builds the argument tree │ └────────────────────────┘ + * │ • prevents constraint │ ┌────────────────────────┐ + * │ violation (e.g., depth) │ throws ──▶│ DropArgumentsException │ + * └───────────────────────────────┘ └────────────────────────┘ + * + * Note: BackStackConverter.ArgumentSanitizer owns the ArgumentBudget. It + * selects the ArgumentSource based on the mapper the host app provides. + * ``` + */ +internal interface ArgumentSink { + + /** + * The first [DropArgumentsException] thrown either by a write constraint violation or by a call + * to [reject]; `null` if neither has occurred. + * + * Preserves the original drop reason even if intervening code (e.g., a host app serializer) + * catches it and throws its own exception instead. + */ + val failure: DropArgumentsException? + + /** Starts a map as the next value. Call [end] when finished. */ + fun beginMap() + + /** Starts a list as the next value. Call [end] when finished. */ + fun beginList() + + /** + * Names the next value in the current map. + * + * Throws [DropArgumentsException] if the map already has a value named [name], as recording only + * one of them would show Sentry a partial map as if it were complete. [describeDuplicate] returns + * the warning to log in that case. + */ + fun key( + name: String, + describeDuplicate: () -> String = { DropArgumentsException.DUPLICATE_KEY_WARNING }, + ) + + /** + * Writes [value] as the next value. Supports `null`, [Boolean], [Number], [CharSequence], and + * [Char]; text is recorded as a [String]. + */ + fun scalar(value: Any?) + + /** + * Writes the value [compute] returns as the next value, as for [scalar]. A sink that enforces + * limits checks that the value can be written before calling [compute], so that host app code + * (e.g., a `toString()`) doesn't run for a value that won't be recorded, and can't replace the + * limit's drop reason with its own failure. + */ + fun computedScalar(compute: () -> Any?) { + scalar(compute()) + } + + /** Ends the most recently started map or list. */ + fun end() + + /** + * Reports the violation of a constraint that a source enforces itself, rather than one broken via + * a write (e.g., a host app's map that contains itself, or how deeply serializers nest). Throws + * the resulting [DropArgumentsException]. + * + * If a constraint was already violated, throws its `DropArgumentsException` instead. + */ + fun reject(reason: ArgumentDropReason, warning: String): Nothing +} + +/** + * Something that knows how to write a back stack entry's properties or arguments to an + * [ArgumentSink]. + * + * Sources have the following responsibilities: + * + * - choose which data to expose to the sink; and + * + * - enforce constraints the sink can't address because they aren't reflected in the sink's + * materialized tree (e.g., prohibit cycles in a custom mapper's arguments). + * + * Sources may implement additional functionality as needed, e.g., the source backing + * `SerialNameAndProperties` filters sensitive values to comply with Sentry's + * [sensitive denylist policy](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist). + */ +internal interface ArgumentSource { + fun writeTo(sink: ArgumentSink) +} + +/** + * The value and character budgets shared by the entries of one back stack update. + * + * Throws a [DropArgumentsException] if the remaining budget is insufficient. + */ +internal class ArgumentBudget { + + private var remainingValues = MAX_ARGUMENT_VALUES + private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + + /** Spends one value. */ + fun spendValue() { + if (--remainingValues < 0) { + throw DropArgumentsException( + ArgumentDropReason.MAX_COUNT, + DropArgumentsException.MAX_COUNT_WARNING, + ) + } + } + + /** + * 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. + */ + fun spendText(text: CharSequence): String { + checkFits(text.length) + val string = text.toString() + checkFits(string.length) + remainingCharacters -= string.length + return string + } + + private fun checkFits(characters: Int) { + if (characters > remainingCharacters) { + throw DropArgumentsException( + ArgumentDropReason.CHARACTER_LIMIT, + DropArgumentsException.MAX_CHARACTER_WARNING, + ) + } + } +} + +/** + * Thrown when an [ArgumentSink] is written to out of order or with a value it can't record, e.g., a + * map value without a key. + * + * Signals either a bug in the SDK or a custom serializer that writes values outside its elements, + * as opposed to a serializer that threw an exception of its own. + */ +internal class ArgumentProtocolException(message: String) : IllegalStateException(message) + +/** + * Control-flow signal to drop a back stack entry's arguments, logging [warning]. Overrides + * [fillInStackTrace] to skip stack-trace capture. + */ +internal class DropArgumentsException(val reason: ArgumentDropReason, val warning: String) : + RuntimeException() { + + override fun fillInStackTrace(): Throwable = this + + companion object { + + const val DUPLICATE_KEY_WARNING = + "Nav3 map keys stringify to the same string. Dropping this entry's arguments." + + const val MAX_CHARACTER_WARNING = + "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + + "this and older entries." + + const val MAX_COUNT_WARNING = + "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + + "and older entries." + + const val STRUCTURE_WARNING = + "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + + "entry's arguments." + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSource.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSource.kt new file mode 100644 index 0000000000..1756795a8d --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSource.kt @@ -0,0 +1,124 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import java.util.Collections +import java.util.IdentityHashMap + +/** + * An [ArgumentSource] for writing [the argument map][arguments] produced by a host app to an + * [ArgumentSink]. + * + * Nested maps are traversed recursively, collections and arrays become lists, and enums use their + * names. Map keys and unsupported values are stringified; unsupported types are reported to + * [onUnsupportedValue]. + * + * Traversal and string conversion may invoke host app code. + * + * **Rejects cycles** + * + * A map, collection, or array that contains itself, directly or through nested values, is a cycle, + * which this source [rejects][ArgumentSink.reject] as `INVALID_STRUCTURE` rather than writing the + * same object again until the depth limit is reached. + * + * An object that appears more than once without containing itself is written each time. + */ +internal class HostArgumentSource( + private val arguments: Map<*, *>, + private val onUnsupportedValue: (typeName: String?) -> Unit, +) : ArgumentSource { + + override fun writeTo(sink: ArgumentSink) { + Traversal(sink).writeEntries(arguments) + } + + /** Writes [arguments] to [sink] once, tracking the containers being written. */ + private inner class Traversal(private val sink: ArgumentSink) { + + /** The maps, collections, and arrays being written, by identity, starting with [arguments]. */ + private val open: MutableSet = + Collections.newSetFromMap(IdentityHashMap()).apply { add(arguments) } + + fun writeEntries(map: Map<*, *>) { + for ((key, value) in map) { + val name = key.toString() + sink.key(name) { duplicateKeyWarning(map, key, name) } + write(value) + } + } + + private fun write(value: Any?) { + val collection = value?.asCollectionOrNull() + when { + value is Map<*, *> -> writeContainer(value, sink::beginMap) { writeEntries(value) } + collection != null -> + writeContainer(value, sink::beginList) { + // Iterated without reading the collection's size, which the host app controls. + for (element in collection) { + write(element) + } + } + // Computed only once the sink has checked the value fits, as it may run host app code. + else -> sink.computedScalar { scalarOf(value) } + } + } + + private inline fun writeContainer( + container: Any, + begin: () -> Unit, + writeContents: () -> Unit, + ) { + // Begun before the cycle check, so that the sink's depth and value limits take precedence: + // the values they spend come from a budget that later entries share. + begin() + if (!open.add(container)) { + sink.reject( + ArgumentDropReason.INVALID_STRUCTURE, + DropArgumentsException.STRUCTURE_WARNING, + ) + } + writeContents() + open.remove(container) + sink.end() + } + } + + private fun scalarOf(value: Any?): Any? = + when (value) { + null, + is Boolean, + is Number, + is CharSequence, + is Char -> value + is Enum<*> -> value.name + else -> { + onUnsupportedValue(value::class.simpleName) + value.toString() + } + } + + /** + * 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 duplicateKeyWarning(map: Map<*, *>, key: Any?, name: String): String { + val otherKey = map.keys.firstOrNull { it !== key && it.toString() == name } + return "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." + } +} + +/** Returns this collection, 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 + } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt new file mode 100644 index 0000000000..8e279732bb --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt @@ -0,0 +1,136 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason + +/** + * An [ArgumentSink] that materializes an argument tree for a single back stack entry and enforces + * argument constraints. + * + * **Argument constraints** + * + * Rejects excessive nesting, duplicate keys, and writes that exceed the value or character limits + * in [budget]. + * + * Once a constraint is violated or [reject] is called, a [DropArgumentsException] is thrown. Both + * subsequent writes and [argumentsOrThrow] rethrow the same failure to prevent an [ArgumentSource] + * from accidentally generating partial arguments. + */ +@Suppress("TooManyFunctions") +internal class TreeArgumentSink( + /** The argument budget shared across all back stack entries processed in one update. */ + private val budget: ArgumentBudget, +) : ArgumentSink { + + private val root = LinkedHashMap() + + /** The open containers, innermost last. */ + private val containers = ArrayList().apply { add(root) } + + private var pendingKey: String? = null + + override var failure: DropArgumentsException? = null + private set + + override fun beginMap() = guarded { begin(LinkedHashMap()) } + + override fun beginList() = guarded { begin(ArrayList()) } + + override fun key(name: String, describeDuplicate: () -> String) = guarded { + budget.spendText(name) + if ((containers.last() as? Map<*, *>)?.containsKey(name) == true) { + throw DropArgumentsException(ArgumentDropReason.DUPLICATE_KEY, describeDuplicate()) + } + pendingKey = name + } + + override fun scalar(value: Any?) = writeScalar { value } + + override fun computedScalar(compute: () -> Any?) = writeScalar(compute) + + override fun end() = guarded { + if (containers.size <= 1) { + throw ArgumentProtocolException("end() without an open map or list.") + } + containers.removeAt(containers.lastIndex) + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing { + failure?.let { throw it } + throw DropArgumentsException(reason, warning).also { failure = it } + } + + /** + * Returns the entry's arguments, or re-throws the [DropArgumentsException] a write threw, even if + * the source caught it. + * + * Should only be called after the [ArgumentSource] has completed all writes and closed every + * nested map and list. + */ + fun argumentsOrThrow(): Map { + failure?.let { throw it } + return root + } + + private fun begin(container: Any) { + visitValue() + add(container) + containers += container + } + + /** Enforces the depth limit and spends one value for the value about to be added. */ + private fun visitValue() { + // A value added while n containers are open has a depth of n. + if (containers.size > MAX_ARGUMENT_DEPTH) { + throw DropArgumentsException( + ArgumentDropReason.INVALID_STRUCTURE, + DropArgumentsException.STRUCTURE_WARNING, + ) + } + budget.spendValue() + } + + @Suppress("UNCHECKED_CAST") + private fun add(value: Any?) { + when (val parent = containers.last()) { + is ArrayList<*> -> (parent as ArrayList) += value + else -> { + val key = + pendingKey ?: throw ArgumentProtocolException("A map value was written without a key.") + (parent as LinkedHashMap)[key] = value + pendingKey = null + } + } + } + + private inline fun writeScalar(compute: () -> Any?) = guarded { + visitValue() + add( + when (val value = compute()) { + null, + is Boolean -> value + // JSON has no NaN or infinity, and Sentry's JSON writer throws for them, which would drop + // the whole event these arguments are attached to. We record them as strings instead. + is Number -> if (value.isNonFinite()) budget.spendText(value.toString()) else value + is CharSequence -> budget.spendText(value) + is Char -> budget.spendText(value.toString()) + else -> + throw ArgumentProtocolException("Unsupported scalar of type ${value.javaClass.name}.") + }, + ) + } + + private inline fun guarded(write: () -> Unit) { + failure?.let { throw it } + try { + write() + } catch (e: DropArgumentsException) { + failure = e + throw e + } + } +} + +/** 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/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 d1b4a18561..170796764f 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 @@ -6,17 +6,14 @@ import io.sentry.SentryLevel.WARNING 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.common.DropArgumentsException 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 @@ -28,39 +25,6 @@ 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 } @@ -70,28 +34,6 @@ 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, " + @@ -117,199 +59,8 @@ 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())) @@ -333,7 +84,7 @@ class ArgumentSanitizerTest { val sanitized = sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES) { it })) assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_COUNT_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArgumentsException.MAX_COUNT_WARNING)) } @Test @@ -343,7 +94,7 @@ class ArgumentSanitizerTest { assertThat(sanitized) .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArgumentsException.MAX_CHARACTER_WARNING)) } @Test @@ -355,7 +106,7 @@ class ArgumentSanitizerTest { assertThat(sanitized) .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArgumentsException.STRUCTURE_WARNING)) } @Test @@ -374,269 +125,6 @@ class ArgumentSanitizerTest { ) } - @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, - // once the 30 scalars and "self" have spent 31 values. Otherwise its contents would be written - // once more before the cycle is found, spending another 31 values of the shared budget. - val selfContaining = mutableMapOf() - repeat(30) { selfContaining["k$it"] = it } - selfContaining["self"] = selfContaining - // A list and its elements, which spend exactly the values left. - val rest = mapOf("values" to List(MAX_ARGUMENT_VALUES - 31 - 1) { it }) - - val dropped = sanitizer.sanitizeEntry(selfContaining) - val later = sanitizer.sanitizeEntry(rest) - - assertThat(dropped) - .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) - 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 @@ -681,7 +169,8 @@ class ArgumentSanitizerTest { sanitizer.sanitizeEntry(mapOf("throwing" to throwing)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), eq(throwing.failure)) + verify(logger) + .log(eq(WARNING), eq(DropArgumentsException.STRUCTURE_WARNING), eq(throwing.failure)) } @Test @@ -695,18 +184,7 @@ class ArgumentSanitizerTest { sanitizer.sanitizeEntry(mapOf("fatal" to fatal)) } verify(logger, never()) - .log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), any()) - } - - @Test - fun `a container from an entry that failed sanitization isn't treated as a cycle in later entries`() { - val holder = mutableListOf(ThrowingValue()) - sanitizer.sanitizeEntry(mapOf("holder" to holder)) - holder.clear() - - val sanitized = sanitizer.sanitizeEntry(mapOf("holder" to holder)) - - assertThat(sanitized).isEqualTo(SanitizedArguments(mapOf("holder" to emptyList()))) + .log(eq(WARNING), eq(DropArgumentsException.STRUCTURE_WARNING), any()) } // Later entries after a drop @@ -718,7 +196,7 @@ class ArgumentSanitizerTest { val later = sanitizer.sanitizeEntry(laterArguments) assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) - verify(logger, times(1)).log(eq(WARNING), eq(ArgumentSanitizer.MAX_COUNT_WARNING)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArgumentsException.MAX_COUNT_WARNING)) } @Test @@ -728,7 +206,7 @@ class ArgumentSanitizerTest { val later = sanitizer.sanitizeEntry(laterArguments) assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) - verify(logger, times(1)).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArgumentsException.MAX_CHARACTER_WARNING)) } @Test @@ -760,22 +238,3 @@ 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/common/ArgumentBudgetTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgetTest.kt new file mode 100644 index 0000000000..63597a6ead --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgetTest.kt @@ -0,0 +1,125 @@ +package io.sentry.compose.navigation3.internal.common + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlin.test.assertFailsWith +import org.junit.Test + +class ArgumentBudgetTest { + + /** Text whose reported [length] may differ from its text, counting its conversions. */ + private class MisreportedText(override val length: Int, private val text: String) : CharSequence { + var toStringCalls = 0 + + 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 + } + } + + private val budget = ArgumentBudget() + + // spendValue() + + @Test + fun `spendValue() - drops the arguments for the value limit once every value is spent`() { + repeat(MAX_ARGUMENT_VALUES) { budget.spendValue() } + + val drop = assertFailsWith { budget.spendValue() } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(drop.warning).isEqualTo(DropArgumentsException.MAX_COUNT_WARNING) + } + + @Test + fun `spendValue() - doesn't spend characters`() { + repeat(MAX_ARGUMENT_VALUES) { budget.spendValue() } + + val text = budget.spendText("x".repeat(MAX_ARGUMENT_CHARACTERS)) + + assertThat(text).hasLength(MAX_ARGUMENT_CHARACTERS) + } + + // spendText() + + @Test + fun `spendText() - returns the text as a String`() { + val text = budget.spendText(StringBuilder("hello")) + + assertThat(text).isEqualTo("hello") + } + + @Test + fun `spendText() - spends text exactly as long as the remaining characters`() { + val limited = budgetWithCharactersRemaining(2) + + val text = limited.spendText("ab") + + assertThat(text).isEqualTo("ab") + } + + @Test + fun `spendText() - drops the arguments for the character limit when text is longer than the remaining characters`() { + val limited = budgetWithCharactersRemaining(1) + + val drop = assertFailsWith { limited.spendText("ab") } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(drop.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) + } + + @Test + fun `spendText() - spends the characters of earlier text`() { + budget.spendText("x".repeat(MAX_ARGUMENT_CHARACTERS - 1)) + + val drop = assertFailsWith { budget.spendText("ab") } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `spendText() - doesn't convert text whose reported length doesn't fit`() { + val limited = budgetWithCharactersRemaining(1) + val text = MisreportedText(length = 2, text = "ab") + + assertFailsWith { limited.spendText(text) } + + assertThat(text.toStringCalls).isEqualTo(0) + } + + @Test + fun `spendText() - drops the arguments for text longer than its reported length when its text doesn't fit`() { + val limited = budgetWithCharactersRemaining(1) + + val drop = + assertFailsWith { + limited.spendText(MisreportedText(length = 1, text = "ab")) + } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `spendText() - spends the characters of the text rather than its reported length`() { + val limited = budgetWithCharactersRemaining(2) + limited.spendText(MisreportedText(length = 0, text = "ab")) + + val drop = assertFailsWith { limited.spendText("c") } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `spendText() - doesn't spend values`() { + budget.spendText("x".repeat(MAX_ARGUMENT_CHARACTERS)) + + repeat(MAX_ARGUMENT_VALUES) { budget.spendValue() } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgets.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgets.kt new file mode 100644 index 0000000000..4b3f76bb7c --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentBudgets.kt @@ -0,0 +1,12 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES + +/** Returns a budget with only [remaining] values left, as if other entries spent the rest. */ +internal fun budgetWithValuesRemaining(remaining: Int): ArgumentBudget = + ArgumentBudget().apply { repeat(MAX_ARGUMENT_VALUES - remaining) { spendValue() } } + +/** Returns a budget with only [remaining] characters left, as if other entries spent the rest. */ +internal fun budgetWithCharactersRemaining(remaining: Int): ArgumentBudget = + ArgumentBudget().apply { spendText("x".repeat(MAX_ARGUMENT_CHARACTERS - remaining)) } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt new file mode 100644 index 0000000000..addca86f76 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt @@ -0,0 +1,591 @@ +package io.sentry.compose.navigation3.internal.common + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.BeginList +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.BeginMap +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.End +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.Key +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.Reject +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.Scalar +import io.sentry.compose.navigation3.internal.common.HostArgumentSourceTest.Event.UncomputedScalar +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import java.math.BigDecimal +import java.util.AbstractCollection +import kotlin.test.assertFailsWith +import org.junit.Test + +class HostArgumentSourceTest { + + private enum class PrivacyMode { + PUBLIC, + PRIVATE, + } + + private class OpaqueValue { + override fun toString(): String = "opaque-value" + } + + private class OpaqueIterable : Iterable { + override fun iterator(): Iterator = listOf("a").iterator() + + override fun toString(): String = "opaque-iterable" + } + + private class OpaqueSequence : Sequence { + override fun iterator(): Iterator = listOf("a").iterator() + + override fun toString(): String = "opaque-sequence" + } + + private data class UserId(val email: String) { + override fun toString(): String = email + } + + private class CountingValue { + var toStringCalls = 0 + + override fun toString(): String { + toStringCalls++ + return "counting-value" + } + } + + private val unsupportedTypeNames = mutableListOf() + private val sink = RecordingArgumentSink() + + // Arguments + + @Test + fun `writeTo() - writes each argument as its key followed by its value`() { + val source = hostArgumentSource(mapOf("id" to "123", "page" to 2)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("id"), Scalar("123"), Key("page"), Scalar(2)) + .inOrder() + } + + @Test + fun `writeTo() - writes nothing for empty arguments`() { + val source = hostArgumentSource(emptyMap()) + + source.writeTo(sink) + + assertThat(sink.events).isEmpty() + } + + @Test + fun `writeTo() - writes map keys by toString`() { + val key = + object { + override fun toString(): String = "custom-key" + } + val source = + hostArgumentSource(mapOf(1 to "a", PrivacyMode.PUBLIC to "b", key to "c", null to "d")) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly(Key("1"), Key("PUBLIC"), Key("custom-key"), Key("null")) + .inOrder() + } + + @Test + fun `writeTo() - describes a duplicate key by the types of the colliding keys rather than their values`() { + val source = + hostArgumentSource(linkedMapOf(UserId("ada@example.com") to "a", "ada@example.com" to "b")) + + val drop = + assertFailsWith { + source.writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + assertThat(drop.warning) + .isEqualTo( + "A Nav3 map key (String) stringifies to the same string as another key (UserId). " + + "Dropping this entry's arguments.", + ) + } + + @Test + fun `writeTo() - describes a null or anonymous map key that collides with another key as null`() { + val anonymous = + object { + override fun toString(): String = "id" + } + val sources = + listOf( + hostArgumentSource(linkedMapOf("null" to "a", null to "b")), + hostArgumentSource(linkedMapOf("id" to "a", anonymous to "b")), + ) + + val warnings = sources.map { source -> + assertFailsWith { + source.writeTo(TreeArgumentSink(ArgumentBudget())) + } + .warning + } + + val expected = + "A Nav3 map key (null) stringifies to the same string as another key (String). " + + "Dropping this entry's arguments." + assertThat(warnings).containsExactly(expected, expected) + } + + // Containers + + @Test + fun `writeTo() - writes a nested map between beginMap() and end()`() { + val nested = mapOf(1 to "a") + val source = hostArgumentSource(mapOf("nested" to nested)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("nested"), BeginMap, Key("1"), Scalar("a"), End) + .inOrder() + } + + @Test + fun `writeTo() - writes a collection as a list`() { + val set = linkedSetOf("a", "b") + val source = hostArgumentSource(mapOf("set" to set)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("set"), BeginList, Scalar("a"), Scalar("b"), End) + .inOrder() + } + + @Test + fun `writeTo() - writes an object array as a list`() { + val array = arrayOf("a", 1) + val source = hostArgumentSource(mapOf("array" to array)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("array"), BeginList, Scalar("a"), Scalar(1), End) + .inOrder() + } + + @Test + fun `writeTo() - writes primitive arrays as lists of their elements`() { + val source = + hostArgumentSource( + mapOf( + "booleans" to booleanArrayOf(true), + "bytes" to byteArrayOf(1), + "shorts" to shortArrayOf(2), + "ints" to intArrayOf(3), + "longs" to longArrayOf(4L), + "floats" to floatArrayOf(5f), + "doubles" to doubleArrayOf(6.0), + "chars" to charArrayOf('7'), + ), + ) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly( + Scalar(true), + Scalar(1.toByte()), + Scalar(2.toShort()), + Scalar(3), + Scalar(4L), + Scalar(5f), + Scalar(6.0), + Scalar('7'), + ) + .inOrder() + assertThat(sink.events.count { it is BeginList }).isEqualTo(8) + } + + @Test + fun `writeTo() - writes containers nested in containers recursively`() { + val inner = listOf(1) + val outer = mapOf("inner" to inner) + val source = hostArgumentSource(mapOf("outer" to listOf(outer))) + + source.writeTo(sink) + + assertThat(sink.events.drop(1)) + .containsExactly( + BeginList, + BeginMap, + Key("inner"), + BeginList, + Scalar(1), + End, + End, + End, + ) + .inOrder() + } + + @Test + fun `writeTo() - doesn't read the size of a collection`() { + val values = + object : AbstractCollection() { + var wasSizeRead = false + + override val size: Int + get() { + wasSizeRead = true + return Int.MAX_VALUE + } + + override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() + } + val source = hostArgumentSource(mapOf("values" to values)) + + source.writeTo(sink) + + assertThat(values.wasSizeRead).isFalse() + } + + // Cycles + + @Test + fun `writeTo() - rejects a map that contains itself as invalid structure`() { + val cyclic = mutableMapOf() + cyclic["self"] = cyclic + val source = hostArgumentSource(mapOf("cyclic" to cyclic)) + + val drop = assertFailsWith { source.writeTo(sink) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(drop.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + assertThat(sink.events.last()).isEqualTo(Reject(ArgumentDropReason.INVALID_STRUCTURE)) + } + + @Test + fun `writeTo() - rejects a nested value that contains the argument map as invalid structure`() { + val arguments = mutableMapOf() + arguments["children"] = listOf(arguments) + val source = hostArgumentSource(arguments) + + val drop = assertFailsWith { source.writeTo(sink) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(sink.events) + .containsExactly( + Key("children"), + BeginList, + BeginMap, + Reject(ArgumentDropReason.INVALID_STRUCTURE), + ) + .inOrder() + } + + @Test + fun `writeTo() - rejects a collection that contains itself as invalid structure`() { + val cyclic = mutableListOf() + cyclic.add(cyclic) + val source = hostArgumentSource(mapOf("cyclic" to cyclic)) + + val drop = assertFailsWith { source.writeTo(sink) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `writeTo() - rejects an array that contains itself as invalid structure`() { + val cyclic = arrayOfNulls(1) + cyclic[0] = cyclic + val source = hostArgumentSource(mapOf("cyclic" to cyclic)) + + val drop = assertFailsWith { source.writeTo(sink) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `writeTo() - starts a container that contains itself on the sink before rejecting it`() { + val cyclic = mutableListOf() + cyclic.add(cyclic) + val source = hostArgumentSource(mapOf("cyclic" to cyclic)) + + assertFailsWith { source.writeTo(sink) } + + assertThat(sink.events) + .containsExactly( + Key("cyclic"), + BeginList, + BeginList, + Reject(ArgumentDropReason.INVALID_STRUCTURE), + ) + .inOrder() + } + + @Test + fun `writeTo() - writes a container that appears more than once without containing itself`() { + val shared = listOf("a") + val source = hostArgumentSource(mapOf("first" to shared, "second" to listOf(shared))) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly( + Key("first"), + BeginList, + Scalar("a"), + End, + Key("second"), + BeginList, + BeginList, + Scalar("a"), + End, + End, + ) + .inOrder() + } + + @Test + fun `writeTo() - writes the same arguments again on a later call`() { + val nested = mapOf("k" to "v") + val source = hostArgumentSource(mapOf("nested" to nested)) + source.writeTo(RecordingArgumentSink()) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("nested"), BeginMap, Key("k"), Scalar("v"), End) + .inOrder() + } + + @Test + fun `writeTo() - writes a container again on a later call after an earlier call stopped inside it`() { + val failure = + DropArgumentsException(ArgumentDropReason.MAX_COUNT, DropArgumentsException.MAX_COUNT_WARNING) + val nested = mapOf("k" to "v") + val source = hostArgumentSource(mapOf("nested" to nested)) + assertFailsWith { + source.writeTo(RecordingArgumentSink(failOnKey = "k", keyFailure = failure)) + } + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("nested"), BeginMap, Key("k"), Scalar("v"), End) + .inOrder() + } + + // Scalars + + @Test + fun `writeTo() - passes null, Boolean, and Number values unchanged`() { + val bigDecimal = BigDecimal("1.25") + val source = + hostArgumentSource( + mapOf("null" to null, "boolean" to true, "nan" to Double.NaN, "bigDecimal" to bigDecimal), + ) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly(Scalar(null), Scalar(true), Scalar(Double.NaN), Scalar(bigDecimal)) + .inOrder() + } + + @Test + fun `writeTo() - passes CharSequence and Char values unchanged`() { + val text = StringBuilder("hello") + val source = hostArgumentSource(mapOf("text" to text, "char" to 'x')) + + source.writeTo(sink) + + val scalars = sink.events.filterIsInstance() + assertThat(scalars[0].value).isSameInstanceAs(text) + assertThat(scalars[1].value).isEqualTo('x') + } + + @Test + fun `writeTo() - writes enums by name`() { + val source = hostArgumentSource(mapOf("mode" to PrivacyMode.PRIVATE)) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("mode"), Scalar("PRIVATE")).inOrder() + } + + @Test + fun `writeTo() - doesn't report supported values as unsupported`() { + val source = + hostArgumentSource( + mapOf( + "string" to "a", + "char" to 'b', + "number" to 1, + "boolean" to false, + "null" to null, + "enum" to PrivacyMode.PUBLIC, + "list" to listOf(1), + "map" to mapOf("k" to "v"), + "array" to intArrayOf(1), + ), + ) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).isEmpty() + } + + // Unsupported values + + @Test + fun `writeTo() - writes an unsupported value by toString`() { + val source = hostArgumentSource(mapOf("opaque" to OpaqueValue())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("opaque"), Scalar("opaque-value")).inOrder() + } + + @Test + fun `writeTo() - reports an unsupported value with its simple type name`() { + val source = hostArgumentSource(mapOf("opaque" to OpaqueValue())) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).containsExactly("OpaqueValue") + } + + @Test + fun `writeTo() - writes an Iterable that isn't a Collection as an unsupported value`() { + val source = hostArgumentSource(mapOf("iterable" to OpaqueIterable())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("iterable"), Scalar("opaque-iterable")).inOrder() + assertThat(unsupportedTypeNames).containsExactly("OpaqueIterable") + } + + @Test + fun `writeTo() - writes a Sequence as an unsupported value`() { + val source = hostArgumentSource(mapOf("sequence" to OpaqueSequence())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("sequence"), Scalar("opaque-sequence")).inOrder() + assertThat(unsupportedTypeNames).containsExactly("OpaqueSequence") + } + + @Test + fun `writeTo() - reports an unsupported value of an anonymous type with a null type name`() { + val anonymous = + object { + override fun toString(): String = "anonymous" + } + val source = hostArgumentSource(mapOf("anonymous" to anonymous)) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).containsExactly(null) + } + + @Test + fun `writeTo() - doesn't call an unsupported value's toString() or report it until the sink computes the value`() { + val value = CountingValue() + val sink = RecordingArgumentSink(computesScalars = false) + val source = hostArgumentSource(mapOf("counting" to value)) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("counting"), UncomputedScalar).inOrder() + assertThat(value.toStringCalls).isEqualTo(0) + assertThat(unsupportedTypeNames).isEmpty() + } + + // Failures + + @Test + fun `writeTo() - stops writing when the sink throws`() { + val failure = + DropArgumentsException(ArgumentDropReason.MAX_COUNT, DropArgumentsException.MAX_COUNT_WARNING) + val sink = RecordingArgumentSink(failOnKey = "second", keyFailure = failure) + val source = hostArgumentSource(mapOf("first" to 1, "second" to 2, "third" to 3)) + + val thrown = assertFailsWith { source.writeTo(sink) } + + assertThat(thrown).isSameInstanceAs(failure) + assertThat(sink.events).containsExactly(Key("first"), Scalar(1)).inOrder() + } + + private fun hostArgumentSource(arguments: Map<*, *>): HostArgumentSource = + HostArgumentSource(arguments) { unsupportedTypeNames += it } + + internal sealed interface Event { + data class Key(val name: String) : Event + + data class Scalar(val value: Any?) : Event + + object BeginMap : Event { + override fun toString(): String = "BeginMap" + } + + object BeginList : Event { + override fun toString(): String = "BeginList" + } + + data class Reject(val reason: ArgumentDropReason) : Event + + object End : Event { + override fun toString(): String = "End" + } + + /** A computed scalar the sink declined to compute. */ + object UncomputedScalar : Event { + override fun toString(): String = "UncomputedScalar" + } + } + + /** + * Records every call as an [Event], and throws [keyFailure] when asked for the key [failOnKey]. + * With `computesScalars = false`, records each computed scalar without computing it. + */ + private class RecordingArgumentSink( + private val failOnKey: String? = null, + private val keyFailure: RuntimeException? = null, + private val computesScalars: Boolean = true, + ) : ArgumentSink { + + val events = mutableListOf() + + override val failure: DropArgumentsException? = null + + override fun beginMap() { + events += BeginMap + } + + override fun beginList() { + events += BeginList + } + + override fun key(name: String, describeDuplicate: () -> String) { + if (name == failOnKey && keyFailure != null) throw keyFailure + events += Key(name) + } + + override fun scalar(value: Any?) { + events += Scalar(value) + } + + override fun computedScalar(compute: () -> Any?) { + if (computesScalars) scalar(compute()) else events += UncomputedScalar + } + + override fun end() { + events += End + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing { + events += Reject(reason) + throw DropArgumentsException(reason, warning) + } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt new file mode 100644 index 0000000000..89fb5b5117 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt @@ -0,0 +1,622 @@ +package io.sentry.compose.navigation3.internal.common + +import com.google.common.truth.Truth.assertThat +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.util.UrlUtils +import kotlin.test.assertFailsWith +import org.junit.Test + +class TreeArgumentSinkTest { + + private val sink = TreeArgumentSink(ArgumentBudget()) + + private val characterLimitDrop = + ArgumentDropReason.CHARACTER_LIMIT to DropArgumentsException.MAX_CHARACTER_WARNING + private val duplicateKeyDrop = + ArgumentDropReason.DUPLICATE_KEY to DropArgumentsException.DUPLICATE_KEY_WARNING + private val maxCountDrop = + ArgumentDropReason.MAX_COUNT to DropArgumentsException.MAX_COUNT_WARNING + private val structureDrop = + ArgumentDropReason.INVALID_STRUCTURE to DropArgumentsException.STRUCTURE_WARNING + + private val DropArgumentsException.signal: Pair + get() = reason to warning + + private companion object { + const val SUBSTITUTE = UrlUtils.SENSITIVE_DATA_SUBSTITUTE + } + + // Building the tree + + @Test + fun `argumentsOrThrow() - returns the arguments written as maps and lists`() { + sink.key("id") + sink.scalar("123") + sink.key("filters") + sink.beginMap() + sink.key("tags") + sink.beginList() + sink.scalar("a") + sink.scalar(true) + sink.end() + sink.key("limit") + sink.scalar(null) + sink.end() + sink.key("page") + sink.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf( + "id" to "123", + "filters" to mapOf("tags" to listOf("a", true), "limit" to null), + "page" to 2, + ), + ) + } + + @Test + fun `argumentsOrThrow() - keeps arguments in the order they were written`() { + sink.key("b") + sink.scalar(1) + sink.key("a") + sink.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments.keys).containsExactly("b", "a").inOrder() + } + + @Test + fun `argumentsOrThrow() - returns an empty map when nothing was written`() { + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEmpty() + } + + // Scalars + + @Test + fun `scalar() - records CharSequence and Char values as Strings`() { + sink.key("text") + sink.scalar(StringBuilder("hello")) + sink.key("char") + sink.scalar('x') + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("text" to "hello", "char" to "x")) + assertThat(arguments["text"]).isInstanceOf(String::class.java) + assertThat(arguments["char"]).isInstanceOf(String::class.java) + } + + @Test + fun `scalar() - spends one value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + limitedSink.key("id") + + val drop = assertFailsWith { limitedSink.scalar(1) } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `scalar() - spends characters for a CharSequence value`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar(StringBuilder("ab")) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - spends characters for a Char value`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(0)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar('x') } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - records non-finite Double and Float values as strings`() { + sink.key("double") + sink.scalar(Double.NEGATIVE_INFINITY) + sink.key("float") + sink.scalar(Float.NaN) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("double" to "-Infinity", "float" to "NaN")) + } + + @Test + fun `scalar() - spends characters for a non-finite number string`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining("NaN".length - 1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar(Double.NaN) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - doesn't spend characters for a finite number`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(0)) + limitedSink.key("") + + limitedSink.scalar(123.456) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to 123.456)) + } + + @Test + fun `scalar() - doesn't spend characters for a boolean or null`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(0)) + limitedSink.key("") + limitedSink.beginList() + + limitedSink.scalar(true) + limitedSink.scalar(null) + limitedSink.end() + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to listOf(true, null))) + } + + @Test + fun `scalar() - throws ArgumentProtocolException for an unsupported type`() { + sink.key("opaque") + + assertFailsWith { sink.scalar(Any()) } + } + + @Test + fun `scalar() - throws ArgumentProtocolException for a map value written without a key`() { + assertFailsWith { sink.scalar(1) } + } + + // Computed scalars + + @Test + fun `computedScalar() - writes the computed value as scalar() would`() { + sink.key("text") + sink.computedScalar { StringBuilder("hello") } + sink.key("page") + sink.computedScalar { 2 } + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("text" to "hello", "page" to 2)) + assertThat(arguments["text"]).isInstanceOf(String::class.java) + } + + @Test + fun `computedScalar() - spends characters for computed text`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.computedScalar { "ab" } } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `computedScalar() - drops the arguments without computing the value when the value budget is spent`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + limitedSink.key("a") + var computations = 0 + + val drop = + assertFailsWith { limitedSink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - drops the arguments for invalid structure without computing a value nested too deeply`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + var computations = 0 + + val drop = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(structureDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - rethrows an earlier drop without computing the value`() { + val drop = exhaustValues() + var computations = 0 + + val thrown = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(thrown).isSameInstanceAs(drop) + assertThat(computations).isEqualTo(0) + } + + // Keys + + @Test + fun `key() - spends the characters of the key`() { + val limitedSink = TreeArgumentSink(budgetWithCharactersRemaining(1)) + + val drop = assertFailsWith { limitedSink.key("ab") } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `key() - doesn't spend a value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + + limitedSink.key("a") + + val drop = assertFailsWith { limitedSink.scalar(1) } + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + // Duplicate keys + + @Test + fun `key() - drops the arguments for a key already in its map before its value is written`() { + sink.key("id") + sink.scalar(1) + + val drop = assertFailsWith { sink.key("id") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `key() - drops the arguments for a key already in its map with the warning describeDuplicate returns`() { + sink.key("id") + sink.scalar(1) + + val drop = assertFailsWith { sink.key("id") { "described" } } + + assertThat(drop.signal).isEqualTo(ArgumentDropReason.DUPLICATE_KEY to "described") + } + + @Test + fun `key() - doesn't describe a key that isn't already in its map`() { + sink.key("id") { error("described a unique key") } + + sink.scalar(1) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to 1)) + } + + @Test + fun `key() - drops the arguments for a duplicate key, not the value limit, with no values left`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(1)) + limitedSink.key("id") + limitedSink.scalar(1) + + val drop = assertFailsWith { limitedSink.key("id") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `the same key in a nested map and its parent map is written to both`() { + sink.key("id") + sink.beginMap() + sink.key("id") + sink.scalar(1) + sink.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("id" to mapOf("id" to 1))) + } + + @Test + fun `the same key in sibling maps is written to both`() { + sink.key("first") + sink.beginMap() + sink.key("id") + sink.scalar(1) + sink.end() + sink.key("second") + sink.beginMap() + sink.key("id") + sink.scalar(2) + sink.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo(mapOf("first" to mapOf("id" to 1), "second" to mapOf("id" to 2))) + } + + @Test + fun `key() - drops the arguments for a duplicate substitute key, even when both values are the substitute`() { + sink.key(SUBSTITUTE) + sink.scalar(SUBSTITUTE) + + val drop = assertFailsWith { sink.key(SUBSTITUTE) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `another key holding the substitute drops the arguments for a duplicate key`() { + sink.key("token") + sink.scalar(SUBSTITUTE) + + val drop = assertFailsWith { sink.key("token") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + // Containers + + @Test + fun `beginMap() - spends one value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + limitedSink.key("map") + + val drop = assertFailsWith { limitedSink.beginMap() } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `beginList() - spends one value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(0)) + limitedSink.key("list") + + val drop = assertFailsWith { limitedSink.beginList() } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `the root map doesn't spend a value`() { + val limitedSink = TreeArgumentSink(budgetWithValuesRemaining(1)) + limitedSink.key("id") + + limitedSink.scalar(1) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("id" to 1)) + } + + @Test + fun `end() - throws ArgumentProtocolException when no map or list is open`() { + assertFailsWith { sink.end() } + } + + @Test + fun `end() - throws ArgumentProtocolException after every opened map and list was ended`() { + sink.key("list") + sink.beginList() + sink.end() + + assertFailsWith { sink.end() } + } + + // Depth + + @Test + fun `a scalar at the maximum depth is written`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.scalar("leaf") + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("nested" to nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf"))) + } + + @Test + fun `a scalar past the maximum depth drops the arguments for invalid structure`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + + val drop = assertFailsWith { sink.scalar("leaf") } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container at the maximum depth is written`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.beginMap() + sink.end() + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("nested" to nestedInLists(MAX_ARGUMENT_DEPTH - 1, emptyMap()))) + } + + @Test + fun `a container past the maximum depth drops the arguments for invalid structure`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + + val drop = assertFailsWith { sink.beginMap() } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `depth counts only containers that are still open`() { + sink.key("closed") + openLists(MAX_ARGUMENT_DEPTH - 1) + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.scalar("leaf") + + assertThat(sink.argumentsOrThrow()["nested"]) + .isEqualTo(nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf")) + } + + // Sticky failure + + @Test + fun `every write after the arguments are dropped rethrows the same DropArgumentsException`() { + val drop = exhaustValues() + + assertThat(assertFailsWith { sink.key("a") }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.scalar(1) }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginMap() }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginList() }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.end() }).isSameInstanceAs(drop) + } + + @Test + fun `argumentsOrThrow() - rethrows the DropArgumentsException a source caught and swallowed`() { + val caught = exhaustValues() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(caught) + } + + // Recorded failure + + @Test + fun `failure - is null while every write is within the limits`() { + sink.key("id") + sink.scalar("123") + + assertThat(sink.failure).isNull() + } + + @Test + fun `failure - is the DropArgumentsException thrown by the write that broke a limit`() { + val drop = exhaustValues() + + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `failure - stays the first DropArgumentsException after later writes throw`() { + val drop = exhaustValues() + assertFailsWith { sink.key("after") } + assertFailsWith { sink.scalar("x".repeat(MAX_ARGUMENT_CHARACTERS)) } + + val failure = sink.failure + + assertThat(failure).isSameInstanceAs(drop) + } + + @Test + fun `failure - stays null after a write throws for an unsupported value`() { + sink.key("opaque") + assertFailsWith { sink.scalar(Any()) } + + val failure = sink.failure + + assertThat(failure).isNull() + } + + // Limits a source enforces itself + + @Test + fun `reject() - throws DropArgumentsException with the given reason and warning`() { + val drop = rejectStructure() + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `reject() - records the DropArgumentsException it throws as the failure`() { + val drop = rejectStructure() + + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArgumentsException when a write already broke a limit`() { + val writeDrop = exhaustValues() + + val drop = rejectStructure() + + assertThat(drop).isSameInstanceAs(writeDrop) + assertThat(sink.failure).isSameInstanceAs(writeDrop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArgumentsException when a limit was already rejected`() { + val firstDrop = rejectStructure() + + val drop = + assertFailsWith { + sink.reject(ArgumentDropReason.MAX_COUNT, DropArgumentsException.MAX_COUNT_WARNING) + } + + assertThat(drop).isSameInstanceAs(firstDrop) + assertThat(sink.failure).isSameInstanceAs(firstDrop) + } + + @Test + fun `every write after a rejected limit rethrows the rejected DropArgumentsException`() { + val drop = rejectStructure() + + assertThat(assertFailsWith { sink.key("a") }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.scalar(1) }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginMap() }).isSameInstanceAs(drop) + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `argumentsOrThrow() - rethrows the rejected DropArgumentsException a source caught and swallowed`() { + sink.key("id") + sink.scalar("123") + val rejected = rejectStructure() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(rejected) + } + + // DropArgumentsException + + @Test + fun `DropArgumentsException - has no stack trace`() { + val drop = exhaustValues() + + assertThat(drop.stackTrace).isEmpty() + } + + /** Opens [count] nested lists, so the next value has a depth of `count + 1`. */ + private fun openLists(count: Int) { + repeat(count) { sink.beginList() } + } + + private fun writeScalars(target: ArgumentSink, count: Int) { + repeat(count) { + target.key("k$it") + target.scalar(it) + } + } + + /** Writes one value more than the value budget allows and returns the resulting drop. */ + private fun exhaustValues(): DropArgumentsException = + assertFailsWith { writeScalars(sink, count = MAX_ARGUMENT_VALUES + 1) } + + /** Rejects the entry for invalid structure, as a source would, and returns the resulting drop. */ + private fun rejectStructure(): DropArgumentsException = + assertFailsWith { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArgumentsException.STRUCTURE_WARNING) + } + + private fun nestedInLists(levels: Int, leaf: Any?): Any? { + var nested = leaf + repeat(levels) { nested = listOf(nested) } + return nested + } +} From 7e35dad6714db76ff22a9e2f0d33fb8a033812e3 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 11:35:20 +0100 Subject: [PATCH 2/2] feat(nav3): Add bounded and filtered property encoding Add KotlinxPropertiesEncoder, which encodes a @Serializable back stack entry's properties as maps, lists, and scalars, for the upcoming SerialNameAndProperties mapper. It writes through the same ArgumentSink as a custom mapper's map, so the same size and structural limits apply, and it also limits how deeply serializers nest. Values under property names or map keys on Sentry's sensitive denylist are replaced with [Filtered] without running their serializers. To share the denylist, HttpUtils.containsSensitiveDataKey becomes public. Co-Authored-By: Claude Opus 5.5 --- .../kotlinx/KotlinxPropertiesEncoder.kt | 469 +++++++++++++++ .../internal/common/ArgumentProtocol.kt | 7 + .../internal/common/TreeArgumentSink.kt | 16 + .../backstack/kotlinx/KotlinxEncoding.kt | 22 + .../KotlinxPropertiesEncoderFilteringTest.kt | 568 ++++++++++++++++++ .../KotlinxPropertiesEncoderLimitsTest.kt | 424 +++++++++++++ .../kotlinx/KotlinxPropertiesEncoderTest.kt | 508 ++++++++++++++++ .../backstack/kotlinx/KotlinxTestEntries.kt | 82 +++ .../kotlinx/SensitiveKeyFilterTest.kt | 200 ++++++ .../internal/common/HostArgumentSourceTest.kt | 2 + .../internal/common/TreeArgumentSinkTest.kt | 36 ++ sentry/api/sentry.api | 1 + .../main/java/io/sentry/util/HttpUtils.java | 6 +- 13 files changed, 2340 insertions(+), 1 deletion(-) create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt new file mode 100644 index 0000000000..1f02476943 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt @@ -0,0 +1,469 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.util.HttpUtils +import io.sentry.util.UrlUtils +import java.math.BigInteger +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerializationException +import kotlinx.serialization.SerializationStrategy +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.StructureKind +import kotlinx.serialization.encoding.AbstractEncoder +import kotlinx.serialization.encoding.CompositeEncoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.modules.EmptySerializersModule +import kotlinx.serialization.modules.SerializersModule + +/** + * Encodes the properties of a `@Serializable` back stack entry as maps, lists, and scalars for use + * as [SentryBackStackEntry.arguments]. + * + * **Encoding formats** + * + * Uses a custom tree encoder because `kotlinx-serialization-core` provides no output format and + * Nav3 apps may not include `kotlinx-serialization-json`. + * + * - Classes and objects become property maps. Objects without properties record no arguments. + * + * - Lists and sets become lists. Maps use stringified scalar keys, such as strings, numbers, or + * enums. Structured map keys are rejected, matching `kotlinx-serialization-json`'s defaults. + * + * - Enums use their serial names. Value classes use their underlying values. + * + * - Unsigned numbers (`UByte`, `UShort`, `UInt`, `ULong`) retain their unsigned values. + * + * - Polymorphic properties become `{"type": , "value": }`. + * + * - Entries encoded as scalars, such as by a custom string serializer, become `{"value": }`. + * + * - Properties marked `@Transient` are omitted. + * + * **Argument limits** + * + * Writes through [ArgumentSink], which enforces the same size and structural limits as for custom + * mappers. Violations throw [DropArgumentsException], bounding traversal and allocation for cyclic, + * deeply nested, or large entries. + * + * Custom serializers can recurse without nesting properties, bypassing the sink's depth limit. The + * encoder separately limits nested serializer calls to [MAX_SERIALIZER_NESTING]. + * + * **Sensitive data** + * + * Values under property names or map keys matching Sentry's + * [sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist) + * are replaced with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE] without invoking their serializers. + * + * [SensitiveKeyFilter] checks every key the encoders write, and the encoders read its decision to + * skip filtered values' serializers. [ValueEncoder.encodeInline] also checks value classes' + * underlying property names, which aren't written as keys. + * + * The denylist originates from filtering HTTP headers, cookies, and query parameters. This encoder + * applies it to navigation arguments as a baseline for sensitive-data filtering. + */ +internal object KotlinxPropertiesEncoder { + + /** Key for top-level values encoded without a map, such as by a custom serializer. */ + const val VALUE_KEY: String = "value" + + /** + * Encodes [value] with [serializer], writing its top-level properties to [sink]'s root map. + * + * Throws [SerializationException] when a value cannot be encoded, such as when a contextual or + * open polymorphic property has no registered serializer. Throws [DropArgumentsException] when an + * argument limit is exceeded. + * + * Limit failures, including [MAX_SERIALIZER_NESTING], are recorded in [ArgumentSink.failure]. A + * serializer can catch [DropArgumentsException] and then throw a different exception or return + * normally. Callers must check [ArgumentSink.failure] to determine whether to drop the arguments. + */ + fun encode(serializer: KSerializer, value: Any, sink: ArgumentSink) { + val filteredSink = SensitiveKeyFilter(sink) + RootEncoder(filteredSink, SerializerNesting(filteredSink)) + .encodeSerializableValue(serializer, value) + // Checked here rather than when the arguments are read, so that a custom serializer that stops + // part-way is reported as an encoding failure on every path. + filteredSink.checkComplete() + } + + /** Encodes a single value and writes it to [sink]. Structures are delegated to child encoders. */ + private open class ValueEncoder( + protected val sink: SensitiveKeyFilter, + protected val nesting: SerializerNesting, + ) : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + protected open fun put(value: Any?) { + sink.scalar(value) + } + + /** Replaces a filtered value with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE]. */ + protected open fun putFiltered() { + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + } + + override fun encodeSerializableValue(serializer: SerializationStrategy, value: T) { + nesting.enter() + try { + serializer.serialize(this, value) + } finally { + nesting.exit() + } + } + + override fun encodeValue(value: Any) { + put(value) + } + + override fun encodeNull() { + put(null) + } + + override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) { + put(enumDescriptor.getElementName(index)) + } + + override fun encodeInline(descriptor: SerialDescriptor): Encoder = + when { + descriptor.serialName in UNSIGNED_SERIAL_NAMES -> UnsignedEncoder(::put) + // A value class records only its underlying value, so its underlying property's name + // never reaches encodeElement. We check it here instead. + descriptor.hasSensitiveUnderlyingProperty() -> { + putFiltered() + DiscardingEncoder + } + else -> this + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder = + // The sink checks the depth as the structure begins, so a cyclic or deeply nested entry + // stops here instead of recursing until the stack overflows. + when (descriptor.kind) { + StructureKind.LIST -> { + sink.beginList() + ListEncoder(sink, nesting) + } + StructureKind.MAP -> { + sink.beginMap() + MapEncoder(sink, nesting) + } + else -> { + sink.beginMap() + ClassEncoder(sink, nesting) + } + } + } + + /** + * Encodes the entry itself. A class's properties, or a map's entries, are written to the sink's + * root map. Anything else (e.g., a custom serializer that encodes to a string) is written under + * [VALUE_KEY]. + */ + private class RootEncoder(sink: SensitiveKeyFilter, nesting: SerializerNesting) : + ValueEncoder(sink, nesting) { + + override fun put(value: Any?) { + sink.key(VALUE_KEY) + sink.scalar(value) + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder = + when (descriptor.kind) { + StructureKind.LIST -> { + sink.key(VALUE_KEY) + super.beginStructure(descriptor) + } + StructureKind.MAP -> MapEncoder(sink, nesting, isRoot = true) + else -> ClassEncoder(sink, nesting, isRoot = true) + } + } + + /** + * Writes the elements of a class, object, or polymorphic value as a map. + * + * If [isRoot] is true, uses the sink's already-open root map. + */ + private class ClassEncoder( + sink: SensitiveKeyFilter, + nesting: SerializerNesting, + private val isRoot: Boolean = false, + ) : ValueEncoder(sink, nesting) { + + override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean { + sink.key(descriptor.getElementName(index)) + if (sink.isNextValueSensitive) { + // Skipping the element keeps a sensitive value's own serializers from running. + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + return false + } + return true + } + + override fun endStructure(descriptor: SerialDescriptor) { + if (!isRoot) { + sink.end() + } + } + } + + /** Writes the elements of a list or set. */ + private class ListEncoder(sink: SensitiveKeyFilter, nesting: SerializerNesting) : + ValueEncoder(sink, nesting) { + + override fun endStructure(descriptor: SerialDescriptor) { + sink.end() + } + } + + /** + * Writes alternating map keys and values. If [isRoot] is true, uses the sink's already-open root + * map. + * + * Keys must be scalars and are recorded as strings, matching kotlinx-serialization-json's + * defaults. Stringifying structured keys could exhaust memory before the sink checks their size. + * + * Sensitive key text causes the value to be filtered. If the key itself was filtered because of a + * sensitive value-class property, its original text is unavailable, so the value is filtered too. + * Every such entry records the same substitute key and value, so only the first is written. + * + * Skipped entries write nothing, so the sink's limits can't bound how many are visited. A map + * that skips more than [MAX_ARGUMENT_VALUES] entries drops the arguments as over the value limit, + * which its entries would have broken unfiltered too. + */ + private class MapEncoder( + sink: SensitiveKeyFilter, + nesting: SerializerNesting, + private val isRoot: Boolean = false, + ) : ValueEncoder(sink, nesting) { + + private var isKey = true + private var isCurrentValueSensitive = false + private var hasFilteredKey = false + private var isCurrentEntrySkipped = false + private var skippedEntries = 0 + + override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean { + isKey = index % 2 == 0 + // Each key is encoded before its value, so the flags a key sets already apply to its value. + return when { + isKey -> { + isCurrentValueSensitive = false + isCurrentEntrySkipped = false + true + } + isCurrentEntrySkipped -> false + isCurrentValueSensitive -> { + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + false + } + else -> true + } + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { + if (isKey) { + throw SerializationException( + "Back stack entry has a map key that's a structure (${descriptor.serialName}). Only " + + "scalar map keys are supported.", + ) + } + return super.beginStructure(descriptor) + } + + override fun put(value: Any?) { + if (isKey) { + // The filter lets the sink reject oversized keys before its denylist scan allocates a + // lowercase copy. + sink.key(value.toString()) + isCurrentValueSensitive = sink.isNextValueSensitive + } else { + sink.scalar(value) + } + } + + override fun putFiltered() { + if (!isKey) { + super.putFiltered() + } else if (hasFilteredKey) { + if (++skippedEntries > MAX_ARGUMENT_VALUES) { + sink.reject(ArgumentDropReason.MAX_COUNT, DropArgumentsException.MAX_COUNT_WARNING) + } + isCurrentEntrySkipped = true + } else { + sink.key(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + hasFilteredKey = true + isCurrentValueSensitive = true + } + } + + override fun endStructure(descriptor: SerialDescriptor) { + if (!isRoot) { + sink.end() + } + } + } + + /** + * Maximum nested [Encoder.encodeSerializableValue] calls per entry. + * + * Allows room for property serializers and polymorphic or value-class wrappers within + * [MAX_ARGUMENT_DEPTH]. Guards against stack overflow when serializers recurse without nesting + * properties, which the argument depth limit can't detect. + */ + const val MAX_SERIALIZER_NESTING: Int = 64 + + /** + * Serial names of the unsigned number types, whose serializers encode them inline as their + * same-width signed storage value (e.g. `UInt.MAX_VALUE` as `-1`). + * + * Read from kotlinx.serialization's own serializers, so that the names can't drift from the + * library's. + */ + private val UNSIGNED_SERIAL_NAMES: Set = + listOf(UByte.serializer(), UShort.serializer(), UInt.serializer(), ULong.serializer()).mapTo( + HashSet(), + ) { + it.descriptor.serialName + } + + /** Whether this describes a value class whose underlying property's name is sensitive. */ + private fun SerialDescriptor.hasSensitiveUnderlyingProperty(): Boolean = + isInline && elementsCount == 1 && isSensitive(getElementName(0)) + + /** + * Discards a value class's underlying value after its filtered substitute has been recorded. + * + * Skips nested serializers, matching the handling of sensitive properties. + */ + private object DiscardingEncoder : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + override fun encodeValue(value: Any) = Unit + + override fun encodeNull() = Unit + + override fun encodeSerializableValue(serializer: SerializationStrategy, value: T) = Unit + + override fun encodeNullableSerializableValue( + serializer: SerializationStrategy, + value: T?, + ) = Unit + } + + /** + * Converts the signed storage value of an unsigned number back to its unsigned value and hands it + * to [put]. `ULong`s beyond `Long.MAX_VALUE` become [BigInteger]s. + */ + private class UnsignedEncoder(private val put: (Any?) -> Unit) : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + override fun encodeValue(value: Any) { + put( + when (value) { + is Byte -> value.toUByte().toInt() + is Short -> value.toUShort().toInt() + is Int -> value.toUInt().toLong() + is Long -> if (value >= 0) value else BigInteger(value.toULong().toString()) + else -> value + }, + ) + } + } + + /** + * Limits nested [Encoder.encodeSerializableValue] calls for one entry, rejecting it through + * [sink] when nesting exceeds [MAX_SERIALIZER_NESTING]. + * + * After any sink failure, [enter] rethrows that failure to prevent further serializer calls, even + * if a serializer catches the original exception. + */ + private class SerializerNesting(private val sink: ArgumentSink) { + + private var calls = 0 + + fun enter() { + sink.failure?.let { throw it } + if (++calls > MAX_SERIALIZER_NESTING) { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArgumentsException.STRUCTURE_WARNING) + } + } + + fun exit() { + calls-- + } + } + + /** + * Replaces scalar values under sensitive keys with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE] before + * forwarding them to [sink]. + * + * All encoders write through this filter to keep sensitive values out of the output. They read + * [isNextValueSensitive] after writing a key to skip the serializers of values that will be + * filtered, avoiding work and potential failures. As a result, no map or list starts under a + * sensitive key; one that does throws an [ArgumentProtocolException], which drops the entry's + * arguments rather than recording what's under the key. + * + * The encoders write values only through [scalar]. The inherited [computedScalar] computes a + * value before filtering it. + */ + internal class SensitiveKeyFilter(private val sink: ArgumentSink) : ArgumentSink { + + /** Whether the value written next is filtered, because the last key written is sensitive. */ + var isNextValueSensitive = false + private set + + override val failure: DropArgumentsException? + get() = sink.failure + + override fun beginMap() { + begin { sink.beginMap() } + } + + override fun beginList() { + begin { sink.beginList() } + } + + override fun key(name: String, describeDuplicate: () -> String) { + sink.key(name, describeDuplicate) + isNextValueSensitive = isSensitive(name) + } + + override fun scalar(value: Any?) { + sink.scalar(if (isNextValueSensitive) UrlUtils.SENSITIVE_DATA_SUBSTITUTE else value) + isNextValueSensitive = false + } + + override fun end() { + sink.end() + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing = + sink.reject(reason, warning) + + override fun checkComplete() { + sink.checkComplete() + } + + private inline fun begin(beginInSink: () -> Unit) { + if (isNextValueSensitive) { + throw ArgumentProtocolException("A map or list was started under a sensitive key.") + } + beginInSink() + } + } + + /** Whether [key] is sensitive and its value should be filtered. */ + private fun isSensitive(key: String): Boolean = HttpUtils.containsSensitiveDataKey(key) +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt index 353b0b1a6c..6cc5bba59a 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt @@ -118,6 +118,13 @@ internal interface ArgumentSink { * If a constraint was already violated, throws its `DropArgumentsException` instead. */ fun reject(reason: ArgumentDropReason, warning: String): Nothing + + /** + * Throws [ArgumentProtocolException] if a map or list is still open or a key has no value, so + * that a source that stops part-way doesn't record a partial tree as complete. Call after the + * last write. + */ + fun checkComplete() } /** diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt index 8e279732bb..a162cf1664 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSink.kt @@ -37,6 +37,12 @@ internal class TreeArgumentSink( override fun beginList() = guarded { begin(ArrayList()) } override fun key(name: String, describeDuplicate: () -> String) = guarded { + if (containers.last() !is Map<*, *>) { + throw ArgumentProtocolException("A key was written outside a map.") + } + if (pendingKey != null) { + throw ArgumentProtocolException("A key was written without a value.") + } budget.spendText(name) if ((containers.last() as? Map<*, *>)?.containsKey(name) == true) { throw DropArgumentsException(ArgumentDropReason.DUPLICATE_KEY, describeDuplicate()) @@ -69,9 +75,19 @@ internal class TreeArgumentSink( */ fun argumentsOrThrow(): Map { failure?.let { throw it } + checkComplete() return root } + override fun checkComplete() { + if (containers.size > 1) { + throw ArgumentProtocolException("A map or list was left open.") + } + if (pendingKey != null) { + throw ArgumentProtocolException("A key was written without a value.") + } + } + private fun begin(container: Any) { visitValue() add(container) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt new file mode 100644 index 0000000000..5bc3032c56 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt @@ -0,0 +1,22 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import kotlinx.serialization.KSerializer + +/** + * Encodes the properties of [value] with [serializer] into a map, with a budget of its own. Throws + * as [KotlinxPropertiesEncoder.encode] does. + */ +internal fun encodeToMap(serializer: KSerializer, value: T): Map { + val sink = TreeArgumentSink(ArgumentBudget()) + encodeInto(serializer, value, sink) + return sink.argumentsOrThrow() +} + +/** Encodes the properties of [value] with [serializer] into [sink]. */ +@Suppress("UNCHECKED_CAST") +internal fun encodeInto(serializer: KSerializer, value: T, sink: ArgumentSink) { + KotlinxPropertiesEncoder.encode(serializer as KSerializer, value, sink) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt new file mode 100644 index 0000000000..06c18f9b3d --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt @@ -0,0 +1,568 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.util.UrlUtils +import kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderFilteringTest { + + @Serializable + enum class Sort { + @SerialName("price_asc") PRICE_ASC, + NEWEST, + } + + @Serializable @JvmInline value class ProductId(val value: String) + + @Serializable data class WithSensitiveProperty(val query: String, val password: String) + + @Serializable data class WithNullableSecret(val id: String, val password: String?) + + @Serializable data class WithSensitiveMapKey(val params: Map) + + @Serializable + data class WithSensitiveKeysInList(val nested: Map>>) + + @Serializable @JvmInline value class HeaderName(val name: String) + + @Serializable data class WithHeaderNameMapKeys(val headers: Map) + + /** A value class whose underlying property's name (`key`) is sensitive. */ + @Serializable @JvmInline value class SensitiveHeaderName(val key: String) + + @Serializable + data class WithSensitiveValueClassMapKeys(val headers: Map) + + @Serializable data class WithSensitiveValueClassMapValues(val params: Map) + + /** A map key that encodes as a [SensitiveHeaderName] when [isSecret], or else as its [name]. */ + @Serializable(with = MixedHeaderSerializer::class) + data class MixedHeader(val name: String, val isSecret: Boolean) + + object MixedHeaderSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.MixedHeader", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: MixedHeader) { + if (value.isSecret) { + encoder.encodeSerializableValue( + SensitiveHeaderName.serializer(), + SensitiveHeaderName(value.name), + ) + } else { + encoder.encodeString(value.name) + } + } + + override fun deserialize(decoder: Decoder): MixedHeader = + MixedHeader(decoder.decodeString(), isSecret = false) + } + + @Serializable data class WithMixedHeaderMapKeys(val headers: Map) + + @Serializable + data class WithSerialNames( + @SerialName("position") val side: String, + @SerialName("apiKey") val label: String, + ) + + @Serializable @JvmInline value class TokenRef(val token: String) + + @Serializable + data class WithSensitiveValueClassPropertyName( + val productId: ProductId, + val sessionRef: ProductId, + ) + + @Serializable + data class WithSensitiveUnderlyingPropertyName(val productId: ProductId, val reference: TokenRef) + + @Serializable data class WithValueClassList(val references: List) + + @Serializable data class Credentials(val user: String) + + @Serializable @JvmInline value class CredentialsRef(val credentials: Credentials) + + @Serializable data class WithStructuredValueClass(val owner: CredentialsRef) + + @Serializable data class WithLargeSecret(val id: String, val refreshTokens: List) + + @Serializable data class WithLargeSecretMapValue(val params: Map>) + + @Serializable + data class WithUnencodableSecret( + val id: String, + @Serializable(with = ThrowingSerializer::class) val authToken: String, + ) + + @Serializable + data class WithUnencodableSecretMapValue( + val params: Map, + ) + + /** A value class whose underlying property's name (`token`) is sensitive. */ + @Serializable + @JvmInline + value class UnencodableSecretRef( + @Serializable(with = ThrowingSerializer::class) val token: String, + ) + + @Serializable data class WithUnencodableSecretRef(val id: String, val ref: UnencodableSecretRef) + + object ThrowingSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.Throwing", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: String): Unit = error("serializer ran") + + override fun deserialize(decoder: Decoder): String = decoder.decodeString() + } + + @Serializable @JvmInline value class Wrapped(val raw: String) + + @Serializable + data class SecretsProfile(val name: String, @SerialName("PASSWORD") val password: String) + + @Serializable data class SecretsItem(val sku: String, val apiKey: String) + + @Serializable + sealed interface SecretsOrigin { + @Serializable + @SerialName("login") + data class Login(val user: String, val authToken: String) : SecretsOrigin + } + + /** Places sensitive keys at every structural position the encoder supports. */ + @Serializable + data class SecretsEverywhere( + val query: String, + val authToken: String, + val password: String?, + val sort: Sort, + val profile: SecretsProfile, + val items: List, + val headers: Map, + val filters: Map>, + val rows: List>, + val grid: List>>, + val label: Wrapped, + val sessionSecret: Wrapped, + val origin: SecretsOrigin, + val authOrigin: SecretsOrigin, + val refreshTokens: List, + val credentials: Map, + val reference: TokenRef, + ) + + // Sensitive values + + @Test + fun `encode() - replaces the values of sensitive properties with the Filtered substitute`() { + val entry = WithSensitiveProperty(query = "shoes", password = "secret") + + val encoded = encodeToMap(WithSensitiveProperty.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("query" to "shoes", "password" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces a null sensitive property with the Filtered substitute`() { + val entry = WithNullableSecret(id = "1", password = null) + + val encoded = encodeToMap(WithNullableSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "password" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces the values of sensitive map keys with the Filtered substitute`() { + val entry = WithSensitiveMapKey(mapOf("query" to "shoes", "authToken" to "secret")) + + val encoded = encodeToMap(WithSensitiveMapKey.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "params" to mapOf("query" to "shoes", "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces the values of sensitive map keys in maps nested in lists with the Filtered substitute`() { + val entry = + WithSensitiveKeysInList( + nested = mapOf("items" to listOf(mapOf("authToken" to "secret", "query" to "shoes"))), + ) + + val encoded = encodeToMap(WithSensitiveKeysInList.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "nested" to + mapOf( + "items" to + listOf( + mapOf("authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE, "query" to "shoes"), + ), + ), + ), + ) + } + + @Test + fun `encode() - replaces the values of value class map keys whose text is sensitive with the Filtered substitute`() { + val entry = + WithHeaderNameMapKeys( + mapOf(HeaderName("Accept") to "json", HeaderName("Authorization") to "Bearer abc123"), + ) + + val encoded = encodeToMap(WithHeaderNameMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf("Accept" to "json", "Authorization" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces map entries with the Filtered substitute if their key's underlying property is sensitive`() { + val entry = + WithSensitiveValueClassMapKeys( + mapOf( + SensitiveHeaderName("Authorization") to "Bearer LEAKED-SECRET-1", + SensitiveHeaderName("X-Api-Key") to "LEAKED-SECRET-2", + // Filtered by its underlying property name even though its text isn't sensitive. + SensitiveHeaderName("Accept") to "LEAKED-SECRET-3", + ), + ) + + val encoded = encodeToMap(WithSensitiveValueClassMapKeys.serializer(), entry) + + // The filtered keys share one text, so they collapse to a single entry. + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf(UrlUtils.SENSITIVE_DATA_SUBSTITUTE to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + assertThat(leavesOf(encoded).values.filter { it.contains("LEAKED-SECRET") }).isEmpty() + } + + @Test + fun `encode() - replaces a map value with the Filtered substitute based only on its own key`() { + val entry = + WithMixedHeaderMapKeys( + mapOf( + MixedHeader("Accept", isSecret = false) to "VISIBLE-1", + MixedHeader("Authorization", isSecret = true) to "LEAKED-SECRET-1", + MixedHeader("Accept-Language", isSecret = false) to "VISIBLE-2", + ), + ) + + val encoded = encodeToMap(WithMixedHeaderMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf( + "Accept" to "VISIBLE-1", + UrlUtils.SENSITIVE_DATA_SUBSTITUTE to UrlUtils.SENSITIVE_DATA_SUBSTITUTE, + "Accept-Language" to "VISIBLE-2", + ), + ), + ) + } + + // Security regression test: a filtered key must not overwrite or merge with a visible entry. + @Test + fun `encode() - drops the arguments for a duplicate key when a filtered map key matches an unfiltered key's text`() { + val entry = + WithMixedHeaderMapKeys( + mapOf( + MixedHeader(UrlUtils.SENSITIVE_DATA_SUBSTITUTE, isSecret = false) to "VISIBLE", + MixedHeader("Authorization", isSecret = true) to "LEAKED-SECRET", + ), + ) + + val exception = + assertFailsWith { + encodeToMap(WithMixedHeaderMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + // Security regression test: a visible entry must not merge with an earlier filtered key. + @Test + fun `encode() - drops the arguments for a duplicate key when an unfiltered key matches an earlier filtered one`() { + val entry = + WithMixedHeaderMapKeys( + mapOf( + MixedHeader("Authorization", isSecret = true) to "LEAKED-SECRET", + MixedHeader(UrlUtils.SENSITIVE_DATA_SUBSTITUTE, isSecret = false) to "VISIBLE", + ), + ) + + val exception = + assertFailsWith { + encodeToMap(WithMixedHeaderMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - replaces map values with the Filtered substitute when their underlying property is sensitive`() { + val entry = WithSensitiveValueClassMapValues(mapOf("reference" to TokenRef("abc123"))) + + val encoded = encodeToMap(WithSensitiveValueClassMapValues.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("params" to mapOf("reference" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE))) + } + + @Test + fun `encode() - replaces the values of properties whose serial name is sensitive with the Filtered substitute`() { + val entry = WithSerialNames(side = "left", label = "secret") + + val encoded = encodeToMap(WithSerialNames.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("position" to "left", "apiKey" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces value class properties whose property name is sensitive with the Filtered substitute`() { + val entry = + WithSensitiveValueClassPropertyName( + productId = ProductId("p-1"), + sessionRef = ProductId("secret"), + ) + + val encoded = encodeToMap(WithSensitiveValueClassPropertyName.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("productId" to "p-1", "sessionRef" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces properties with the Filtered substitute when their underlying property is sensitive`() { + val entry = + WithSensitiveUnderlyingPropertyName(productId = ProductId("p-1"), reference = TokenRef("abc")) + + val encoded = encodeToMap(WithSensitiveUnderlyingPropertyName.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("productId" to "p-1", "reference" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces a top-level value with the Filtered substitute when its underlying property is sensitive`() { + val encoded = encodeToMap(TokenRef.serializer(), TokenRef("abc123")) + + assertThat(encoded) + .isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces list elements with the Filtered substitute when their underlying property is sensitive`() { + val entry = WithValueClassList(listOf(TokenRef("abc"), TokenRef("def"))) + + val encoded = encodeToMap(WithValueClassList.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "references" to + listOf(UrlUtils.SENSITIVE_DATA_SUBSTITUTE, UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces a wrapped structure with the Filtered substitute if its underlying property is sensitive`() { + val entry = WithStructuredValueClass(CredentialsRef(Credentials(user = "jane"))) + + val encoded = encodeToMap(WithStructuredValueClass.serializer(), entry) + + assertThat(encoded).isEqualTo(mapOf("owner" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - counts a sensitive property as one value regardless of its size`() { + val entry = + WithLargeSecret(id = "1", refreshTokens = List(MAX_ARGUMENT_VALUES + 1) { "token$it" }) + + val encoded = encodeToMap(WithLargeSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "refreshTokens" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - counts a sensitive map value as one value regardless of its size`() { + val entry = + WithLargeSecretMapValue( + params = mapOf("query" to listOf(1), "authToken" to List(MAX_ARGUMENT_VALUES + 1) { it }), + ) + + val encoded = encodeToMap(WithLargeSecretMapValue.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "params" to + mapOf("query" to listOf(1), "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - counts map entries with filtered keys as one value however many there are`() { + val entry = + WithSensitiveValueClassMapKeys( + (0..MAX_ARGUMENT_VALUES).associate { SensitiveHeaderName("header$it") to "secret$it" }, + ) + + val encoded = encodeToMap(WithSensitiveValueClassMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf(UrlUtils.SENSITIVE_DATA_SUBSTITUTE to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - drops the arguments when a map skips more filtered keys than the value limit`() { + val entry = + WithSensitiveValueClassMapKeys( + (0..MAX_ARGUMENT_VALUES + 1).associate { SensitiveHeaderName("header$it") to "secret$it" }, + ) + + val thrown = + assertFailsWith { + encodeToMap(WithSensitiveValueClassMapKeys.serializer(), entry) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + } + + @Test + fun `encode() - doesn't run the serializers of sensitive properties`() { + val entry = WithUnencodableSecret(id = "1", authToken = "secret") + + val encoded = encodeToMap(WithUnencodableSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - doesn't run the serializers of sensitive map values`() { + val entry = WithUnencodableSecretMapValue(mapOf("authToken" to "secret")) + + val encoded = encodeToMap(WithUnencodableSecretMapValue.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("params" to mapOf("authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE))) + } + + @Test + fun `encode() - doesn't run the serializers wrapped by a value class with a sensitive underlying property`() { + val entry = WithUnencodableSecretRef(id = "1", ref = UnencodableSecretRef("secret")) + + val encoded = encodeToMap(WithUnencodableSecretRef.serializer(), entry) + + assertThat(encoded).isEqualTo(mapOf("id" to "1", "ref" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + /** + * Deliberately structure-agnostic: rather than asserting the encoded shape, this walks the whole + * output looking for any secret at the structural positions [SecretsEverywhere] covers. It checks + * the end result only, so it passes whether the encoders' own checks or `SensitiveKeyFilter` + * filter each value; it can't tell whether an encoding path bypasses the encoders' checks. + */ + @Test + fun `encode() - doesn't record the values of sensitive keys anywhere in the encoded tree`() { + val entry = + SecretsEverywhere( + query = "VISIBLE-1", + authToken = "LEAKED-SECRET-1", + password = "LEAKED-SECRET-2", + sort = Sort.NEWEST, + profile = SecretsProfile(name = "VISIBLE-2", password = "LEAKED-SECRET-3"), + items = + listOf( + SecretsItem(sku = "VISIBLE-3", apiKey = "LEAKED-SECRET-4"), + SecretsItem(sku = "VISIBLE-4", apiKey = "LEAKED-SECRET-5"), + ), + headers = mapOf("accept" to "VISIBLE-5", "X-Api-Key" to "LEAKED-SECRET-6"), + filters = mapOf("color" to mapOf("shade" to "VISIBLE-6", "sessionId" to "LEAKED-SECRET-7")), + rows = listOf(mapOf("note" to "VISIBLE-7", "Bearer" to "LEAKED-SECRET-8")), + grid = listOf(listOf(mapOf("cell" to "VISIBLE-8", "jwt" to "LEAKED-SECRET-9"))), + label = Wrapped("VISIBLE-9"), + sessionSecret = Wrapped("LEAKED-SECRET-10"), + origin = SecretsOrigin.Login(user = "VISIBLE-10", authToken = "LEAKED-SECRET-11"), + authOrigin = SecretsOrigin.Login(user = "LEAKED-SECRET-12", authToken = "LEAKED-SECRET-13"), + refreshTokens = listOf("LEAKED-SECRET-14", "LEAKED-SECRET-15"), + credentials = mapOf("user" to "LEAKED-SECRET-16"), + reference = TokenRef("LEAKED-SECRET-17"), + ) + + val leaves = leavesOf(encodeToMap(SecretsEverywhere.serializer(), entry)) + + assertThat(leaves.filterValues { it.contains("LEAKED-SECRET") }).isEmpty() + assertThat(leaves.values).containsAtLeastElementsIn((1..10).map { "VISIBLE-$it" } + "NEWEST") + // authToken, password, PASSWORD, apiKey (x2), X-Api-Key, sessionId, Bearer, jwt, + // sessionSecret, origin's authToken, authOrigin, refreshTokens, credentials, and reference + // (whose value class wraps a token). + assertThat(leaves.values.count { it == UrlUtils.SENSITIVE_DATA_SUBSTITUTE }).isEqualTo(15) + } + + /** + * Flattens [value] into its map keys and scalar values, stringified and keyed by their path, so + * that a failing assertion names where each one sits. + */ + private fun leavesOf( + value: Any?, + path: String = "", + leaves: MutableMap = LinkedHashMap(), + ): Map { + when (value) { + is Map<*, *> -> + value.forEach { (key, child) -> + leaves["$path.$key (key)"] = key.toString() + leavesOf(child, "$path.$key", leaves) + } + is Iterable<*> -> + value.forEachIndexed { index, child -> leavesOf(child, "$path[$index]", leaves) } + else -> leaves[path] = value.toString() + } + return leaves + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt new file mode 100644 index 0000000000..0156f1042c --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt @@ -0,0 +1,424 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.common.budgetWithValuesRemaining +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 kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderLimitsTest { + + @Serializable + class SelfReferencing { + var next: SelfReferencing? = null + } + + /** Nests a polymorphic and a value class serializer at every other level. */ + @Serializable @JvmInline value class LayerRef(val layer: Layer) + + @Serializable + sealed interface Layer { + @Serializable @SerialName("node") data class Node(val child: LayerRef) : Layer + + @Serializable @SerialName("leaf") data class Leaf(val value: String) : Layer + } + + /** + * Encodes a link with [LinkSerializer], and if that throws [DropArgumentsException], records it + * and encodes a fallback with [recover] instead. + */ + internal class RecoveringLinkSerializer(private val recover: (Encoder) -> Unit) : + KSerializer { + var caught: DropArgumentsException? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.RecoveringLink", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + try { + encoder.encodeSerializableValue(LinkSerializer, value) + } catch (e: DropArgumentsException) { + caught = e + recover(encoder) + } + } + + override fun deserialize(decoder: Decoder): Link = Link(decoder.decodeString()) + } + + /** A value that [CatchingWriteSerializer] encodes. */ + private class Code(val code: String) + + /** Writes nothing, counting its calls in [calls]. */ + private class WritesNothingSerializer : KSerializer { + var calls = 0 + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.WritesNothing", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: String) { + calls++ + } + + override fun deserialize(decoder: Decoder): String = throw UnsupportedOperationException() + } + + /** + * Writes the code, recording a [DropArgumentsException] that throws in [caught], then encodes a + * fallback with [fallback]. + */ + private class CatchingWriteSerializer(private val fallback: KSerializer) : + KSerializer { + var caught: DropArgumentsException? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.CatchingWrite", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Code) { + try { + encoder.encodeString(value.code) + } catch (e: DropArgumentsException) { + caught = e + } + encoder.encodeSerializableValue(fallback, "fallback") + } + + override fun deserialize(decoder: Decoder): Code = throw UnsupportedOperationException() + } + + // Character limit + + @Test + fun `encode() - encodes an entry with the maximum number of characters, counting property names`() { + // The Box's property name and its value together are the maximum. + val value = "x".repeat(MAX_ARGUMENT_CHARACTERS - "value".length) + val (serializer, entry) = boxed(depth = 1, value = value, String.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to value)) + } + + @Test + fun `encode() - drops the arguments for the character limit when property names put an entry one character over`() { + val value = "x".repeat(MAX_ARGUMENT_CHARACTERS - "value".length + 1) + val (serializer, entry) = boxed(depth = 1, value = value, String.serializer()) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(exception.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) + } + + @Test + fun `encode() - encodes a map key of the maximum number of characters`() { + // A top-level map has no property names, and Int values, so the key is the only text counted. + val value = mapOf("k".repeat(MAX_ARGUMENT_CHARACTERS) to 1) + val (serializer, entry) = + boxed(depth = 0, value = value, MapSerializer(String.serializer(), Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(value) + } + + @Test + fun `encode() - drops the arguments for the character limit when a map key is too long`() { + val (serializer, entry) = + boxed( + depth = 0, + value = mapOf("k".repeat(MAX_ARGUMENT_CHARACTERS + 1) to 1), + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(exception.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) + } + + // Depth limit + + @Test + fun `encode() - encodes a value at the maximum depth`() { + val (serializer, entry) = boxed(depth = MAX_ARGUMENT_DEPTH, value = "leaf", String.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = "leaf")) + } + + @Test + fun `encode() - encodes polymorphic and value class properties at the maximum depth`() { + // The leaf's value sits at depth 2, and each node nests its child two levels deeper. + val nodes = (MAX_ARGUMENT_DEPTH - 2) / 2 + var layer: Layer = Layer.Leaf("leaf") + repeat(nodes) { layer = Layer.Node(LayerRef(layer)) } + + val encoded = encodeToMap(LayerRef.serializer(), LayerRef(layer)) + + var expected: Map = mapOf("type" to "leaf", "value" to mapOf("value" to "leaf")) + repeat(nodes) { expected = mapOf("type" to "node", "value" to mapOf("child" to expected)) } + assertThat(encoded).isEqualTo(expected) + } + + @Test + fun `encode() - drops the arguments for invalid structure when a value is nested past the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH + 1, value = "leaf", String.serializer()) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for a list, so an empty list fits at the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH, value = emptyList(), ListSerializer(String.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded) + .isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = emptyList())) + } + + @Test + fun `encode() - adds one level of depth for a list, so a list's elements can't be past the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH, value = listOf("a"), ListSerializer(String.serializer())) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for a map, so a map's values can't be past the maximum depth`() { + val (serializer, entry) = + boxed( + depth = MAX_ARGUMENT_DEPTH, + value = mapOf("a" to 1), + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for an object, so an object without properties fits at the maximum depth`() { + val (serializer, entry) = boxed(depth = MAX_ARGUMENT_DEPTH, value = Home, Home.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded) + .isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = emptyMap())) + } + + @Test + fun `encode() - stops at the depth limit when an entry references itself`() { + val entry = SelfReferencing().apply { next = this } + + val exception = + assertFailsWith { encodeToMap(SelfReferencing.serializer(), entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + // Value limit + + @Test + fun `encode() - encodes an entry with the maximum number of values`() { + // The list property and its elements are the maximum. + val values = List(MAX_ARGUMENT_VALUES - 1) { it } + val (serializer, entry) = boxed(depth = 1, value = values, ListSerializer(Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to values)) + } + + @Test + fun `encode() - drops the arguments for count when an entry has one value too many`() { + val (serializer, entry) = + boxed(depth = 1, value = List(MAX_ARGUMENT_VALUES) { it }, ListSerializer(Int.serializer())) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(exception.warning).isEqualTo(DropArgumentsException.MAX_COUNT_WARNING) + } + + @Test + fun `encode() - doesn't count map keys as values`() { + // The map property and its values are the maximum; counting the keys would exceed it. + val values = (0 until MAX_ARGUMENT_VALUES - 1).associate { "item$it" to it } + val (serializer, entry) = + boxed(depth = 1, value = values, MapSerializer(String.serializer(), Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to values)) + } + + @Test + fun `encode() - drops the arguments for count when a map has one value too many`() { + val (serializer, entry) = + boxed( + depth = 1, + value = (0 until MAX_ARGUMENT_VALUES).associate { "item$it" to it }, + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(exception.warning).isEqualTo(DropArgumentsException.MAX_COUNT_WARNING) + } + + // Serializer nesting limit + + @Test + fun `encode() - encodes custom serializers nested up to the maximum number of calls`() { + // The top-level serializer is the first call, and each next link nests one more. + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val encoded = encodeToMap(LinkSerializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to "leaf")) + } + + @Test + fun `encode() - counts only nested serializer calls toward the nesting limit`() { + // Each element's serializer call returns before the next element's begins. + val values = List(KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) { it } + + val encoded = encodeToMap(ListSerializer(Int.serializer()), values) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to values)) + } + + @Test + fun `encode() - drops the arguments for invalid structure when custom serializers nest too many calls deep`() { + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) + + val exception = assertFailsWith { encodeToMap(LinkSerializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - drops the arguments for invalid structure when a custom serializer recurses through a cycle`() { + val entry = Link("leaf").apply { next = this } + + val exception = assertFailsWith { encodeToMap(LinkSerializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - records the nesting failure on the sink`() { + val sink = TreeArgumentSink(ArgumentBudget()) + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) + + val exception = + assertFailsWith { encodeInto(LinkSerializer, entry, sink) } + + assertThat(sink.failure).isSameInstanceAs(exception) + } + + @Test + fun `encode() - keeps failing when a serializer catches the nesting failure and calls another serializer`() { + // The recovering serializer is the first call, so its link chain nests one call too many. + val serializer = RecoveringLinkSerializer { + it.encodeSerializableValue(String.serializer(), "fallback") + } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - throws the caught nesting failure when a serializer catches it and writes a value directly`() { + val serializer = RecoveringLinkSerializer { it.encodeString("fallback") } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArgumentsException.STRUCTURE_WARNING) + } + + @Test + fun `encode() - keeps the nesting failure on the sink when a serializer catches it and returns`() { + val sink = TreeArgumentSink(ArgumentBudget()) + val serializer = RecoveringLinkSerializer {} + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + encodeInto(serializer, entry, sink) + + val exception = assertFailsWith { sink.argumentsOrThrow() } + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `encode() - propagates a serializer's exception in place of the nesting failure, which the sink keeps`() { + val error = SerializationException("replaced") + val sink = TreeArgumentSink(ArgumentBudget()) + val serializer = RecoveringLinkSerializer { throw error } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val thrown = assertFailsWith { encodeInto(serializer, entry, sink) } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(sink.failure).isSameInstanceAs(serializer.caught) + assertThat(sink.failure?.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `encode() - doesn't run another serializer after a serializer catches the sink's broken limit`() { + val fallback = WritesNothingSerializer() + val serializer = CatchingWriteSerializer(fallback) + val sink = TreeArgumentSink(budgetWithValuesRemaining(0)) + + val exception = + assertFailsWith { encodeInto(serializer, Code("x"), sink) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(fallback.calls).isEqualTo(0) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt new file mode 100644 index 0000000000..a6a49bd24f --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt @@ -0,0 +1,508 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import java.math.BigInteger +import kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Polymorphic +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.Transient +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderTest { + + @Serializable + data class Product( + val name: String, + val inStock: Boolean, + val price: Double, + val grade: Char, + val quantity: Long, + val note: String?, + ) + + @Serializable data class Filters(val minPrice: Int, val brands: List) + + @Serializable data class WithNestedClass(val query: String, val filters: Filters) + + @Serializable data class WithCollections(val names: List, val tags: Set) + + @Serializable + enum class Sort { + @SerialName("price_asc") PRICE_ASC, + NEWEST, + } + + @Serializable data class WithEnums(val primary: Sort, val secondary: Sort) + + @Serializable @JvmInline value class ProductId(val value: String) + + @Serializable data class WithValueClass(val productId: ProductId) + + @Serializable data class WithDefault(val query: String, val page: Int = 1) + + @Serializable + data class WithTransient(val query: String, @Transient val cached: String = "not recorded") + + @Serializable + sealed interface Origin { + @Serializable @SerialName("search") data class Search(val query: String) : Origin + + @Serializable @SerialName("deeplink") data object DeepLink : Origin + } + + @Serializable data class WithOrigin(val productId: String, val origin: Origin) + + @Serializable(with = CustomSerializer::class) data class CustomSerialized(val id: String) + + object CustomSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: CustomSerialized) { + encoder.encodeString(value.id) + } + + override fun deserialize(decoder: Decoder): CustomSerialized = + CustomSerialized(decoder.decodeString()) + } + + @Serializable + data class WithUnsignedNumbers( + val uByte: UByte, + val uShort: UShort, + val uInt: UInt, + val uLong: ULong, + ) + + @Serializable data class WithULong(val uLong: ULong) + + @Serializable + data class WithSignedNumbers(val byte: Byte, val short: Short, val int: Int, val long: Long) + + @Serializable data class WithIntMapKeys(val counts: Map) + + @Serializable + data class WithEncodedMapKeys(val bySort: Map, val byRank: Map) + + @Serializable data class WithNullableMapKeys(val counts: Map) + + @Serializable + data class WithWrappedMapKeys( + val byProduct: Map, + val byCustom: Map, + ) + + /** A key that's recorded by its [name] alone, so keys that differ only in [version] collide. */ + @Serializable(with = VersionedNameSerializer::class) + data class VersionedName(val name: String, val version: Int) + + object VersionedNameSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.VersionedName", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: VersionedName) { + encoder.encodeString(value.name) + } + + override fun deserialize(decoder: Decoder): VersionedName = + VersionedName(decoder.decodeString(), version = 0) + } + + @Serializable data class WithVersionedNameMapKeys(val byName: Map) + + @Serializable data class Point(val x: Int) + + @Serializable data class WithPointMapKeys(val byPoint: Map) + + @Serializable @JvmInline value class PointRef(val point: Point) + + @Serializable data class WithPointRefMapKeys(val byPointRef: Map) + + @Serializable data class WithListMapKeys(val byList: Map, Int>) + + @Serializable data class WithMapMapKeys(val byMap: Map, Int>) + + @Serializable data class WithOriginMapKeys(val byOrigin: Map) + + @Serializable data class WithNestedPointMapKeys(val groups: List>) + + interface OpenOrigin + + @Serializable data class WithOpenPolymorphic(val id: String, @Polymorphic val origin: OpenOrigin) + + // Encoded shapes + + @Test + fun `encode() - encodes a class as a map from property name to value`() { + val entry = + Product( + name = "shoes", + inStock = false, + price = 0.5, + grade = 'A', + quantity = 3L, + note = null, + ) + + val encoded = encodeToMap(Product.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "name" to "shoes", + "inStock" to false, + "price" to 0.5, + "grade" to "A", + "quantity" to 3L, + "note" to null, + ), + ) + } + + @Test + fun `encode() - encodes a nested class as a nested map`() { + val entry = WithNestedClass("shoes", Filters(minPrice = 10, brands = listOf("a"))) + + val encoded = encodeToMap(WithNestedClass.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("query" to "shoes", "filters" to mapOf("minPrice" to 10, "brands" to listOf("a"))), + ) + } + + @Test + fun `encode() - encodes lists and sets as lists`() { + val entry = WithCollections(names = listOf("a", null), tags = setOf("new", "sale")) + + val encoded = encodeToMap(WithCollections.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("names" to listOf("a", null), "tags" to listOf("new", "sale"))) + } + + @Test + fun `encode() - encodes enums by their serial name`() { + val encoded = encodeToMap(WithEnums.serializer(), WithEnums(Sort.PRICE_ASC, Sort.NEWEST)) + + assertThat(encoded).isEqualTo(mapOf("primary" to "price_asc", "secondary" to "NEWEST")) + } + + @Test + fun `encode() - encodes value classes by their underlying value`() { + val encoded = encodeToMap(WithValueClass.serializer(), WithValueClass(ProductId("p-1"))) + + assertThat(encoded).isEqualTo(mapOf("productId" to "p-1")) + } + + @Test + fun `encode() - encodes properties that have their default values`() { + val encoded = encodeToMap(WithDefault.serializer(), WithDefault(query = "shoes")) + + assertThat(encoded).isEqualTo(mapOf("query" to "shoes", "page" to 1)) + } + + @Test + fun `encode() - omits @Transient properties`() { + val encoded = encodeToMap(WithTransient.serializer(), WithTransient(query = "shoes")) + + assertThat(encoded).isEqualTo(mapOf("query" to "shoes")) + } + + @Test + fun `encode() - encodes polymorphic properties as their serial name and value`() { + val search = encodeToMap(WithOrigin.serializer(), WithOrigin("p-1", Origin.Search("shoes"))) + val deepLink = encodeToMap(WithOrigin.serializer(), WithOrigin("p-1", Origin.DeepLink)) + + assertThat(search) + .isEqualTo( + mapOf( + "productId" to "p-1", + "origin" to mapOf("type" to "search", "value" to mapOf("query" to "shoes")), + ), + ) + assertThat(deepLink) + .isEqualTo( + mapOf( + "productId" to "p-1", + "origin" to mapOf("type" to "deeplink", "value" to emptyMap()), + ), + ) + } + + @Test + fun `encode() - encodes an object without properties as an empty map`() { + val encoded = encodeToMap(Home.serializer(), Home) + + assertThat(encoded).isEmpty() + } + + @Test + fun `encode() - wraps a top-level value that doesn't encode to a structure under the value key`() { + val encoded = encodeToMap(CustomSerializer, CustomSerialized("abc")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "abc")) + } + + @Test + fun `encode() - wraps a top-level list under the value key`() { + val encoded = encodeToMap(ListSerializer(String.serializer()), listOf("a", "b")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to listOf("a", "b"))) + } + + @Test + fun `encode() - encodes a top-level map's entries as the arguments`() { + val encoded = + encodeToMap(MapSerializer(String.serializer(), Int.serializer()), mapOf("page" to 2)) + + assertThat(encoded).isEqualTo(mapOf("page" to 2)) + } + + @Test + fun `encode() - wraps a top-level value class's underlying value under the value key`() { + val encoded = encodeToMap(ProductId.serializer(), ProductId("p-1")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "p-1")) + } + + @Test + fun `encode() - wraps a top-level enum's serial name under the value key`() { + val encoded = encodeToMap(Sort.serializer(), Sort.PRICE_ASC) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "price_asc")) + } + + @Test + fun `encode() - encodes a top-level polymorphic value's serial name and value as the arguments`() { + val encoded = encodeToMap(Origin.serializer(), Origin.Search("shoes")) + + assertThat(encoded).isEqualTo(mapOf("type" to "search", "value" to mapOf("query" to "shoes"))) + } + + // Numbers + + @Test + fun `encode() - encodes unsigned numbers by their unsigned value`() { + val entry = + WithUnsignedNumbers( + uByte = UByte.MAX_VALUE, + uShort = UShort.MAX_VALUE, + uInt = UInt.MAX_VALUE, + uLong = Long.MAX_VALUE.toULong(), + ) + + val encoded = encodeToMap(WithUnsignedNumbers.serializer(), entry) + + val uByteMax: Int = 255 + val uShortMax: Int = 65_535 + val uIntMax: Long = 4_294_967_295L + assertThat(encoded) + .isEqualTo( + mapOf( + "uByte" to uByteMax, + "uShort" to uShortMax, + "uInt" to uIntMax, + "uLong" to Long.MAX_VALUE, + ), + ) + } + + @Test + fun `encode() - wraps a top-level unsigned number's unsigned value under the value key`() { + val encoded = encodeToMap(UInt.serializer(), UInt.MAX_VALUE) + + val uIntMax: Long = 4_294_967_295L + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to uIntMax)) + } + + @Test + fun `encode() - encodes a ULong above Long MAX_VALUE as a BigInteger`() { + val encoded = encodeToMap(WithULong.serializer(), WithULong(ULong.MAX_VALUE)) + + assertThat(encoded).isEqualTo(mapOf("uLong" to BigInteger("18446744073709551615"))) + } + + @Test + fun `encode() - encodes negative signed numbers as-is`() { + val entry = WithSignedNumbers(byte = -1, short = -1, int = -1, long = -1L) + + val encoded = encodeToMap(WithSignedNumbers.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("byte" to (-1).toByte(), "short" to (-1).toShort(), "int" to -1, "long" to -1L), + ) + } + + // Map keys + + @Test + fun `encode() - converts map keys to strings`() { + val encoded = encodeToMap(WithIntMapKeys.serializer(), WithIntMapKeys(mapOf(1 to 2L))) + + assertThat(encoded).isEqualTo(mapOf("counts" to mapOf("1" to 2L))) + } + + @Test + fun `encode() - converts enum and unsigned map keys to strings of their encoded values`() { + val entry = + WithEncodedMapKeys(bySort = mapOf(Sort.PRICE_ASC to 1), byRank = mapOf(UInt.MAX_VALUE to 2)) + + val encoded = encodeToMap(WithEncodedMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("bySort" to mapOf("price_asc" to 1), "byRank" to mapOf("4294967295" to 2)), + ) + } + + @Test + fun `encode() - converts a null map key to the string null`() { + val encoded = + encodeToMap(WithNullableMapKeys.serializer(), WithNullableMapKeys(mapOf(null to 1))) + + assertThat(encoded).isEqualTo(mapOf("counts" to mapOf("null" to 1))) + } + + @Test + fun `encode() - converts value class and custom serializer map keys to strings`() { + val entry = + WithWrappedMapKeys( + byProduct = mapOf(ProductId("p-1") to 1), + byCustom = mapOf(CustomSerialized("c-1") to 2), + ) + + val encoded = encodeToMap(WithWrappedMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("byProduct" to mapOf("p-1" to 1), "byCustom" to mapOf("c-1" to 2))) + } + + @Test + fun `encode() - drops the arguments for a duplicate key when a null map key and the string null are both keys`() { + val entry = WithNullableMapKeys(mapOf(null to 1, "null" to 2)) + + val exception = + assertFailsWith { + encodeToMap(WithNullableMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - drops the arguments for a duplicate key when a custom serializer encodes two keys as one string`() { + val entry = + WithVersionedNameMapKeys(mapOf(VersionedName("home", 1) to 1, VersionedName("home", 2) to 2)) + + val exception = + assertFailsWith { + encodeToMap(WithVersionedNameMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - throws for a class map key`() { + val entry = WithPointMapKeys(mapOf(Point(1) to 2)) + + assertFailsWith { + encodeToMap(WithPointMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a value class map key that wraps a class`() { + val entry = WithPointRefMapKeys(mapOf(PointRef(Point(1)) to 2)) + + assertFailsWith { + encodeToMap(WithPointRefMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a list map key`() { + // Converting this key to a string would copy the one 16 KiB string 4,000 times (~64 MiB). + val longString = "a".repeat(16 * 1024) + val entry = WithListMapKeys(mapOf(List(4_000) { longString } to 1)) + + assertFailsWith { + encodeToMap(WithListMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a map map key`() { + val entry = WithMapMapKeys(mapOf(mapOf("a" to 1) to 2)) + + assertFailsWith { + encodeToMap(WithMapMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a polymorphic map key`() { + val entry = WithOriginMapKeys(mapOf(Origin.Search("shoes") to 1)) + + assertFailsWith { + encodeToMap(WithOriginMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a class map key in a map nested in a list`() { + val entry = WithNestedPointMapKeys(listOf(mapOf(Point(1) to 2))) + + assertFailsWith { + encodeToMap(WithNestedPointMapKeys.serializer(), entry) + } + } + + // Unsupported properties + + @Test + fun `encode() - throws for a contextual property without a registered serializer`() { + val entry = WithContextual("1", Unregistered("2")) + + assertFailsWith { + encodeToMap(WithContextual.serializer(), entry) + } + } + + @Test + fun `encode() - throws for an open polymorphic property without a registered serializer`() { + val entry = WithOpenPolymorphic("1", object : OpenOrigin {}) + + assertFailsWith { + encodeToMap(WithOpenPolymorphic.serializer(), entry) + } + } + + // Serializer failures + + @Test + fun `encode() - propagates a serializer's exception unchanged`() { + val error = IllegalStateException("boom") + val serializer = RecordingSerializer(Detail.serializer()).apply { this.error = error } + + val thrown = assertFailsWith { encodeToMap(serializer, Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt index d06ebe92ab..342f57f53b 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -2,9 +2,13 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx +import kotlinx.serialization.Contextual import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder @@ -14,9 +18,87 @@ import kotlinx.serialization.encoding.Encoder @Serializable @SerialName("Search") internal data class Search(val query: String) +internal class Unregistered(val id: String) + +@Serializable +@SerialName("WithContextual") +internal data class WithContextual(val id: String, @Contextual val other: Unregistered) + /** A serializer for tests that only read its descriptor, e.g., to name an entry. */ internal abstract class NamingOnlySerializer : KSerializer { override fun serialize(encoder: Encoder, value: T) = throw UnsupportedOperationException() override fun deserialize(decoder: Decoder): T = throw UnsupportedOperationException() } + +@Serializable internal data class Box(val value: T) + +/** Wraps [value] in [depth] nested [Box]es, so that [value] sits at [depth]. */ +internal fun boxed( + depth: Int, + value: T, + serializer: KSerializer, +): Pair, Any> { + var boxedSerializer: KSerializer<*> = serializer + var boxedValue: Any? = value + repeat(depth) { + @Suppress("UNCHECKED_CAST") + boxedSerializer = Box.serializer(boxedSerializer as KSerializer) + boxedValue = Box(boxedValue) + } + @Suppress("UNCHECKED_CAST") + return boxedSerializer as KSerializer to boxedValue!! +} + +/** The arguments the encoder produces for [boxed] when within its limits. */ +internal fun boxedArguments(depth: Int, value: Any?): Map { + var arguments: Any? = value + repeat(depth) { arguments = mapOf("value" to arguments) } + @Suppress("UNCHECKED_CAST") + return arguments as Map +} + +internal class Link(val id: String) { + var next: Link? = null +} + +/** + * Encodes a link as the id of the last link in its chain, encoding each next link in place of its + * own, so the recursion never begins a structure. + */ +internal object LinkSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.Link", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + val next = value.next + if (next != null) encoder.encodeSerializableValue(this, next) + else encoder.encodeString(value.id) + } + + override fun deserialize(decoder: Decoder): Link = Link(decoder.decodeString()) +} + +/** Chains [length] [Link]s, the last of which has the id `leaf`. */ +internal fun linked(length: Int): Link { + var link = Link("leaf") + repeat(length - 1) { index -> link = Link("link-$index").apply { next = link } } + return link +} + +/** + * Delegates to [delegate], recording each serialized value and throwing [error], if set, for the + * values [failsFor] accepts. + */ +internal class RecordingSerializer(private val delegate: KSerializer) : + KSerializer by delegate { + val serialized = mutableListOf() + var error: Throwable? = null + var failsFor: (T) -> Boolean = { true } + + override fun serialize(encoder: Encoder, value: T) { + serialized += value + error?.takeIf { failsFor(value) }?.let { throw it } + delegate.serialize(encoder, value) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt new file mode 100644 index 0000000000..21223bcc59 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt @@ -0,0 +1,200 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxPropertiesEncoder.SensitiveKeyFilter +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.util.UrlUtils.SENSITIVE_DATA_SUBSTITUTE +import kotlin.test.assertFailsWith +import org.junit.Test + +class SensitiveKeyFilterTest { + + private val sink = TreeArgumentSink(ArgumentBudget()) + private val filter = SensitiveKeyFilter(sink) + + // Keys, values, maps, and lists under non-sensitive keys + + @Test + fun `passes keys, scalars, maps, and lists under non-sensitive keys to the sink`() { + filter.key("query") + filter.scalar("shoes") + filter.key("filters") + filter.beginMap() + filter.key("brands") + filter.beginList() + filter.scalar("a") + filter.end() + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo(mapOf("query" to "shoes", "filters" to mapOf("brands" to listOf("a")))) + } + + // Next value sensitivity + + @Test + fun `isNextValueSensitive - is true after a sensitive key`() { + filter.key("authToken") + + assertThat(filter.isNextValueSensitive).isTrue() + } + + @Test + fun `isNextValueSensitive - is false after a non-sensitive key`() { + filter.key("query") + + assertThat(filter.isNextValueSensitive).isFalse() + } + + @Test + fun `isNextValueSensitive - is false once the sensitive key's value is written`() { + filter.key("authToken") + filter.scalar("secret") + + assertThat(filter.isNextValueSensitive).isFalse() + } + + // Scalars + + @Test + fun `scalar() - writes the substitute in place of a scalar under a sensitive key`() { + filter.key("password") + filter.scalar("hunter2") + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("password" to SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `scalar() - writes a scalar under a non-sensitive key that follows a sensitive key`() { + filter.key("password") + filter.scalar("hunter2") + filter.key("page") + filter.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("password" to SENSITIVE_DATA_SUBSTITUTE, "page" to 2)) + } + + @Test + fun `scalar() - writes list elements under a non-sensitive key, even if they look like sensitive keys`() { + filter.key("tags") + filter.beginList() + filter.scalar("password") + filter.scalar("token") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("tags" to listOf("password", "token"))) + } + + @Test + fun `scalar() - writes the substitute under the sensitive keys of maps in a list`() { + filter.key("rows") + filter.beginList() + filter.beginMap() + filter.key("jwt") + filter.scalar("t-1") + filter.key("note") + filter.scalar("visible") + filter.end() + filter.scalar("plain") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf( + "rows" to listOf(mapOf("jwt" to SENSITIVE_DATA_SUBSTITUTE, "note" to "visible"), "plain"), + ), + ) + } + + @Test + fun `beginMap() - throws without writing when a map starts under a sensitive key`() { + filter.key("credentials") + + assertFailsWith { filter.beginMap() } + sink.scalar(null) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("credentials" to null)) + } + + @Test + fun `beginList() - throws without writing when a list starts under a sensitive key`() { + filter.key("refreshTokens") + + assertFailsWith { filter.beginList() } + sink.scalar(null) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("refreshTokens" to null)) + } + + @Test + fun `beginMap() - writes a map under a non-sensitive key that follows a filtered scalar`() { + filter.key("password") + filter.scalar("hunter2") + filter.key("filters") + filter.beginMap() + filter.key("color") + filter.scalar("red") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf("password" to SENSITIVE_DATA_SUBSTITUTE, "filters" to mapOf("color" to "red")), + ) + } + + // Rejected limits + + @Test + fun `reject() - rejects the limit on the sink`() { + val drop = + assertFailsWith { + filter.reject( + ArgumentDropReason.INVALID_STRUCTURE, + DropArgumentsException.STRUCTURE_WARNING, + ) + } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(sink.failure).isSameInstanceAs(drop) + } + + // Failure + + @Test + fun `failure - is null while the sink has no failure`() { + filter.key("query") + filter.scalar("shoes") + + val failure = filter.failure + + assertThat(failure).isNull() + } + + @Test + fun `failure - is the sink's failure`() { + val drop = + assertFailsWith { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArgumentsException.STRUCTURE_WARNING) + } + + val failure = filter.failure + + assertThat(failure).isSameInstanceAs(drop) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt index addca86f76..5284038a77 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/HostArgumentSourceTest.kt @@ -587,5 +587,7 @@ class HostArgumentSourceTest { events += Reject(reason) throw DropArgumentsException(reason, warning) } + + override fun checkComplete() = Unit } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt index 89fb5b5117..1611fff77e 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/TreeArgumentSinkTest.kt @@ -182,6 +182,39 @@ class TreeArgumentSinkTest { assertFailsWith { sink.scalar(1) } } + // Incomplete writes + + @Test + fun `key() - throws ArgumentProtocolException in a list`() { + sink.key("list") + sink.beginList() + + assertFailsWith { sink.key("id") } + } + + @Test + fun `key() - throws ArgumentProtocolException when the previous key has no value`() { + sink.key("first") + + assertFailsWith { sink.key("second") } + } + + @Test + fun `argumentsOrThrow() - throws ArgumentProtocolException while a map or list is open`() { + sink.key("list") + sink.beginList() + sink.scalar(1) + + assertFailsWith { sink.argumentsOrThrow() } + } + + @Test + fun `argumentsOrThrow() - throws ArgumentProtocolException when the last key has no value`() { + sink.key("id") + + assertFailsWith { sink.argumentsOrThrow() } + } + // Computed scalars @Test @@ -412,6 +445,7 @@ class TreeArgumentSinkTest { openLists(MAX_ARGUMENT_DEPTH - 1) sink.scalar("leaf") + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } assertThat(sink.argumentsOrThrow()) .isEqualTo(mapOf("nested" to nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf"))) @@ -434,6 +468,7 @@ class TreeArgumentSinkTest { sink.beginMap() sink.end() + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } assertThat(sink.argumentsOrThrow()) .isEqualTo(mapOf("nested" to nestedInLists(MAX_ARGUMENT_DEPTH - 1, emptyMap()))) @@ -458,6 +493,7 @@ class TreeArgumentSinkTest { openLists(MAX_ARGUMENT_DEPTH - 1) sink.scalar("leaf") + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } assertThat(sink.argumentsOrThrow()["nested"]) .isEqualTo(nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf")) diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 8dd75b41ad..f351bae3ab 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -8025,6 +8025,7 @@ public abstract interface class io/sentry/util/HintUtils$SentryNullableConsumer public final class io/sentry/util/HttpUtils { public fun ()V + public static fun containsSensitiveDataKey (Ljava/lang/String;)Z public static fun containsSensitiveHeader (Ljava/lang/String;)Z public static fun filterHeaders (Ljava/util/Map;Lio/sentry/KeyValueCollectionBehavior;)Ljava/util/Map; public static fun filterQueryParams (Ljava/lang/String;Lio/sentry/KeyValueCollectionBehavior;)Ljava/lang/String; diff --git a/sentry/src/main/java/io/sentry/util/HttpUtils.java b/sentry/src/main/java/io/sentry/util/HttpUtils.java index 544cb18094..4802d42760 100644 --- a/sentry/src/main/java/io/sentry/util/HttpUtils.java +++ b/sentry/src/main/java/io/sentry/util/HttpUtils.java @@ -136,7 +136,11 @@ public static boolean containsSensitiveHeader(final @NotNull String header) { } } - static boolean containsSensitiveDataKey(final @NotNull String key) { + /** + * Returns whether {@code key} contains a term from the Data Collection spec's sensitive denylist, + * matched partially and case-insensitively. + */ + public static boolean containsSensitiveDataKey(final @NotNull String key) { final @NotNull String normalizedKey = key.toLowerCase(Locale.ROOT); for (final String term : SENSITIVE_DATA_KEYS) { if (normalizedKey.contains(term)) {