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..8b56ad7be9 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt @@ -0,0 +1,461 @@ +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 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. + * + * **The argument conversion subsystem** + * + * With Nav3, host apps manage their own nav back stack, which they implement as a list of + * arbitrarily typed entries. In order to be displayed in Sentry, each of those entries has to be + * mapped to a Sentry name (e.g., ProductDetailScreen) and zero or more arguments (e.g., productId) + * via a `BackStackEntryMapper`. + * + * `ArgumentSink` and `ArgumentSource` create the seam that lets us support variable processing on + * the source side (e.g., a plain map supplied by the host app vs. arguments that write themselves) + * but uniform processing on the sink side (argument pruning, protecting against constraint + * violation, and tree materialization). + * + * Here are the moving parts: + * ```text + * ArgumentSource + * ┌────────────────────┐ + * │ HostArgumentSource │ + * │ (plain host map) │ + * └─────────┬──────────┘ + * ▼ + * ┌───────────────────────────────┐ + * │ ArgumentSink │ + * └───────────────────────────────┘ + * ▲ sole impl + * ┌───────────────┴───────────────┐ + * │ TreeArgumentWriter │ + * │ │ ┌────────────────┐ + * │ Enforce + materialize: │ spends ──▶│ ArgumentBudget │ + * │ • builds the argument tree │ └────────────────┘ + * │ • prevents constraint │ ┌────────────────┐ + * │ violation (e.g., cycles) │ throws ──▶│ DropArguments │ + * └───────────────────────────────┘ └────────────────┘ + * + * Note: BackStackConverter.ArgumentSanitizer owns the ArgumentBudget and + * selects the ArgumentSource based on what the host app provides. + * ``` + * + * Receives one back stack entry's arguments as a [source][ArgumentSource] produces them, enforcing + * the argument limits as it goes. + * + * 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? + + /** + * Throws [failure], if there is one. + * + * The recorded failure always wins: code that catches an exception while writing calls this + * before handling the exception itself, as intervening code (e.g., host app code) may have caught + * the original [DropArguments] and thrown something else, and the recorded reason decides whether + * older entries keep their arguments. + */ + fun throwIfFailed() { + failure?.let { throw it } + } + + /** + * 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]. + * + * [describeDuplicate], if provided, returns the warning to log in that case instead of + * [DropArguments.DUPLICATE_KEY_WARNING]. It's only called for a duplicate, so it may do work that + * would be wasteful for every key, e.g., finding the key that [name] collides with. + */ + fun key(name: String, describeDuplicate: (() -> String)? = null) + + /** + * 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]. + * + * By default, computes the value first and then writes it through [scalar], so nothing is checked + * before [compute] runs. [TreeArgumentWriter] overrides this to check 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. + * A sink that wraps another must forward this method to keep that check. + */ + 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 +} + +/** + * Writes a back stack entry's arguments 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. + */ +@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 + private var describePendingDuplicate: (() -> 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, describeDuplicate: (() -> String)?) = guarded { + pendingKey = budget.spendText(name) + describePendingDuplicate = describeDuplicate + } + + 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 { + throwIfFailed() + 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 { + throwIfFailed() + return root + } + + /** Adds [container] as the next value, and makes it the container that later writes fill. */ + 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 + } + + /** + * Checks the value about to be added before it's computed: enforces the depth limit, rejects a + * key that's already taken, and then spends one value from [budget]. + */ + 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) + } + val key = pendingKey + val map = containers.last() as? LinkedHashMap<*, *> + if (key != null && map != null && map.containsKey(key)) { + throw duplicateKey() + } + budget.spendValue() + } + + @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." } + (parent as LinkedHashMap)[key] = value + pendingKey = null + describePendingDuplicate = null + } + } + } + + private fun duplicateKey(): DropArguments = + DropArguments( + ArgumentDropReason.DUPLICATE_KEY, + describePendingDuplicate?.invoke() ?: DropArguments.DUPLICATE_KEY_WARNING, + ) + + private inline fun writeScalar(compute: () -> Any?) = guarded { + visitValue() + add( + when (val value = compute()) { + null, + is Boolean -> value + // JSON has no NaN or infinity, and Sentry's JSON writer throws for them, which would drop + // the whole event these arguments are attached to. We record them as strings instead. + is Number -> if (value.isNonFinite()) budget.spendText(value.toString()) else value + is CharSequence -> budget.spendText(value) + is Char -> budget.spendText(value.toString()) + else -> + throw IllegalArgumentException("Unsupported scalar of type ${value.javaClass.name}.") + }, + ) + } + + private inline fun guarded(write: () -> Unit) { + throwIfFailed() + 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) { + val name = key.toString() + sink.key(name) { duplicateKeyWarning(map, key, name) } + write(value, sink) + } + } + + /** + * Names only the colliding keys' types, as the keys themselves may contain host data. Collisions + * are rare, so we re-scan [map] instead of tracking the original keys of every map. + */ + private fun duplicateKeyWarning(map: Map<*, *>, key: Any?, name: String): String { + val otherKey = map.keys.firstOrNull { it !== key && it.toString() == name } + return "A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same " + + "string as another key (${otherKey?.let { it::class.simpleName }}). Dropping this " + + "entry's arguments." + } + + 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. Use `null` if no warning is needed, for + * example when the source already logged the failure. + */ +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." + } +} + +/** + * 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 { + checkFits(text.length) + remainingCharacters -= text.length + return text + } + + /** + * Returns [text] as a [String] after spending its characters. + * + * Checks [text]'s length before converting it, so that host app text that doesn't fit isn't + * copied, and again after, in case a custom [CharSequence]'s length doesn't match its text. + */ + fun spendText(text: CharSequence): String { + checkFits(text.length) + return spendText(text.toString()) + } + + private fun checkFits(characters: Int) { + if (characters > remainingCharacters) { + throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, DropArguments.MAX_CHARACTER_WARNING) + } + } +} + +/** 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 e15194da1c..1e8bcf891f 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt @@ -5,13 +5,9 @@ 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. @@ -139,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 { @@ -167,161 +173,37 @@ 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 for ArgumentSink.throwIfFailed. Here it's the reason the arguments are dropped with. 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)) { - // Types only b/c key strings may contain host data. Collisions are rare, so we re-scan - // instead of tracking original keys for every map. - val otherKey = value.keys.firstOrNull { it !== key && it.toString() == keyString } - throw DropSubtree( - "A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same " + - "string as another key (${otherKey?.let { it::class.simpleName }}). " + - "Dropping this entry's arguments.", - ArgumentDropReason.DUPLICATE_KEY, - ) - } - sanitized[keyString] = sanitizeValue(childValue, depth + 1) - } - return sanitized - } finally { - exit(value) - } - } - - 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 - } - - companion object { - - const val MAX_CHARACTER_WARNING = - "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + - "this and older entries." - - const val MAX_COUNT_WARNING = - "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + - "and older entries." - - const val STRUCTURE_WARNING = - "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + - "entry's arguments." + drop.warning?.let { logger.log(WARNING, it) } + return SanitizedArguments(emptyMap(), drop.reason) } } @@ -451,7 +333,3 @@ internal enum class ArgumentDropReason( 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/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgetTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgetTest.kt new file mode 100644 index 0000000000..09fed2fb5e --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgetTest.kt @@ -0,0 +1,63 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import kotlin.test.assertFailsWith +import org.junit.Test + +class ArgumentBudgetTest { + + // spendText(CharSequence) + + @Test + fun `spendText(CharSequence) - returns text exactly as long as the remaining characters as a String`() { + val budget = budgetWithCharactersRemaining(2) + + val spent = budget.spendText(StringBuilder("ab")) + + assertThat(spent).isEqualTo("ab") + } + + @Test + fun `spendText(CharSequence) - spends the characters of the text`() { + val budget = budgetWithCharactersRemaining(2) + budget.spendText(StringBuilder("ab")) + + val drop = assertFailsWith { budget.spendText(StringBuilder("c")) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + } + + @Test + fun `spendText(CharSequence) - spends the characters of the text rather than its reported length`() { + val budget = budgetWithCharactersRemaining(2) + budget.spendText(CountingText(length = 0, text = "ab")) + + val drop = assertFailsWith { budget.spendText(StringBuilder("c")) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `spendText(CharSequence) - throws for the character limit without converting text that's too long`() { + val budget = budgetWithCharactersRemaining(1) + val text = CountingText(length = 2, text = "ab") + + val drop = assertFailsWith { budget.spendText(text) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + assertThat(text.toStringCalls).isEqualTo(0) + } + + @Test + fun `spendText(CharSequence) - throws for the character limit when text is longer than its reported length`() { + val budget = budgetWithCharactersRemaining(1) + + val drop = + assertFailsWith { budget.spendText(CountingText(length = 1, text = "ab")) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + } +} 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 index d9f0f76864..7067a8cfc5 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt @@ -16,6 +16,7 @@ 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 { @@ -74,6 +75,88 @@ class ArgumentSanitizerTest { 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.INVALID_STRUCTURE, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + 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.INVALID_STRUCTURE, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + // Dropped arguments @Test @@ -82,7 +165,7 @@ class ArgumentSanitizerTest { val sanitized = sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES) { it })) assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_COUNT_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArguments.MAX_COUNT_WARNING)) } @Test @@ -92,7 +175,7 @@ class ArgumentSanitizerTest { assertThat(sanitized) .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArguments.MAX_CHARACTER_WARNING)) } @Test @@ -142,6 +225,74 @@ class ArgumentSanitizerTest { 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)) + } + + @Test + fun `an entry dropped for a duplicate map key doesn't spend the value budget of later entries`() { + // A list and its elements, which leave three values: two for the duplicate entry's nested map + // and its first value, and one for the later entry's value. + sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES - 4) { it })) + + val duplicate = sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", "1" to "b"))) + val later = sanitizer.sanitizeEntry(mapOf("one" to 1)) + + assertThat(duplicate) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.DUPLICATE_KEY)) + assertThat(later).isEqualTo(SanitizedArguments(mapOf("one" to 1))) + } + + @Test + fun `a duplicate map key with no values left drops only that entry, for the duplicate key`() { + // A list and its elements, which leave two values, for the duplicate entry's nested map and its + // first value. + sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES - 3) { it })) + + val duplicate = sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", "1" to "b"))) + val later = sanitizer.sanitizeEntry(emptyMap()) + + assertThat(duplicate) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.DUPLICATE_KEY)) + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), dropReason = null)) + } + // Failures @Test @@ -158,7 +309,7 @@ class ArgumentSanitizerTest { sanitizer.sanitizeEntry(mapOf("throwing" to throwing)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), eq(throwing.failure)) + verify(logger).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), eq(throwing.failure)) } @Test @@ -171,8 +322,7 @@ class ArgumentSanitizerTest { assertFailsWith { sanitizer.sanitizeEntry(mapOf("fatal" to fatal)) } - verify(logger, never()) - .log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), any()) + verify(logger, never()).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), any()) } @Test @@ -195,7 +345,7 @@ class ArgumentSanitizerTest { val later = sanitizer.sanitizeEntry(laterArguments) assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) - verify(logger, times(1)).log(eq(WARNING), eq(ArgumentSanitizer.MAX_COUNT_WARNING)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArguments.MAX_COUNT_WARNING)) } @Test @@ -205,7 +355,45 @@ class ArgumentSanitizerTest { val later = sanitizer.sanitizeEntry(laterArguments) assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) - verify(logger, times(1)).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + verify(logger, times(1)).log(eq(WARNING), eq(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.INVALID_STRUCTURE, warning = null) + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) } @Test @@ -228,6 +416,17 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) } + @Test + fun `an ArgumentSource that drops its arguments for invalid structure doesn't drop later entries`() { + sanitizer.sanitizeEntry( + SelfWritingArguments { throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, 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())) @@ -236,4 +435,19 @@ class ArgumentSanitizerTest { 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 d07f373311..74cc380c6f 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,6 +1,7 @@ package io.sentry.compose.navigation3.internal.backstack import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat import io.sentry.ILogger @@ -9,11 +10,11 @@ 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.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS 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.io.StringWriter -import java.util.AbstractCollection import kotlin.test.assertFailsWith import org.junit.Test import org.mockito.kotlin.any @@ -396,128 +397,60 @@ class BackStackConverterTest { } @Test - fun `convert returns arguments in proper serializable form`() { - val text = StringBuilder("hello") + fun `convert returns the mapper's arguments sanitized`() { 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), - ), - ) + entryInfo(entry, mapOf("mode" to PrivacyMode.PRIVATE, "ids" to intArrayOf(1, 2))) }, ) 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()), - ), - ) + .isEqualTo(mapOf("mode" to "PRIVATE", "ids" to listOf(1, 2))) } @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'), - ), - ), - ), - ) - }, - ) + fun `convert drops the arguments for the character limit without converting mapper text that's too long`() { + val text = CountingText(length = MAX_ARGUMENT_CHARACTERS + 1, text = "short") + val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("title" to text)) }) - assertThat(sut.convert(HomeScreen()).arguments) + val route = sut.convert(HomeScreen()) + + assertThat(route) .isEqualTo( - mapOf( - "nested" to - mapOf("items" to listOf("x", listOf("y", "PRIVATE"), listOf(true, false), listOf("q"))), + NormalizedSentryBackStackEntry( + "/HomeScreen", + argumentDropReason = ArgumentDropReason.CHARACTER_LIMIT, ), ) + assertThat(text.toStringCalls).isEqualTo(0) } @Test - fun `convert coerces arguments with unsupported values to strings`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" - } + fun `convert hides state reads during argument sanitization from snapshot observation`() { + val arguments = mutableStateMapOf("state" to "value") + val sut = getSut(entryMapper = { entry -> entryInfo(entry, arguments) }) + val observedReads = mutableListOf() + val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("bad" to OpaqueValue())) }) + val converted = + try { + snapshot.enter { sut.convert(HomeScreen()) } + } finally { + snapshot.dispose() + } - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("bad" to "opaque-value")) + assertThat(converted.arguments).isEqualTo(mapOf("state" to "value")) + assertThat(observedReads).isEmpty() } @Test - fun `convert logs an unsupported value warning once per back stack update`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" + 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, - when (entry) { - is HomeScreen -> mapOf("bad" to OpaqueValue()) - is ProfileScreen -> mapOf("alsoBad" to OpaqueValue()) - else -> emptyMap() - }, - ) - }, - ) - - sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) - - verify(logger, times(1)) - .log( - eq(WARNING), - eq(UNSUPPORTED_VALUE_WARNING), - eq("OpaqueValue"), - ) - } - - @Test - fun `convert hides state reads during argument sanitization from snapshot observation`() { - val arguments = mutableStateMapOf("state" to "value") val sut = getSut(entryMapper = { entry -> entryInfo(entry, arguments) }) val observedReads = mutableListOf() val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) @@ -554,54 +487,6 @@ class BackStackConverterTest { ) } - @Test - fun `convert returns empty arguments for cyclic structures`() { - val cyclic = mutableMapOf() - cyclic["self"] = cyclic - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("cyclic" to cyclic)) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert returns empty arguments for deeply nested structures`() { - var nested: Any? = "value" - repeat(25) { nested = listOf(nested) } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("nested" to nested)) }) - - val entry = sut.convert(ProfileScreen("123")) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert drops oversized arguments`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(1_001) { it })) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.MAX_COUNT) - } - - @Test - fun `convert drops arguments when character budget is exceeded`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to "x".repeat(4_097))) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - @Test fun `convert starts each back stack update with a fresh argument budget`() { val sut = @@ -614,40 +499,6 @@ class BackStackConverterTest { assertThat(entry.argumentDropReason).isNull() } - @Test - fun `convert reports sanitization failures`() { - class ThrowingValue { - override fun toString(): String = error("boom") - } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to ThrowingValue())) }) - - val converted = sut.convert(HomeScreen()) - - assertThat(converted.arguments).isEmpty() - assertThat(converted.argumentDropReason).isEqualTo(ArgumentDropReason.SANITIZATION_FAILED) - } - - @Test - fun `arguments do not use caller collection size for allocation`() { - val values = - object : AbstractCollection() { - var wasSizeRead = false - - override val size: Int - get() { - wasSizeRead = true - return 2 - } - - override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() - } - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to values)) }) - - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("values" to listOf(1, 2))) - assertThat(values.wasSizeRead).isFalse() - } - @Test fun `omitted arguments normalize to an empty map`() { val sut = getSut() 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..0b143b1041 --- /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, describeDuplicate: (() -> String)?) { + if (name == failOnKey && keyFailure != null) throw keyFailure + events += Key(name) + } + + override fun scalar(value: Any?) { + events += Scalar(value) + } + + override fun computedScalar(compute: () -> Any?) { + if (computesScalars) scalar(compute()) else events += UncomputedScalar + } + + override fun end() { + events += End + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing = + 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/TestTexts.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TestTexts.kt new file mode 100644 index 0000000000..4cb99bbf5e --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TestTexts.kt @@ -0,0 +1,31 @@ +package io.sentry.compose.navigation3.internal.backstack + +/** + * Host app text that reports [length], which may differ from [text]'s, and counts its conversions + * to a `String` in [toStringCalls]. + */ +internal class CountingText(override val length: Int, private val text: String) : CharSequence { + var toStringCalls = 0 + private set + + override fun get(index: Int): Char = text[index] + + override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = + text.subSequence(startIndex, endIndex) + + override fun toString(): String { + toStringCalls++ + return text + } +} + +/** Host app text whose conversion to a `String` throws [error]. */ +internal class FailingText(val error: RuntimeException) : CharSequence { + override val length: Int = 1 + + override fun get(index: Int): Char = 'x' + + override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = "x" + + @Suppress("ExceptionRaisedInUnexpectedLocation") override fun toString(): String = throw error +} 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..20d01897c3 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt @@ -0,0 +1,872 @@ +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 + +@Suppress("LargeClass") +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() - drops for the character limit without converting a CharSequence that's too long`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + limitedSink.key("") + val text = CountingText(length = 2, text = "ab") + + val drop = assertFailsWith { limitedSink.scalar(text) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + assertThat(text.toStringCalls).isEqualTo(0) + } + + @Test + fun `scalar() - drops for the character limit when a CharSequence is longer than its reported length`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + limitedSink.key("") + + val drop = + assertFailsWith { limitedSink.scalar(CountingText(length = 1, text = "ab")) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - propagates the exception a CharSequence's toString() throws`() { + val error = IllegalArgumentException("unreadable") + sink.key("text") + + val thrown = assertFailsWith { sink.scalar(FailingText(error)) } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(sink.failure).isNull() + } + + @Test + fun `scalar() - adds nothing for a CharSequence whose toString() throws, so its key can take a value`() { + sink.key("text") + assertFailsWith { + sink.scalar(FailingText(IllegalArgumentException("unreadable"))) + } + + sink.scalar("replacement") + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("text" to "replacement")) + } + + @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 duplicate key drops the arguments with the warning its describeDuplicate returns`() { + sink.key("id") + sink.scalar(1) + sink.key("id") { "described duplicate" } + + val drop = assertFailsWith { sink.scalar(2) } + + assertThat(drop.signal).isEqualTo(ArgumentDropReason.DUPLICATE_KEY to "described duplicate") + } + + @Test + fun `key() - doesn't call describeDuplicate for a key that isn't taken`() { + var calls = 0 + sink.key("id") { + calls++ + "described duplicate" + } + sink.scalar(1) + sink.key("other") + sink.scalar(2) + + assertThat(calls).isEqualTo(0) + } + + @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 scalar equal to the one already under its key drops the arguments for a duplicate key`() { + sink.key("id") + sink.scalar('1') + sink.key("id") + + val drop = assertFailsWith { sink.scalar("1") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a duplicate key drops the arguments for a duplicate key before spending the value budget`() { + val sink = TreeArgumentWriter(budgetWithValuesRemaining(1)) + sink.key(SUBSTITUTE) + sink.scalar(SUBSTITUTE) + sink.key(SUBSTITUTE) + + 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) + } + + @Test + fun `a duplicate key doesn't spend a value of the shared budget`() { + val sharedBudget = budgetWithValuesRemaining(2) + val first = TreeArgumentWriter(sharedBudget) + val second = TreeArgumentWriter(sharedBudget) + first.key("id") + first.scalar(1) + first.key("id") + assertFailsWith { first.scalar(2) } + second.key("id") + + second.scalar(3) + + assertThat(second.argumentsOrThrow()).isEqualTo(mapOf("id" to 3)) + } + + @Test + fun `a duplicate key drops the arguments for a duplicate key when the shared budget has no values left`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(1)) + limitedSink.key("id") + limitedSink.scalar(1) + limitedSink.key("id") + + val drop = assertFailsWith { limitedSink.scalar(2) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a duplicate key for a container drops the arguments for the duplicate key with no values left`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(1)) + limitedSink.key("filters") + limitedSink.scalar(null) + limitedSink.key("filters") + + val drop = assertFailsWith { limitedSink.beginMap() } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + // 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 + } +}