Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,9 @@
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.
Expand Down Expand Up @@ -139,191 +135,78 @@
)

/**
* 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<Any, Unit>()
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<String, Any?>): SanitizedArguments {
dropReason?.let { reason ->
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<String, Any?> {
enter(value)
try {
val sanitized = mutableMapOf<String, Any?>()
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<Any?> {
enter(value)
try {
// The value budget bounds allocation instead of the caller-provided collection size.
val sanitized = mutableListOf<Any?>()
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)
}
}

Check failure on line 209 in sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt

View check run for this annotation

@sentry/warden / warden: code-review

Catch parameter `drop` shadows the handler and fails compilation

In `sanitizeEntry`, the `DropArguments` catch parameter shadows the `drop` handler, so `drop(sink.failure ?: drop)` attempts to invoke the exception value and prevents the module from compiling. Rename the catch parameter or qualify the handler call.
Comment on lines +202 to 209

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Catch parameter drop shadows the handler and fails compilation

In sanitizeEntry, the DropArguments catch parameter shadows the drop handler, so drop(sink.failure ?: drop) attempts to invoke the exception value and prevents the module from compiling. Rename the catch parameter or qualify the handler call.

Evidence
  • BackStackConverter.convert() reaches ArgumentSanitizer.sanitizeEntry() for mapped arguments.
  • In sanitizeEntry(), the catch parameter named drop is in scope at the call drop(sink.failure ?: drop).
  • The handler is a separate member function, private fun drop(drop: DropArguments), and DropArguments has no invoke operator; the catch call therefore fails compilation.

Identified by Warden ยท code-review ยท L53-F55


/** A small state wrapper that lets us avoid spamming logs when sanitizing arguments. */
internal class WarningState {
Expand Down Expand Up @@ -451,7 +334,3 @@
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())
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ class ArgumentDuplicateKeysTest {
.log(
eq(WARNING),
eq(
"A Nav3 map key (String) stringifies to the same string as another key (Int). " +
"Dropping this entry's arguments.",
"Nav3 map keys stringify to the same string. Dropping this entry's arguments.",
),
)

Expand Down
Original file line number Diff line number Diff line change
@@ -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)) }
Loading
Loading