From 0f8bd10805df52a8022b0e8099b83e0c5cbeb52b Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 20 Nov 2026 12:02:38 +0100 Subject: [PATCH] ref(nav3): Unify bounded argument conversion --- sentry-android-navigation3/build.gradle.kts | 1 + .../internal/backstack/ArgumentConstraints.kt | 45 - .../internal/backstack/ArgumentConversion.kt | 447 ++++++++++ .../internal/backstack/BackStackConverter.kt | 243 ++---- .../internal/backstack/BackStackObserver.kt | 73 ++ .../backstack/CoordinatedBackStackObserver.kt | 76 -- .../navigation3/internal/backstack/README.md | 3 + .../internal/backstack/ArgumentBudgets.kt | 12 + .../backstack/ArgumentSanitizerTest.kt | 425 ++++++++++ .../backstack/BackStackConverterTest.kt | 300 +++---- .../backstack/HostArgumentSourceTest.kt | 436 ++++++++++ .../backstack/SelfWritingArguments.kt | 15 + .../backstack/TreeArgumentWriterTest.kt | 781 ++++++++++++++++++ 13 files changed, 2348 insertions(+), 509 deletions(-) delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConstraints.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index fab767c4bf..7a6cf51d18 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -87,6 +87,7 @@ dependencies { testImplementation(libs.androidx.test.ext.junit) testImplementation(libs.androidx.viewpager2) testImplementation(libs.google.truth) + testImplementation(libs.kotlin.test.junit) testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) testImplementation(libs.roboelectric) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConstraints.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConstraints.kt deleted file mode 100644 index 42b428c710..0000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConstraints.kt +++ /dev/null @@ -1,45 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack - -internal object ArgumentConstraints { - - /** - * Max combined length of map keys and text values visited in one back stack update. - * - * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries - * are preserved. - * - * Caps payload size in the presence of large individual arguments. - */ - const val MAX_ARGUMENT_CHARACTERS = 4_096 - - /** - * Max depth of an argument value within one back stack entry. Root arguments have depth 1; each - * nested map or list adds one level. - * - * For instance, `mapOf("id" to 123)` reaches a depth of 1; `mapOf("items" to listOf("apple", - * "banana"))` reaches a depth of 2. - * - * If exceeded, all arguments for that back stack entry are dropped. - */ - const val MAX_ARGUMENT_DEPTH = 10 - - /** - * Max number of argument values visited in one back stack update. Each scalar or nested container - * counts as one value; map keys and each entry's root argument map are excluded. - * - * For instance, `mapOf("id" to 123)` consumes 1 value; `mapOf("profile" to mapOf("id" to 123, - * "name" to "Ada"))` consumes 3 values. - * - * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries - * are preserved. - * - * For instance, suppose we have the following back stack: - * - * - /Checkout -> Top of the stack and processed first - * - /ProductDetail -> Processed second and exceeds the `MAX_ARGUMENT_VALUES` budget - * - /Home - * - * Then /ProductDetail and /Home will have no arguments, but /Checkout will. - */ - const val MAX_ARGUMENT_VALUES = 200 -} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt new file mode 100644 index 0000000000..96e2e7dc76 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt @@ -0,0 +1,447 @@ +package io.sentry.compose.navigation3.internal.backstack + +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.util.UrlUtils +import java.util.IdentityHashMap + +/** + * The core contract for the subsystem that converts properties of back stack entries into Sentry + * arguments. + * + * An [ArgumentSource] pushes information about back stack properties into this sink. Sink + * implementations are expected to materialize the provided info into a tree of Sentry arguments, + * where the tree has a bounded size and height. + * + * Receives one back stack entry's arguments as a [source][ArgumentSource] produces them, enforcing + * the argument limits as it goes. + * + * Throws [DropArguments] when a write violates a constraint or [reject] is called. Every write + * thereafter will also throw. + */ +internal interface ArgumentSink { + + /** + * The first [DropArguments] 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: DropArguments? + + /** + * Starts a map as the next value. [identity] is the object being written, if any, so that one + * that contains itself is rejected instead of written until a limit is reached. + * + * Call [end] when finished. + */ + fun beginMap(identity: Any? = null) + + /** + * Starts a list as the next value. [identity] is as for [beginMap]. + * + * Call [end] when finished. + */ + fun beginList(identity: Any? = null) + + /** + * Names the next value in the current map. If the map already has a value named [name], writing + * the next value throws [DropArguments], as recording only one of them would show Sentry a + * partial map as if it were complete. + */ + fun key(name: String) + + /** + * 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., how deeply serializers nest), and throws the resulting [DropArguments]. + * + * If a constraint was already violated, throws that instead. + */ + fun reject(reason: ArgumentDropReason, warning: String): Nothing +} + +/** + * Something that can write info about a back stack entry's properties to an [ArgumentSink]. + * + * Sources decide which data to expose and whether to filter sensitive values. The sink applies size + * and structural limits without performing sensitive-data filtering. + */ +internal interface ArgumentSource { + fun writeTo(sink: ArgumentSink) +} + +/** + * Materializes an argument tree for a single back stack entry and enforces argument constraints. + * Argument inputs are provided by an [ArgumentSource]. + * + * **Argument constraints** + * + * Rejects cycles, excessive nesting, duplicate keys, and writes that exceed the value or character + * limits in [budget]. Writes in violation of those limits throw [DropArguments], as does [reject] + * for a constraint the source enforces itself. Once thrown, subsequent writes and + * [argumentsOrThrow] rethrow that failure so a source can't accidentally return partial arguments. + * + * [budget] is shared across all back stack entries processed in one update, limiting their combined + * value and character counts. + * + * [rootIdentity] identifies the source object represented by this entry's root argument map, + * allowing references back to that object to be detected as cycles. + * + * **Key duplication** + * + * Duplicate keys are allowed only when both the key and the old and new values are + * [UrlUtils.SENSITIVE_DATA_SUBSTITUTE], since replacing one redacted value with another loses no + * information. + */ +@Suppress("TooManyFunctions") +internal class TreeArgumentWriter( + private val budget: ArgumentBudget, + rootIdentity: Any? = null, +) : ArgumentSink { + + private val root = LinkedHashMap() + + /** The open containers, innermost last, with the identity each was written from. */ + private val containers = ArrayList().apply { add(root) } + private val identities = ArrayList().apply { add(rootIdentity) } + private val activeIdentities = + IdentityHashMap().apply { rootIdentity?.let { put(it, Unit) } } + + private var pendingKey: String? = null + + override var failure: DropArguments? = null + private set + + override fun beginMap(identity: Any?) = guarded { begin(LinkedHashMap(), identity) } + + override fun beginList(identity: Any?) = guarded { begin(ArrayList(), identity) } + + override fun key(name: String) = guarded { pendingKey = budget.spendText(name) } + + override fun scalar(value: Any?) = writeScalar { value } + + override fun computedScalar(compute: () -> Any?) = writeScalar(compute) + + override fun end() = guarded { + check(containers.size > 1) { "end() without an open map or list." } + containers.removeAt(containers.lastIndex) + identities.removeAt(identities.lastIndex)?.let(activeIdentities::remove) + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing { + failure?.let { throw it } + throw DropArguments(reason, warning).also { failure = it } + } + + /** + * Returns the entry's arguments, or re-throws the [DropArguments] 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, identity: Any?) { + visitValue() + if (identity != null && activeIdentities.put(identity, Unit) != null) { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + add(container) + containers += container + identities += identity + } + + /** + * Enforces the depth limit, spends one value for the value about to be added, and rejects a key + * that's already taken, before the value is computed. + */ + private fun visitValue() { + // A value added while n containers are open has a depth of n. + if (containers.size > MAX_ARGUMENT_DEPTH) { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + budget.spendValue() + // A substitute key may still be written again with a substitute value, which add() decides + // once the value is known. + val key = pendingKey + val isKeyTaken = key != null && (containers.last() as? Map<*, *>)?.containsKey(key) == true + if (isKeyTaken && !key.isSubstitute()) { + throw DropArguments(ArgumentDropReason.DUPLICATE_KEY, DropArguments.DUPLICATE_KEY_WARNING) + } + } + + @Suppress("UNCHECKED_CAST") + private fun add(value: Any?) { + when (val parent = containers.last()) { + is ArrayList<*> -> (parent as ArrayList) += value + else -> { + val key = checkNotNull(pendingKey) { "A map value was written without a key." } + val map = parent as LinkedHashMap + val replacesSubstituteWithSubstitute = + key.isSubstitute() && map[key].isSubstitute() && value.isSubstitute() + if (map.containsKey(key) && !replacesSubstituteWithSubstitute) { + throw DropArguments(ArgumentDropReason.DUPLICATE_KEY, DropArguments.DUPLICATE_KEY_WARNING) + } + map[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, + is Char -> budget.spendText(value.toString()) + else -> + throw IllegalArgumentException("Unsupported scalar of type ${value.javaClass.name}.") + }, + ) + } + + private inline fun guarded(write: () -> Unit) { + failure?.let { throw it } + try { + write() + } catch (e: DropArguments) { + failure = e + throw e + } + } +} + +/** + * Writes a host app's argument map 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. + */ +internal class HostArgumentSource( + private val arguments: Map<*, *>, + private val onUnsupportedValue: (typeName: String?) -> Unit, +) : ArgumentSource { + + override fun writeTo(sink: ArgumentSink) { + writeEntries(arguments, sink) + } + + private fun writeEntries(map: Map<*, *>, sink: ArgumentSink) { + for ((key, value) in map) { + sink.key(key.toString()) + write(value, sink) + } + } + + private fun write(value: Any?, sink: ArgumentSink) { + val collection = value?.asCollectionOrNull() + when { + value is Map<*, *> -> { + sink.beginMap(identity = value) + writeEntries(value, sink) + sink.end() + } + collection != null -> { + sink.beginList(identity = value) + // Iterated without reading the collection's size, which the host app controls. + for (element in collection) { + write(element, sink) + } + sink.end() + } + // Computed only once the sink has checked the value fits, as it may run host app code. + else -> sink.computedScalar { scalarOf(value) } + } + } + + 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() + } + } +} + +/** 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 + } + +/** + * Control-flow signal to drop an entry's arguments. Overrides [fillInStackTrace] to skip + * stack-trace capture. + * + * [warning] is logged when the arguments are dropped, or no-ops if `null` (e.g., because the source + * logged its own). + */ +internal class DropArguments( + 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." + } +} + +/** Why host-provided arguments were unavailable in emitted nav state. */ +internal enum class ArgumentDropReason( + val serializedValue: String, + val exhaustsUpdateBudget: Boolean = false, +) { + + CHARACTER_LIMIT("max_character_limit_exceeded", exhaustsUpdateBudget = true), + DUPLICATE_KEY("duplicate_key"), + ENCODING_FAILED("encoding_failed"), + INVALID_STRUCTURE("invalid_structure"), + MAPPING_FAILED("mapping_failed"), + MAX_COUNT("max_argument_count_exceeded", exhaustsUpdateBudget = true), + SANITIZATION_FAILED("sanitization_failed"); + + companion object { + const val ARGUMENT_DROP_REASON_KEY = "dropped_by_sentry" + } +} + +/** + * The value and character budgets shared by the entries of one back stack update. Throws + * [DropArguments] when a value or text doesn't fit in what's left. + */ +internal class ArgumentBudget { + + private var remainingValues = MAX_ARGUMENT_VALUES + private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + + /** Spends one value. */ + fun spendValue() { + if (--remainingValues < 0) { + throw DropArguments(ArgumentDropReason.MAX_COUNT, DropArguments.MAX_COUNT_WARNING) + } + } + + /** Returns [text] after spending its characters. */ + fun spendText(text: String): String { + if (text.length > remainingCharacters) { + throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, DropArguments.MAX_CHARACTER_WARNING) + } + remainingCharacters -= text.length + return text + } +} + +internal object ArgumentConstraints { + + /** + * Max combined length of map keys and text values visited in one back stack update. + * + * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries + * are preserved. + * + * Caps payload size in the presence of large individual arguments. + */ + const val MAX_ARGUMENT_CHARACTERS = 4_096 + + /** + * Max depth of an argument value within one back stack entry. Root arguments have depth 1; each + * nested map or list adds one level. + * + * For instance, `mapOf("id" to 123)` reaches a depth of 1; `mapOf("items" to listOf("apple", + * "banana"))` reaches a depth of 2. + * + * If exceeded, all arguments for that back stack entry are dropped. + */ + const val MAX_ARGUMENT_DEPTH = 10 + + /** + * Max number of argument values visited in one back stack update. Each scalar or nested container + * counts as one value; map keys and each entry's root argument map are excluded. + * + * For instance, `mapOf("id" to 123)` consumes 1 value; `mapOf("profile" to mapOf("id" to 123, + * "name" to "Ada"))` consumes 3 values. + * + * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries + * are preserved. + * + * For instance, suppose we have the following back stack: + * + * - /Checkout -> Top of the stack and processed first + * - /ProductDetail -> Processed second and exceeds the `MAX_ARGUMENT_VALUES` budget + * - /Home + * + * Then /ProductDetail and /Home will have no arguments, but /Checkout will. + */ + const val MAX_ARGUMENT_VALUES = 200 +} + +private fun Any?.isSubstitute(): Boolean = this == UrlUtils.SENSITIVE_DATA_SUBSTITUTE + +/** Whether this is a NaN or infinite `Double` or `Float`. */ +private fun Number.isNonFinite(): Boolean = + (this is Double && !isFinite()) || (this is Float && !isFinite()) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index a549a39bb8..7d61951052 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 @@ -1,16 +1,13 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.compose.runtime.snapshots.Snapshot import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME import io.sentry.util.ExceptionUtils -import java.util.IdentityHashMap /** * Converts the host app back stack into a list of [NormalizedSentryBackStackEntry]s. @@ -26,7 +23,7 @@ import java.util.IdentityHashMap * **Threading policy** * * This class performs work synchronously on the calling thread. The host app's - * [BackStackEntryMapper] is invoked on that same thread and should remain small, non-blocking, and + * `BackStackEntryMapper` is invoked on that same thread and should remain small, non-blocking, and * safe for the caller's threading context. */ internal class BackStackConverter( @@ -86,7 +83,12 @@ internal class BackStackConverter( } val sanitizedArguments = - info.arguments?.let(sanitizer::sanitizeEntry) ?: SanitizedArguments(emptyMap()) + info.arguments?.let { arguments -> + // Argument conversion may read Compose state through host app code. Suppress read + // observation so changes to that state don't trigger recomposition solely b/c our + // telemetry code read it. + Snapshot.withoutReadObservation { sanitizer.sanitizeEntry(arguments) } + } ?: SanitizedArguments(emptyMap()) val formattedName = NormalizedSentryBackStackEntry.formatName(info.name) return if (formattedName.isBlank()) { @@ -133,27 +135,37 @@ internal class BackStackConverter( ) /** - * Sanitizes a back stack entry's arguments and writes them in a serializable form. It bounds - * depth and total value count, and it rejects cyclic structures. + * Sanitizes a back stack entry's raw argument inputs and returns them in a + * [serializable form][SanitizedArguments.values]. * - * One instance is shared across every entry in a single [convert] call, so the value budget is - * enforced across the whole update. Once the budget is spent, the overflowing entry and every - * older entry are dropped, while newer (already-processed) entries are preserved. + * Internally, this class processes argument inputs returned by the [entryMapper] passed to the + * outer converter instance. Those inputs can come from built-in or custom + * [BackStackEntryMapper]s. + * + * Built-in mappers supply their own [ArgumentSource], while custom mappers typically supply an + * ordinary map. [HostArgumentSource] adapts ordinary maps to the [ArgumentSource] contract, so + * both paths can be handled by the same processing pipeline. */ internal class ArgumentSanitizer( private val logger: ILogger, private val warningState: WarningState, ) { - private val activeContainers = IdentityHashMap() - private var remainingValues = MAX_ARGUMENT_VALUES - private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + // One instance per sanitizer, so the budgets span every entry of a back stack update. + private val budget = ArgumentBudget() private var dropReason: ArgumentDropReason? = null /** - * Sanitizes one entry's arguments, or returns an empty map to drop them, either because the - * structure is cyclic or too deeply nested (this entry only), or because the shared per-update - * value budget is spent (this entry and every older one). + * Sanitizes one entry's raw argument inputs and returns the result. + * + * [SanitizedArguments.values] will be empty if [raw] is empty or if the arguments were dropped. + * Arguments can be dropped if: + * + * - a previously processed entry exceeded the shared value or character budget; + * - an argument constraint is violated; or + * - conversion fails. + * + * [SanitizedArguments.dropReason] will be non-null if and only if arguments are dropped. */ @Suppress("TooGenericExceptionCaught") fun sanitizeEntry(raw: Map): SanitizedArguments { @@ -161,155 +173,38 @@ internal class BackStackConverter( return SanitizedArguments(emptyMap(), reason) } + // Use the raw inputs' own source implementation when available; otherwise, provide them with + // an adapter. + val source = + raw as? ArgumentSource + ?: HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } + val sink = TreeArgumentWriter(budget, rootIdentity = raw) + + // 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: DropSubtree) { - if (drop.reason.exhaustsUpdateBudget) { - dropReason = drop.reason - } - logger.log(WARNING, drop.warning) - SanitizedArguments(emptyMap(), drop.reason) + source.writeTo(sink) + SanitizedArguments(sink.argumentsOrThrow()) + } catch (drop: DropArguments) { + 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) - } - } - - private fun sanitizeMap(value: Map<*, *>, depth: Int): Map { - enter(value) - try { - val sanitized = mutableMapOf() - for ((key, childValue) in value) { - val keyString = key.toString() - consumeCharacters(keyString.length) - if (sanitized.containsKey(keyString)) { - throw DropSubtree( - "Nav3 map keys stringify to the same string. Dropping this entry's arguments.", - ArgumentDropReason.DUPLICATE_KEY, - ) - } - sanitized[keyString] = sanitizeValue(childValue, depth + 1) - } - return sanitized - } finally { - exit(value) - } - } - - private fun sanitizeCollection(value: Collection<*>, depth: Int): List { - enter(value) - try { - // The value budget bounds allocation instead of the caller-provided collection size. - val sanitized = mutableListOf() - for (childValue in value) { - sanitized += sanitizeValue(childValue, depth + 1) - } - return sanitized - } finally { - exit(value) - } - } - - private fun sanitizeValue(value: Any?, depth: Int): Any? { - visit(depth) - val collection = value?.asSanitizableCollectionOrNull() - - return when { - value is Map<*, *> -> sanitizeMap(value, depth) - collection != null -> sanitizeCollection(collection, depth) - else -> sanitizeScalar(value) - } - } - - private fun sanitizeScalar(value: Any?): Any? = - when (value) { - null, - is Boolean -> value - is Number -> - if (value.isNonFinite()) { - value.toString().also { consumeCharacters(it.length) } - } else value - is String -> value.also { consumeCharacters(it.length) } - is CharSequence, - is Char -> value.toString().also { consumeCharacters(it.length) } - is Enum<*> -> value.name.also { consumeCharacters(it.length) } - else -> { - warningState.logUnsupportedValueWarning(value::class.simpleName, logger) - value.toString().also { consumeCharacters(it.length) } + sink.failure?.let { + return drop(it) } + logger.log(WARNING, DropArguments.STRUCTURE_WARNING, t) + SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) } - - private fun Any.asSanitizableCollectionOrNull(): Collection<*>? = - when (this) { - is Collection<*> -> this - is Array<*> -> asList() - is BooleanArray -> asList() - is ByteArray -> asList() - is ShortArray -> asList() - is IntArray -> asList() - is LongArray -> asList() - is FloatArray -> asList() - is DoubleArray -> asList() - is CharArray -> asList() - else -> null - } - - /** - * Records a visit to one value, enforcing the per-entry depth cap and the shared per-update - * value budget. Throws [DropSubtree] to abort the current subtree when either is exceeded. - */ - private fun visit(depth: Int) { - if (depth > MAX_ARGUMENT_DEPTH) { - throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE) - } - if (--remainingValues < 0) { - throw DropSubtree(MAX_COUNT_WARNING, ArgumentDropReason.MAX_COUNT) - } - } - - private fun consumeCharacters(count: Int) { - if (count > remainingCharacters) { - throw DropSubtree(MAX_CHARACTER_WARNING, ArgumentDropReason.CHARACTER_LIMIT) - } - remainingCharacters -= count } - private fun enter(container: Any) { - if (activeContainers.put(container, Unit) != null) { - throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE) + private fun drop(drop: DropArguments): SanitizedArguments { + if (drop.reason.exhaustsUpdateBudget) { + dropReason = drop.reason } - } - - private fun exit(container: Any) { - activeContainers.remove(container) - } - - /** - * Control-flow signal to abort sanitization of the current subtree. Internal to - * [ArgumentSanitizer]. - * - * [reason] distinguishes entry-local drops from update-wide budget exhaustion. Overrides - * [fillInStackTrace] to skip stack-trace capture. - */ - private class DropSubtree(val warning: String, val reason: ArgumentDropReason) : - RuntimeException() { - override fun fillInStackTrace(): Throwable = this - } - - private companion object { - - private const val MAX_CHARACTER_WARNING = - "Nav3 arguments exceeded the maximum total character count for one backstack update. Skipping " + - "arguments for this and older captured entries." - - private const val MAX_COUNT_WARNING = - "Nav3 arguments exceeded the maximum total count for one backstack update. Skipping arguments for " + - "this and older captured entries." - - private const val STRUCTURE_WARNING = - "Nav3 argument sanitization failed (possibly a cyclic or deeply nested structure). Skipping arguments." + drop.warning?.let { logger.log(WARNING, it) } + return SanitizedArguments(emptyMap(), drop.reason) } } @@ -327,8 +222,7 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper returned a blank name while processing this back stack update. " + - "Using $UNKNOWN_ENTRY_NAME instead.", + "Nav3 backStackEntryMapper returned a blank name. Using $UNKNOWN_ENTRY_NAME.", ) hasLoggedInvalidNameWarning = true } @@ -340,8 +234,7 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper threw while resolving an entry. " + - "Using $UNKNOWN_ENTRY_NAME without arguments instead.", + "Nav3 backStackEntryMapper threw. Using $UNKNOWN_ENTRY_NAME without arguments.", throwable, ) hasLoggedMapperFailureWarning = true @@ -354,10 +247,8 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this back " + - "stack update. Falling back to toString(). Use String, CharSequence, Char, Number, " + - "Boolean, Enum, Map, Collection, object Array, and primitive array values for reliable " + - "results.", + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper.", typeName, ) hasLoggedUnsupportedValueWarning = true @@ -425,25 +316,3 @@ internal data class NormalizedSentryBackStackEntry( internal fun List.serialize(): List> = map(NormalizedSentryBackStackEntry::serialize) - -/** Why host-provided arguments were unavailable in emitted nav state. */ -internal enum class ArgumentDropReason( - val serializedValue: String, - val exhaustsUpdateBudget: Boolean = false, -) { - - CHARACTER_LIMIT("max_character_limit_exceeded", exhaustsUpdateBudget = true), - DUPLICATE_KEY("duplicate_key"), - INVALID_STRUCTURE("invalid_structure"), - MAPPING_FAILED("mapping_failed"), - MAX_COUNT("max_argument_count_exceeded", exhaustsUpdateBudget = true), - SANITIZATION_FAILED("sanitization_failed"); - - companion object { - const val ARGUMENT_DROP_REASON_KEY = "dropped_by_sentry" - } -} - -/** Whether this is a NaN or infinite Double or Float. */ -private fun Number.isNonFinite(): Boolean = - (this is Double && !isFinite()) || (this is Float && !isFinite()) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt index 8cf28a3a3f..988000c6b6 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt @@ -1,7 +1,10 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.lifecycle.LifecycleEventObserver import io.sentry.Breadcrumb import io.sentry.Hint +import io.sentry.IScope +import io.sentry.IScopes import io.sentry.SentryIntegrationPackageStorage import io.sentry.SentryLevel.INFO import io.sentry.SentryOptions @@ -16,6 +19,9 @@ import io.sentry.compose.navigation3.internal.lifecycle.INavScope import io.sentry.compose.navigation3.internal.lifecycle.INavScopes import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_CONTEXT_KEY import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_OP +import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator +import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo +import io.sentry.compose.navigation3.internal.lifecycle.NavScopes import io.sentry.compose.navigation3.internal.lifecycle.NavTransactionRequest import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion import java.lang.ref.WeakReference @@ -379,3 +385,70 @@ private class NavBreadcrumbs(private val scopes: INavScopes) { scopes.addBreadcrumb(breadcrumb, hint) } } + +/** + * A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with those of + * other `BackStackObserver`s. + * + * Coordination is achieved via [NavScopes]. + * + * **Usage** + * + * Call [attach] before the first [onBackStackChanged], and call [dispose] when observation ends. + * + * Instances targeting the same [IScope] must be created with the same [NavLeaseCoordinator]. + * + * **Thread safety** + * + * This class is ***not*** thread-safe. Invocations should be confined to the same thread as the + * [LifecycleEventObserver] callbacks through which the [NavLeaseCoordinator] observes the attached + * lifecycle. + */ +internal class CoordinatedBackStackObserver( + scopes: IScopes, + options: SentryNavOptions, + entryMapper: ForwardingBackStackEntryMapper, + coordinator: NavLeaseCoordinator, +) { + + private val navScopes = NavScopes(scopes, coordinator) + private val observer = BackStackObserver(navScopes, options, entryMapper) + + fun attach(rootInfo: NavRootInfo) { + navScopes.attach(rootInfo) + } + + fun onBackStackChanged(backStack: List) { + navScopes.onBackStackUpdate() + observer.onBackStackChanged(backStack) + } + + fun dispose() { + // Call disposal on both the observer and navScopes in case their (currently overlapping) + // implementations drift over time. + observer.dispose() + navScopes.dispose() + } +} + +/** + * The [NavLeaseCoordinator] shared by default by all [CoordinatedBackStackObserver]s. + * + * **Lifetime** + * + * The default coordinator lives as long as the process, since lease state follows nav root + * lifecycles rather than the SDK's. Closing and re-initializing the SDK doesn't require a reset + * because: + * + * - `SentryNavEffect` resolves the current scopes on every call; + * + * - while the SDK is closed, bookkeeping continues without a scope; and + * + * - unpublishing compares by reference, so values published to an earlier scope don't affect the + * current one. + * + * Limitation: A nav transaction that's still running when the SDK is closed and re-initialized can + * be bound to the new scope the next time it's published, although its client has been closed. + * Spans then attach to it, and are lost, until it times out or the next navigation finishes it. + */ +internal val defaultNavLeaseCoordinator: NavLeaseCoordinator = NavLeaseCoordinator() diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt deleted file mode 100644 index a7d30a998f..0000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt +++ /dev/null @@ -1,76 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack - -import androidx.lifecycle.LifecycleEventObserver -import io.sentry.IScope -import io.sentry.IScopes -import io.sentry.compose.navigation3.SentryNavOptions -import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator -import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo -import io.sentry.compose.navigation3.internal.lifecycle.NavScopes - -/** - * A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with those of - * other `BackStackObserver`s. - * - * Coordination is achieved via [NavScopes]. - * - * **Usage** - * - * Call [attach] before the first [onBackStackChanged], and call [dispose] when observation ends. - * - * Instances targeting the same [IScope] must be created with the same [NavLeaseCoordinator]. - * - * **Thread safety** - * - * This class is ***not*** thread-safe. Invocations should be confined to the same thread as the - * [LifecycleEventObserver] callbacks through which the [NavLeaseCoordinator] observes the attached - * lifecycle. - */ -internal class CoordinatedBackStackObserver( - scopes: IScopes, - options: SentryNavOptions, - entryMapper: ForwardingBackStackEntryMapper, - coordinator: NavLeaseCoordinator, -) { - - private val navScopes = NavScopes(scopes, coordinator) - private val observer = BackStackObserver(navScopes, options, entryMapper) - - fun attach(rootInfo: NavRootInfo) { - navScopes.attach(rootInfo) - } - - fun onBackStackChanged(backStack: List) { - navScopes.onBackStackUpdate() - observer.onBackStackChanged(backStack) - } - - fun dispose() { - // Call disposal on both the observer and navScopes in case their (currently overlapping) - // implementations drift over time. - observer.dispose() - navScopes.dispose() - } -} - -/** - * The [NavLeaseCoordinator] shared by default by all [CoordinatedBackStackObserver]s. - * - * **Lifetime** - * - * The default coordinator lives as long as the process, since lease state follows nav root - * lifecycles rather than the SDK's. Closing and re-initializing the SDK doesn't require a reset - * because: - * - * - `SentryNavEffect` resolves the current scopes on every call; - * - * - while the SDK is closed, bookkeeping continues without a scope; and - * - * - unpublishing compares by reference, so values published to an earlier scope don't affect the - * current one. - * - * Limitation: A nav transaction that's still running when the SDK is closed and re-initialized can - * be bound to the new scope the next time it's published, although its client has been closed. - * Spans then attach to it, and are lost, until it times out or the next navigation finishes it. - */ -internal val defaultNavLeaseCoordinator: NavLeaseCoordinator = NavLeaseCoordinator() diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md new file mode 100644 index 0000000000..d528413e16 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md @@ -0,0 +1,3 @@ +# `io.sentry.compose.navigation3.internal.backstack` + +Converts host back stacks into bounded Sentry names and arguments. diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt new file mode 100644 index 0000000000..4f77307b74 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt @@ -0,0 +1,12 @@ +package io.sentry.compose.navigation3.internal.backstack + +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.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/backstack/ArgumentSanitizerTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt new file mode 100644 index 0000000000..039b1b2a92 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt @@ -0,0 +1,425 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel.WARNING +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.ArgumentSanitizer +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.SanitizedArguments +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.WarningState +import kotlin.test.assertFailsWith +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions + +class ArgumentSanitizerTest { + + private class OpaqueValue { + override fun toString(): String = "opaque-value" + } + + private class ThrowingValue(val failure: IllegalStateException = IllegalStateException("boom")) { + @Suppress("ExceptionRaisedInUnexpectedLocation") override fun toString(): String = throw failure + } + + private val logger = mock() + private val sanitizer = ArgumentSanitizer(logger, WarningState()) + + private val laterArguments = mapOf("id" to "123") + + private companion object { + private const val UNSUPPORTED_VALUE_WARNING = + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper." + } + + // Plain maps + + @Test + fun `sanitizeEntry() - returns the arguments of a plain map as written`() { + val arguments = + mapOf("id" to "123", "filters" to mapOf("tags" to listOf("a", "b")), "page" to 2) + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized).isEqualTo(SanitizedArguments(arguments)) + } + + @Test + fun `sanitizeEntry() - returns empty arguments without a drop reason for an empty map`() { + val sanitized = sanitizer.sanitizeEntry(emptyMap()) + + assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), dropReason = null)) + } + + // Unsupported values + + @Test + fun `sanitizeEntry() - logs the unsupported value warning with the value type`() { + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) + + verify(logger).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue")) + } + + @Test + fun `the unsupported value warning is logged once across entries sanitized by one sanitizer`() { + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue(), "alsoOpaque" to OpaqueValue())) + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) + + verify(logger, times(1)).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue")) + } + + // Arguments that write themselves + + @Test + fun `sanitizeEntry() - lets an ArgumentSource write its arguments instead of reading them as a map`() { + val arguments = SelfWritingArguments { sink -> + sink.key("written") + sink.scalar("by the source") + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized).isEqualTo(SanitizedArguments(mapOf("written" to "by the source"))) + } + + @Test + fun `sanitizeEntry() - records the drop reason of an ArgumentSource that drops its arguments`() { + val arguments = SelfWritingArguments { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, "source warning") + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + } + + @Test + fun `sanitizeEntry() - logs the warning of an ArgumentSource that drops its arguments`() { + val arguments = SelfWritingArguments { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, "source warning") + } + + sanitizer.sanitizeEntry(arguments) + + verify(logger).log(eq(WARNING), eq("source warning")) + } + + @Test + fun `sanitizeEntry() - logs nothing when an ArgumentSource drops its arguments without a warning`() { + val arguments = SelfWritingArguments { + throw DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.ENCODING_FAILED)) + verifyNoInteractions(logger) + } + + @Test + fun `sanitizeEntry() - records the broken limit when an ArgumentSource replaces it with another exception`() { + val arguments = overCharacterLimitReplacedWith { IllegalStateException("replaced") } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `sanitizeEntry() - logs the broken limit's warning when an ArgumentSource replaces it with another exception`() { + val arguments = overCharacterLimitReplacedWith { IllegalStateException("replaced") } + + sanitizer.sanitizeEntry(arguments) + + verify(logger).log(eq(WARNING), eq(DropArguments.MAX_CHARACTER_WARNING)) + verify(logger, never()).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), any()) + } + + @Test + fun `sanitizeEntry() - records the broken limit when an ArgumentSource replaces it with its own DropArguments`() { + val arguments = overCharacterLimitReplacedWith { + DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + // Dropped arguments + + @Test + fun `sanitizeEntry() - drops arguments over the value budget and logs the value budget warning`() { + // The list and its elements are one value more than the budget. + 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(DropArguments.MAX_COUNT_WARNING)) + } + + @Test + fun `sanitizeEntry() - drops arguments over the character budget and logs the character budget warning`() { + // The key and the value are one character more than the budget. + val sanitized = sanitizer.sanitizeEntry(mapOf("v" to "x".repeat(MAX_ARGUMENT_CHARACTERS))) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + verify(logger).log(eq(WARNING), eq(DropArguments.MAX_CHARACTER_WARNING)) + } + + @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)) + } + + // Budgets shared across entries + + @Test + fun `entries sanitized by one sanitizer share the value budget`() { + // Each of the first two entries uses half of the value budget: a list and its elements. + val half = MAX_ARGUMENT_VALUES / 2 + val first = sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + val second = sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + val third = sanitizer.sanitizeEntry(mapOf("one" to 1)) + + assertThat(first.dropReason).isNull() + assertThat(second.dropReason).isNull() + assertThat(third).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `entries sanitized by one sanitizer share the character budget`() { + // Each of the first two entries uses half of the character budget: a key and its value. + val half = MAX_ARGUMENT_CHARACTERS / 2 + val first = sanitizer.sanitizeEntry(mapOf("a" to "x".repeat(half - 1))) + val second = sanitizer.sanitizeEntry(mapOf("b" to "x".repeat(half - 1))) + val third = sanitizer.sanitizeEntry(mapOf("c" to null)) + + assertThat(first.dropReason).isNull() + assertThat(second.dropReason).isNull() + assertThat(third).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `entries share the value budget with arguments that write themselves`() { + // The source writes half of the value budget, so one value more than the other half doesn't + // fit. + val half = MAX_ARGUMENT_VALUES / 2 + val first = + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(half - 1) { sink.scalar(it) } + sink.end() + }, + ) + val second = sanitizer.sanitizeEntry(mapOf("values" to List(half) { it })) + + assertThat(first.dropReason).isNull() + assertThat(second).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `arguments that write themselves share the value budget with other entries`() { + // The first entry uses half of the value budget, so the source's one value more than the other + // half doesn't fit. + val half = MAX_ARGUMENT_VALUES / 2 + sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + + val sanitized = + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(half) { sink.scalar(it) } + sink.end() + }, + ) + + assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + // Failures + + @Test + fun `sanitizeEntry() - drops arguments for a sanitization failure when a value throws`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("ok" to 1, "throwing" to ThrowingValue())) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED)) + } + + @Test + fun `sanitizeEntry() - logs the structure warning with the exception when a value throws`() { + val throwing = ThrowingValue() + + sanitizer.sanitizeEntry(mapOf("throwing" to throwing)) + + verify(logger).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), eq(throwing.failure)) + } + + @Test + fun `sanitizeEntry() - rethrows fatal errors thrown during sanitization`() { + val fatal = + object { + override fun toString(): String = throw StackOverflowError("fatal") + } + + assertFailsWith { + sanitizer.sanitizeEntry(mapOf("fatal" to fatal)) + } + verify(logger, never()).log(eq(WARNING), eq(DropArguments.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()))) + } + + // Later entries after a drop + + @Test + fun `entries after the value budget is exhausted are dropped without another warning`() { + sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES) { it })) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArguments.MAX_COUNT_WARNING)) + } + + @Test + fun `entries after the character budget is exhausted are dropped without another warning`() { + sanitizer.sanitizeEntry(mapOf("v" to "x".repeat(MAX_ARGUMENT_CHARACTERS))) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArguments.MAX_CHARACTER_WARNING)) + } + + @Test + fun `entries after an ArgumentSource exhausts the value budget are dropped`() { + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(MAX_ARGUMENT_VALUES) { sink.scalar(it) } + sink.end() + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `entries after an ArgumentSource replaces a broken character limit with another exception are dropped`() { + sanitizer.sanitizeEntry(overCharacterLimitReplacedWith { IllegalStateException("replaced") }) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `entries after an ArgumentSource replaces a broken character limit with its own DropArguments are dropped`() { + sanitizer.sanitizeEntry( + overCharacterLimitReplacedWith { + DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null) + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `an entry dropped for invalid structure doesn't drop later entries`() { + val cyclic = mutableListOf() + cyclic.add(cyclic) + sanitizer.sanitizeEntry(mapOf("cyclic" to cyclic)) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + + @Test + fun `an entry dropped for a duplicate map key doesn't drop later entries`() { + sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", "1" to "b"))) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + + @Test + fun `an ArgumentSource that fails to encode its arguments doesn't drop later entries`() { + sanitizer.sanitizeEntry( + SelfWritingArguments { throw DropArguments(ArgumentDropReason.ENCODING_FAILED, null) }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + + @Test + fun `an entry that failed sanitization doesn't drop later entries`() { + sanitizer.sanitizeEntry(mapOf("throwing" to ThrowingValue())) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + + /** + * Arguments that write one character more than the character budget, then catch the sink's + * [DropArguments] and throw [replacement] instead, without it as the cause. + */ + private fun overCharacterLimitReplacedWith(replacement: () -> Throwable) = + SelfWritingArguments { sink -> + try { + // The key and the value are one character more than the budget. + sink.key("v") + sink.scalar("x".repeat(MAX_ARGUMENT_CHARACTERS)) + } catch (@Suppress("SwallowedException") e: DropArguments) { + throw replacement() + } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index 9799eee835..2e61c2792f 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -1,18 +1,25 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat import io.sentry.ILogger +import io.sentry.JsonSerializer import io.sentry.SentryLevel.WARNING +import io.sentry.SentryOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME -import java.util.AbstractCollection +import java.io.StringWriter +import kotlin.test.assertFailsWith import org.junit.Test +import org.mockito.kotlin.any import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify @@ -33,6 +40,13 @@ class BackStackConverterTest { private val logger = mock() + private companion object { + const val BLANK_NAME_WARNING = + "Nav3 backStackEntryMapper returned a blank name. Using /unknown." + const val MAPPER_FAILURE_WARNING = + "Nav3 backStackEntryMapper threw. Using /unknown without arguments." + } + private val defaultEntryMapper = BackStackEntryMapper { entry -> SentryBackStackEntry(entry::class.simpleName ?: "") @@ -95,7 +109,7 @@ class BackStackConverterTest { } @Test - fun `convert preserves input order when top entry is first`() { + fun `convert with KEEP_FIRST returns entries in back stack order`() { val sut = getSut() val routes = @@ -114,20 +128,20 @@ class BackStackConverterTest { } @Test - fun `convert preserves input order when top entry is last`() { + fun `convert with KEEP_LAST returns entries in back stack order`() { val sut = getSut() val routes = sut.convert( - listOf(HomeScreen(), ProfileScreen("123"), SettingsScreen("privacy")), - RetentionPolicy.KEEP_FIRST, + listOf(SettingsScreen("privacy"), ProfileScreen("123"), HomeScreen()), + RetentionPolicy.KEEP_LAST, ) assertThat(routes) .containsExactly( - NormalizedSentryBackStackEntry("/HomeScreen"), - NormalizedSentryBackStackEntry("/ProfileScreen"), NormalizedSentryBackStackEntry("/SettingsScreen"), + NormalizedSentryBackStackEntry("/ProfileScreen"), + NormalizedSentryBackStackEntry("/HomeScreen"), ) .inOrder() } @@ -320,13 +334,19 @@ class BackStackConverterTest { verify(logger) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper returned a blank name while processing this back stack update. " + - "Using /unknown instead.", - ), + eq(BLANK_NAME_WARNING), ) } + @Test + fun `convert logs the blank name warning once per back stack update`() { + val sut = getSut(entryMapper = { SentryBackStackEntry(" ") }) + + sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + + verify(logger, times(1)).log(eq(WARNING), eq(BLANK_NAME_WARNING)) + } + @Test fun `convert returns unknown name without arguments if mapper returns null`() { val sut = getSut(entryMapper = { null }) @@ -349,140 +369,65 @@ class BackStackConverterTest { verify(logger) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper threw while resolving an entry. Using /unknown without arguments instead.", - ), - org.mockito.kotlin.any(), + eq(MAPPER_FAILURE_WARNING), + any(), ) } @Test - fun `convert returns arguments in proper serializable form`() { - val text = StringBuilder("hello") - val sut = - getSut( - entryMapper = { entry -> - entryInfo( - entry, - mapOf( - "str" to "hello", - "charSequence" to text, - "char" to 'x', - "num" to 42, - "bool" to true, - "enum" to PrivacyMode.PRIVATE, - "nil" to null, - "nested" to mapOf("inner" to "value"), - "tags" to listOf("a", "b", "c"), - "array" to arrayOf("a", 1, false, PrivacyMode.PUBLIC, 'z'), - "ints" to intArrayOf(1, 2, 3), - "chars" to charArrayOf('a', 'b'), - "bytes" to byteArrayOf(4, 5), - ), - ) - }, - ) - - assertThat(sut.convert(HomeScreen()).arguments) - .isEqualTo( - mapOf( - "str" to "hello", - "charSequence" to "hello", - "char" to "x", - "num" to 42, - "bool" to true, - "enum" to "PRIVATE", - "nil" to null, - "nested" to mapOf("inner" to "value"), - "tags" to listOf("a", "b", "c"), - "array" to listOf("a", 1, false, "PUBLIC", "z"), - "ints" to listOf(1, 2, 3), - "chars" to listOf("a", "b"), - "bytes" to listOf(4.toByte(), 5.toByte()), - ), - ) - } + fun `convert logs the mapper failure warning once per back stack update`() { + val sut = getSut(entryMapper = { error("boom") }) - @Test - fun `convert sanitizes arguments with nested supported containers recursively`() { - val sut = - getSut( - entryMapper = { entry -> - entryInfo( - entry, - mapOf( - "nested" to - mapOf( - "items" to - arrayOf( - StringBuilder("x"), - listOf('y', PrivacyMode.PRIVATE), - booleanArrayOf(true, false), - charArrayOf('q'), - ), - ), - ), - ) - }, - ) + sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) - assertThat(sut.convert(HomeScreen()).arguments) - .isEqualTo( - mapOf( - "nested" to - mapOf("items" to listOf("x", listOf("y", "PRIVATE"), listOf(true, false), listOf("q"))), - ), - ) + verify(logger, times(1)).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) } @Test - fun `convert coerces arguments with unsupported values to strings`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" - } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("bad" to OpaqueValue())) }) + fun `convert rethrows fatal errors thrown by the mapper`() { + val sut = getSut(entryMapper = { throw StackOverflowError("fatal") }) - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("bad" to "opaque-value")) + assertFailsWith { sut.convert(HomeScreen()) } + verify(logger, never()).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) } @Test - fun `convert logs an unsupported value warning once per back stack update`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" - } - + fun `convert returns the mapper's arguments sanitized`() { val sut = getSut( entryMapper = { entry -> - entryInfo( - entry, - when (entry) { - is HomeScreen -> mapOf("bad" to OpaqueValue()) - is ProfileScreen -> mapOf("alsoBad" to OpaqueValue()) - else -> emptyMap() - }, - ) + entryInfo(entry, mapOf("mode" to PrivacyMode.PRIVATE, "ids" to intArrayOf(1, 2))) }, ) - sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + assertThat(sut.convert(HomeScreen()).arguments) + .isEqualTo(mapOf("mode" to "PRIVATE", "ids" to listOf(1, 2))) + } - verify(logger, times(1)) - .log( - eq(WARNING), - eq( - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this " + - "back stack update. Falling back to toString(). Use String, CharSequence, Char, " + - "Number, Boolean, Enum, Map, Collection, object Array, and primitive array values " + - "for reliable results.", - ), - eq("OpaqueValue"), - ) + @Test + fun `convert hides state reads by an ArgumentSource from snapshot observation`() { + val state = mutableStateOf("value") + val arguments = SelfWritingArguments { sink -> + sink.key("state") + sink.scalar(state.value) + } + val sut = getSut(entryMapper = { entry -> entryInfo(entry, arguments) }) + val observedReads = mutableListOf() + val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) + + val converted = + try { + snapshot.enter { sut.convert(HomeScreen()) } + } finally { + snapshot.dispose() + } + + assertThat(converted.arguments).isEqualTo(mapOf("state" to "value")) + assertThat(observedReads).isEmpty() } @Test - fun `unsupported value warning can recur with a fresh update state`() { + fun `convert logs the unsupported value warning again in a later back stack update`() { class OpaqueValue { override fun toString(): String = "opaque-value" } @@ -498,95 +443,23 @@ class BackStackConverterTest { .log( eq(WARNING), eq( - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this " + - "back stack update. Falling back to toString(). Use String, CharSequence, Char, " + - "Number, Boolean, Enum, Map, Collection, object Array, and primitive array values " + - "for reliable results.", + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper.", ), eq("OpaqueValue"), ) } @Test - fun `convert returns empty arguments for cyclic structures`() { - val cyclic = mutableMapOf() - cyclic["self"] = cyclic - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("cyclic" to cyclic)) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert returns empty arguments for deeply nested structures`() { - var nested: Any? = "value" - repeat(25) { nested = listOf(nested) } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("nested" to nested)) }) - - val entry = sut.convert(ProfileScreen("123")) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert drops oversized arguments`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(1_001) { it })) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.MAX_COUNT) - } - - @Test - fun `convert drops arguments when character budget is exceeded`() { + fun `convert starts each back stack update with a fresh argument budget`() { val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to "x".repeat(4_097))) }) + getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(150) { it })) }) + sut.convert(HomeScreen()) val entry = sut.convert(HomeScreen()) - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - - @Test - fun `convert reports sanitization failures`() { - class ThrowingValue { - override fun toString(): String = error("boom") - } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to ThrowingValue())) }) - - val converted = sut.convert(HomeScreen()) - - assertThat(converted.arguments).isEmpty() - assertThat(converted.argumentDropReason).isEqualTo(ArgumentDropReason.SANITIZATION_FAILED) - } - - @Test - fun `arguments do not use caller collection size for allocation`() { - val values = - object : AbstractCollection() { - var wasSizeRead = false - - override val size: Int - get() { - wasSizeRead = true - return 2 - } - - override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() - } - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to values)) }) - - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("values" to listOf(1, 2))) - assertThat(values.wasSizeRead).isFalse() + assertThat(entry.arguments).isEqualTo(mapOf("values" to List(150) { it })) + assertThat(entry.argumentDropReason).isNull() } @Test @@ -627,6 +500,31 @@ class BackStackConverterTest { .inOrder() } + @Test + fun `converted entries with non-finite number arguments serialize to valid JSON through Sentry's JSON serializer`() { + val sut = + getSut( + entryMapper = { entry -> + entryInfo( + entry, + mapOf( + "price" to Double.NaN, + "limits" to floatArrayOf(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), + ), + ) + }, + ) + val serializedEntry = sut.convert(HomeScreen()).serialize() + val json = StringWriter() + + JsonSerializer(SentryOptions()).serialize(serializedEntry, json) + + assertThat(json.toString()) + .isEqualTo( + """{"entry":"/HomeScreen","entry_arguments":{"price":"NaN","limits":["Infinity","-Infinity"]}}""", + ) + } + @Test fun `serialize includes the reason arguments were dropped`() { val entry = diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt new file mode 100644 index 0000000000..609e4cb478 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt @@ -0,0 +1,436 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.BeginList +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.BeginMap +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.End +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.Key +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.Scalar +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.UncomputedScalar +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 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() + } + + // 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(nested), Key("1"), Scalar("a"), End) + .inOrder() + } + + @Test + fun `writeTo() - passes a nested map as its own identity`() { + val nested = mapOf("k" to "v") + val source = hostArgumentSource(mapOf("nested" to nested)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(nested) + } + + @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(set), Scalar("a"), Scalar("b"), End) + .inOrder() + } + + @Test + fun `writeTo() - passes a collection as its own identity`() { + val list = listOf("a") + val source = hostArgumentSource(mapOf("list" to list)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(list) + } + + @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(array), 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() - passes a primitive array as its own identity`() { + val ints = intArrayOf(1, 2) + val source = hostArgumentSource(mapOf("ints" to ints)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(ints) + } + + @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(listOf(outer)), + BeginMap(outer), + Key("inner"), + BeginList(inner), + 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() + } + + // 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 = DropArguments(ArgumentDropReason.MAX_COUNT, DropArguments.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 } + + sealed interface Event { + data class Key(val name: String) : Event + + data class Scalar(val value: Any?) : Event + + data class BeginMap(val identity: Any?) : Event + + data class BeginList(val identity: Any?) : 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: DropArguments? = null + + override fun beginMap(identity: Any?) { + events += BeginMap(identity) + } + + override fun beginList(identity: Any?) { + events += BeginList(identity) + } + + override fun key(name: 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 = + throw UnsupportedOperationException("HostArgumentSource enforces no limits of its own") + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt new file mode 100644 index 0000000000..ccba9d1679 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt @@ -0,0 +1,15 @@ +package io.sentry.compose.navigation3.internal.backstack + +/** + * Arguments that write themselves with [write], like a built-in mapper's. Read as a map, they hold + * only [entries], which differ from what they write unless a test sets them. + */ +internal class SelfWritingArguments( + override val entries: Set> = mapOf("read" to "as a map").entries, + private val write: (ArgumentSink) -> Unit, +) : AbstractMap(), ArgumentSource { + + override fun writeTo(sink: ArgumentSink) { + write(sink) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt new file mode 100644 index 0000000000..8ce124c126 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt @@ -0,0 +1,781 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.util.UrlUtils +import kotlin.test.assertFailsWith +import org.junit.Test + +class TreeArgumentWriterTest { + + private val budget = ArgumentBudget() + private val sink = TreeArgumentWriter(budget) + + private val characterLimitDrop = + ArgumentDropReason.CHARACTER_LIMIT to DropArguments.MAX_CHARACTER_WARNING + private val duplicateKeyDrop = + ArgumentDropReason.DUPLICATE_KEY to DropArguments.DUPLICATE_KEY_WARNING + private val maxCountDrop = ArgumentDropReason.MAX_COUNT to DropArguments.MAX_COUNT_WARNING + private val structureDrop = + ArgumentDropReason.INVALID_STRUCTURE to DropArguments.STRUCTURE_WARNING + + private val DropArguments.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() - writes text exactly as long as the remaining characters`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(2)) + limitedSink.key("") + + limitedSink.scalar("ab") + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to "ab")) + } + + @Test + fun `scalar() - spends characters for a CharSequence value`() { + val limitedSink = TreeArgumentWriter(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 = TreeArgumentWriter(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 = TreeArgumentWriter(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 = TreeArgumentWriter(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 = TreeArgumentWriter(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 IllegalArgumentException for an unsupported type`() { + sink.key("opaque") + + assertFailsWith { sink.scalar(Any()) } + } + + @Test + fun `scalar() - throws IllegalStateException 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 = TreeArgumentWriter(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 = TreeArgumentWriter(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() - drops the arguments for a duplicate key without computing the value`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + var computations = 0 + + val drop = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - drops the arguments for a duplicate key when computing the value would throw`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + + val drop = + assertFailsWith { + sink.computedScalar { throw IllegalStateException("host toString() failed") } + } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @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() - accepts a key exactly as long as the remaining characters`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(2)) + + limitedSink.key("ab") + limitedSink.scalar(null) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("ab" to null)) + } + + @Test + fun `key() - spends the characters of the key`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + + val drop = assertFailsWith { limitedSink.key("ab") } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `key() - doesn't spend a value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + + limitedSink.key("a") + + val drop = assertFailsWith { limitedSink.scalar(1) } + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + // Containers + + @Test + fun `beginMap() - spends one value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + limitedSink.key("map") + + val drop = assertFailsWith { limitedSink.beginMap() } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `beginList() - spends one value`() { + val limitedSink = TreeArgumentWriter(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 = TreeArgumentWriter(budgetWithValuesRemaining(1)) + limitedSink.key("id") + + limitedSink.scalar(1) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("id" to 1)) + } + + @Test + fun `end() - throws IllegalStateException when no map or list is open`() { + assertFailsWith { sink.end() } + } + + @Test + fun `end() - throws IllegalStateException 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")) + } + + // Cycles + + @Test + fun `a container nested in a container with the same identity drops the arguments for invalid structure`() { + val list = mutableListOf() + sink.key("cyclic") + sink.beginList(identity = list) + + val drop = assertFailsWith { sink.beginList(identity = list) } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container with the root identity drops the arguments for invalid structure`() { + val root = mutableMapOf() + val rootedSink = TreeArgumentWriter(budget, rootIdentity = root) + rootedSink.key("self") + + val drop = assertFailsWith { rootedSink.beginMap(identity = root) } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container identical to the root is written when no root identity is given`() { + val root = mutableMapOf() + sink.key("self") + + sink.beginMap(identity = root) + sink.end() + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("self" to emptyMap())) + } + + @Test + fun `sibling containers with the same identity are both written`() { + val shared = listOf("a") + sink.key("first") + sink.beginList(identity = shared) + sink.scalar("a") + sink.end() + sink.key("second") + + sink.beginList(identity = shared) + sink.scalar("a") + sink.end() + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("first" to listOf("a"), "second" to listOf("a"))) + } + + @Test + fun `nested containers without an identity are never treated as a cycle`() { + sink.key("nested") + sink.beginList(identity = null) + + sink.beginList(identity = null) + sink.end() + sink.end() + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("nested" to listOf(emptyList()))) + } + + // Duplicate keys + + @Test + fun `a scalar under a key already in its map drops the arguments for a duplicate key`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + + val drop = assertFailsWith { sink.scalar(2) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a map under a key already in its map drops the arguments for a duplicate key when the map begins`() { + sink.key("filters") + sink.scalar(null) + sink.key("filters") + + val drop = assertFailsWith { sink.beginMap() } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a list under a key already in its map drops the arguments for a duplicate key when the list begins`() { + sink.key("tags") + sink.beginList() + sink.end() + sink.key("tags") + + val drop = assertFailsWith { sink.beginList() } + + 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 `a substitute value under a substitute key already holding the substitute is written once`() { + sink.key(SUBSTITUTE) + sink.scalar(SUBSTITUTE) + sink.key(SUBSTITUTE) + + sink.scalar(SUBSTITUTE) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf(SUBSTITUTE to SUBSTITUTE)) + } + + @Test + fun `a substitute value under a substitute key holding another value drops the arguments for a duplicate key`() { + sink.key(SUBSTITUTE) + sink.scalar("secret") + sink.key(SUBSTITUTE) + + val drop = assertFailsWith { sink.scalar(SUBSTITUTE) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `another value under a substitute key holding the substitute drops the arguments for a duplicate key`() { + sink.key(SUBSTITUTE) + sink.scalar(SUBSTITUTE) + sink.key(SUBSTITUTE) + + val drop = assertFailsWith { sink.scalar("secret") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a substitute value under another key holding the substitute drops the arguments for a duplicate key`() { + sink.key("token") + sink.scalar(SUBSTITUTE) + sink.key("token") + + val drop = assertFailsWith { sink.scalar(SUBSTITUTE) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + // Value budget + + @Test + fun `values exactly filling the remaining value budget are written`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(2)) + limitedSink.key("list") + limitedSink.beginList() + + limitedSink.scalar(1) + limitedSink.end() + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("list" to listOf(1))) + } + + // Shared budget + + @Test + fun `sinks built on one budget share the value budget`() { + val first = TreeArgumentWriter(budget) + val second = TreeArgumentWriter(budget) + writeScalars(first, count = MAX_ARGUMENT_VALUES - 1) + writeScalars(second, count = 1) + second.key("overflow") + + val drop = assertFailsWith { second.scalar(1) } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `sinks built on one budget share the character budget`() { + val first = TreeArgumentWriter(budget) + val second = TreeArgumentWriter(budget) + first.key("x".repeat(MAX_ARGUMENT_CHARACTERS - 1)) + first.scalar(null) + second.key("y") + + val drop = assertFailsWith { second.scalar("z") } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + // Sticky failure + + @Test + fun `every write after the arguments are dropped rethrows the same DropArguments`() { + 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 DropArguments 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 DropArguments thrown by the write that broke a limit`() { + val drop = exhaustValues() + + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `failure - stays the first DropArguments 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 DropArguments with the given reason and warning`() { + val drop = rejectStructure() + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `reject() - records the DropArguments it throws as the failure`() { + val drop = rejectStructure() + + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArguments 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 DropArguments when a limit was already rejected`() { + val firstDrop = rejectStructure() + + val drop = + assertFailsWith { + sink.reject(ArgumentDropReason.MAX_COUNT, DropArguments.MAX_COUNT_WARNING) + } + + assertThat(drop).isSameInstanceAs(firstDrop) + assertThat(sink.failure).isSameInstanceAs(firstDrop) + } + + @Test + fun `every write after a rejected limit rethrows the rejected DropArguments`() { + 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 DropArguments a source caught and swallowed`() { + sink.key("id") + sink.scalar("123") + val rejected = rejectStructure() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(rejected) + } + + // DropArguments + + @Test + fun `DropArguments - 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(): DropArguments = + 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(): DropArguments = + assertFailsWith { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + + private fun nestedInLists(levels: Int, leaf: Any?): Any? { + var nested = leaf + repeat(levels) { nested = listOf(nested) } + return nested + } +}