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
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import io.sentry.ILogger
import io.sentry.SentryLevel.WARNING
import io.sentry.compose.navigation3.BackStackEntryMapper
import io.sentry.compose.navigation3.SentryBackStackEntry
import io.sentry.compose.navigation3.internal.common.ArgumentBudget
import io.sentry.compose.navigation3.internal.common.DropArgumentsException
import io.sentry.compose.navigation3.internal.common.HostArgumentSource
import io.sentry.compose.navigation3.internal.common.TreeArgumentSink
import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter
import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS
import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH
import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES
import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason
import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY
import io.sentry.compose.navigation3.internal.contract.BACK_STACK_ENTRY_ARGUMENTS_KEY
Expand All @@ -18,7 +19,6 @@ import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME
import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason
import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY
import io.sentry.util.ExceptionUtils
import java.util.IdentityHashMap

/**
* Converts the host app back stack into a list of [NormalizedSentryBackStackEntry]s.
Expand Down Expand Up @@ -151,8 +151,10 @@ internal class BackStackConverter<T : Any>(

/**
* Sanitizes the arguments the [entryMapper] returns for back stack entries and returns them in a
* [serializable form][SanitizedArguments.values]. It bounds depth and total value count, and it
* rejects cyclic structures.
* [serializable form][SanitizedArguments.values].
*
* Each entry's arguments are written by a [HostArgumentSource] into a [TreeArgumentSink], which
* bounds depth and total value count, and rejects cyclic structures.
*
* One instance is shared across every entry in a single [convert] call, so the value and
* character budgets span the whole update.
Expand All @@ -162,13 +164,9 @@ internal class BackStackConverter<T : Any>(
private val warningState: WarningState,
) {

private var remainingValues = MAX_ARGUMENT_VALUES
private var remainingCharacters = MAX_ARGUMENT_CHARACTERS
private val budget = ArgumentBudget()
private var dropReason: ArgumentDropReason? = null

/** The maps and lists currently being sanitized, so that one containing itself is rejected. */
private val activeContainers = IdentityHashMap<Any, Unit>()

/**
* Sanitizes one entry's raw argument inputs and returns the result.
*
Expand All @@ -187,142 +185,34 @@ internal class BackStackConverter<T : Any>(
return SanitizedArguments(emptyMap(), reason)
}

val source = HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) }
val sink = TreeArgumentSink(budget)

// A constraint violation the sink recorded takes precedence over whatever the source threw,
// as the source may have caught it and thrown something else, and it decides whether older
// entries keep their arguments.
return try {
SanitizedArguments(sanitizeMap(raw, depth = 0))
} catch (drop: DropArguments) {
if (drop.reason.exhaustsUpdateBudget) {
dropReason = drop.reason
}
logger.log(WARNING, drop.warning)
SanitizedArguments(emptyMap(), drop.reason)
source.writeTo(sink)
SanitizedArguments(sink.argumentsOrThrow())
} catch (drop: DropArgumentsException) {
drop(sink.failure ?: drop)
} catch (t: Throwable) {
// Extracted maps may invoke host app code while iterating or stringifying values.
ExceptionUtils.rethrowIfFatal(t)
logger.log(WARNING, STRUCTURE_WARNING, t)
SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED)
} finally {
// A drop or failure leaves the containers it was inside of open.
activeContainers.clear()
}
}

/** Sanitizes [map], whose values are at [depth] + 1. The entry's root map has depth 0. */
private fun sanitizeMap(map: Map<*, *>, depth: Int): Map<String, Any?> {
enter(map)
val sanitized = LinkedHashMap<String, Any?>()
for ((key, value) in map) {
val name = spendText(key.toString())
if (sanitized.containsKey(name)) {
throw duplicateKey(map, key, name)
}
sanitized[name] = sanitizeValue(value, depth + 1)
}
activeContainers.remove(map)
return sanitized
}

private fun sanitizeValue(value: Any?, depth: Int): Any? {
// A value at depth n is nested in n containers, counting the entry's root map.
if (depth > MAX_ARGUMENT_DEPTH) {
throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING)
}
if (--remainingValues < 0) {
throw DropArguments(ArgumentDropReason.MAX_COUNT, MAX_COUNT_WARNING)
}

if (value is Map<*, *>) {
return sanitizeMap(value, depth)
}
val collection = value?.asCollectionOrNull() ?: return sanitizeScalar(value)

enter(value)
// Iterated without reading the collection's size, which the host app controls.
val sanitized = ArrayList<Any?>()
for (element in collection) {
sanitized += sanitizeValue(element, depth + 1)
}
activeContainers.remove(value)
return sanitized
}

private fun sanitizeScalar(value: Any?): Any? =
when (value) {
null,
is Boolean -> value
// JSON has no NaN or infinity, and Sentry's JSON writer throws for them, which would drop
// the whole event these arguments are attached to. We record them as strings instead.
is Number -> if (value.isNonFinite()) spendText(value.toString()) else value
is CharSequence -> spendText(value)
is Char -> spendText(value.toString())
is Enum<*> -> spendText(value.name)
else -> {
warningState.logUnsupportedValueWarning(value::class.simpleName, logger)
spendText(value.toString())
sink.failure?.let {
return drop(it)
}
}

/**
* Returns [text] as a [String] after spending its characters.
*
* Checks [text]'s length before converting it, so that host app text that doesn't fit isn't
* copied, and again after, in case a custom [CharSequence]'s length doesn't match its text.
*/
private fun spendText(text: CharSequence): String {
checkFits(text.length)
val string = text.toString()
checkFits(string.length)
remainingCharacters -= string.length
return string
}

private fun checkFits(characters: Int) {
if (characters > remainingCharacters) {
throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, MAX_CHARACTER_WARNING)
logger.log(WARNING, DropArgumentsException.STRUCTURE_WARNING, t)
SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED)
}
}

private fun enter(container: Any) {
if (activeContainers.put(container, Unit) != null) {
throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING)
private fun drop(drop: DropArgumentsException): SanitizedArguments {
if (drop.reason.exhaustsUpdateBudget) {
dropReason = drop.reason
}
}

/**
* Names only the colliding keys' types, as the keys themselves may contain host data.
* Collisions are rare, so we re-scan [map] instead of tracking the original keys of every map.
*/
private fun duplicateKey(map: Map<*, *>, key: Any?, name: String): DropArguments {
val otherKey = map.keys.firstOrNull { it !== key && it.toString() == name }
return DropArguments(
ArgumentDropReason.DUPLICATE_KEY,
"A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same string " +
"as another key (${otherKey?.let { it::class.simpleName }}). Dropping this entry's " +
"arguments.",
)
}

/**
* Control-flow signal to drop an entry's arguments, logging [warning]. Overrides
* [fillInStackTrace] to skip stack-trace capture.
*/
private class DropArguments(val reason: ArgumentDropReason, val warning: String) :
RuntimeException() {
override fun fillInStackTrace(): Throwable = this
}

companion object {

const val MAX_CHARACTER_WARNING =
"Nav3 back stack update exceeded the argument character limit. Dropping arguments for " +
"this and older entries."

const val MAX_COUNT_WARNING =
"Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " +
"and older entries."

const val STRUCTURE_WARNING =
"Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " +
"entry's arguments."
logger.log(WARNING, drop.warning)
return SanitizedArguments(emptyMap(), drop.reason)
}
}

Expand Down Expand Up @@ -380,9 +270,7 @@ internal data class NormalizedSentryBackStackEntry(
val name: String,
/** Sanitized [SentryBackStackEntry.arguments] (i.e., bounded in size and depth). */
val arguments: Map<String, Any?> = emptyMap(),
/**
* The reason why the SDK dropped host-provided arguments, or null if no arguments were dropped.
*/
/** The reason why the SDK dropped the entry's arguments, or null if no arguments were dropped. */
val argumentDropReason: ArgumentDropReason? = null,
/** Why the entry was recorded as [UNKNOWN_ENTRY_NAME], or `null` if it has a name. */
val unknownEntryReason: UnknownEntryReason? = null,
Expand Down Expand Up @@ -451,23 +339,3 @@ internal fun NormalizedSentryBackStackEntry.transactionData(): Map<String, Any>

internal fun List<NormalizedSentryBackStackEntry>.serialize(): List<Map<String, Any?>> =
map(NormalizedSentryBackStackEntry::serialize)

/** Returns this collection, or this array as a list, or `null` if it's neither. */
private fun Any.asCollectionOrNull(): Collection<*>? =
when (this) {
is Collection<*> -> this
is Array<*> -> asList()
is BooleanArray -> asList()
is ByteArray -> asList()
is ShortArray -> asList()
is IntArray -> asList()
is LongArray -> asList()
is FloatArray -> asList()
is DoubleArray -> asList()
is CharArray -> asList()
else -> null
}

/** Whether this is a NaN or infinite `Double` or `Float`. */
private fun Number.isNonFinite(): Boolean =
(this is Double && !isFinite()) || (this is Float && !isFinite())
Loading
Loading