Skip to content

Commit 328049c

Browse files
committed
ref(nav3): Gather nav data keys in a contract package and simplify ArgumentSanitizer
The keys and values the Sentry UI shows (context, breadcrumb, and transaction keys, the /unknown name, and the argument drop reasons and limits) now live in one internal contract package, which the lifecycle package may import. A test pins each displayed string. ArgumentSanitizer recurses directly instead of through visit/exit helpers, checks a CharSequence's length before copying it, and has its own test suite.
1 parent 8fb26b4 commit 328049c

21 files changed

Lines changed: 1129 additions & 754 deletions

‎sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import org.jetbrains.annotations.ApiStatus
55

66
// Keep the default low, as every captured entry may require argument extraction and recursive
77
// sanitization when navigation changes are observed.
8-
private const val DEFAULT_MAX_CAPTURED_BACK_STACK_ENTRIES = 5
8+
internal const val DEFAULT_MAX_CAPTURED_BACK_STACK_ENTRIES = 5
99

1010
/**
1111
* Configuration info for a [SentryNavEffect].

‎sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConstraints.kt‎

Lines changed: 0 additions & 45 deletions
This file was deleted.

‎sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt‎

Lines changed: 113 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,14 @@ import io.sentry.ILogger
55
import io.sentry.SentryLevel.WARNING
66
import io.sentry.compose.navigation3.BackStackEntryMapper
77
import io.sentry.compose.navigation3.SentryBackStackEntry
8-
import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS
9-
import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH
10-
import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES
11-
import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY
12-
import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME
8+
import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS
9+
import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH
10+
import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES
11+
import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason
12+
import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY
13+
import io.sentry.compose.navigation3.internal.contract.BACK_STACK_ENTRY_ARGUMENTS_KEY
14+
import io.sentry.compose.navigation3.internal.contract.BACK_STACK_ENTRY_KEY
15+
import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME
1316
import io.sentry.util.ExceptionUtils
1417
import java.util.IdentityHashMap
1518

@@ -139,27 +142,36 @@ internal class BackStackConverter<T : Any>(
139142
)
140143

141144
/**
142-
* Sanitizes a back stack entry's arguments and writes them in a serializable form. It bounds
143-
* depth and total value count, and it rejects cyclic structures.
145+
* Sanitizes the arguments the [entryMapper] returns for back stack entries and returns them in a
146+
* [serializable form][SanitizedArguments.values]. It bounds depth and total value count, and it
147+
* rejects cyclic structures.
144148
*
145-
* One instance is shared across every entry in a single [convert] call, so the value budget is
146-
* enforced across the whole update. Once the budget is spent, the overflowing entry and every
147-
* older entry are dropped, while newer (already-processed) entries are preserved.
149+
* One instance is shared across every entry in a single [convert] call, so the value and
150+
* character budgets span the whole update.
148151
*/
149152
internal class ArgumentSanitizer(
150153
private val logger: ILogger,
151154
private val warningState: WarningState,
152155
) {
153156

154-
private val activeContainers = IdentityHashMap<Any, Unit>()
155157
private var remainingValues = MAX_ARGUMENT_VALUES
156158
private var remainingCharacters = MAX_ARGUMENT_CHARACTERS
157159
private var dropReason: ArgumentDropReason? = null
158160

161+
/** The maps and lists currently being sanitized, so that one containing itself is rejected. */
162+
private val activeContainers = IdentityHashMap<Any, Unit>()
163+
159164
/**
160-
* Sanitizes one entry's arguments, or returns an empty map to drop them, either because the
161-
* structure is cyclic or too deeply nested (this entry only), or because the shared per-update
162-
* value budget is spent (this entry and every older one).
165+
* Sanitizes one entry's raw argument inputs and returns the result.
166+
*
167+
* [SanitizedArguments.values] will be empty if [raw] is empty or if the arguments were dropped.
168+
* Arguments can be dropped if:
169+
*
170+
* - a previously processed entry exceeded the shared value or character budget;
171+
* - an argument constraint is violated; or
172+
* - conversion fails.
173+
*
174+
* [SanitizedArguments.dropReason] will be non-null if and only if arguments are dropped.
163175
*/
164176
@Suppress("TooGenericExceptionCaught")
165177
fun sanitizeEntry(raw: Map<String, Any?>): SanitizedArguments {
@@ -169,7 +181,7 @@ internal class BackStackConverter<T : Any>(
169181

170182
return try {
171183
SanitizedArguments(sanitizeMap(raw, depth = 0))
172-
} catch (drop: DropSubtree) {
184+
} catch (drop: DropArguments) {
173185
if (drop.reason.exhaustsUpdateBudget) {
174186
dropReason = drop.reason
175187
}
@@ -180,131 +192,112 @@ internal class BackStackConverter<T : Any>(
180192
ExceptionUtils.rethrowIfFatal(t)
181193
logger.log(WARNING, STRUCTURE_WARNING, t)
182194
SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED)
183-
}
184-
}
185-
186-
private fun sanitizeMap(value: Map<*, *>, depth: Int): Map<String, Any?> {
187-
enter(value)
188-
try {
189-
val sanitized = mutableMapOf<String, Any?>()
190-
for ((key, childValue) in value) {
191-
val keyString = key.toString()
192-
consumeCharacters(keyString.length)
193-
if (sanitized.containsKey(keyString)) {
194-
// Types only b/c key strings may contain host data. Collisions are rare, so we re-scan
195-
// instead of tracking original keys for every map.
196-
val otherKey = value.keys.firstOrNull { it !== key && it.toString() == keyString }
197-
throw DropSubtree(
198-
"A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same " +
199-
"string as another key (${otherKey?.let { it::class.simpleName }}). " +
200-
"Dropping this entry's arguments.",
201-
ArgumentDropReason.DUPLICATE_KEY,
202-
)
203-
}
204-
sanitized[keyString] = sanitizeValue(childValue, depth + 1)
205-
}
206-
return sanitized
207195
} finally {
208-
exit(value)
196+
// A drop or failure leaves the containers it was inside of open.
197+
activeContainers.clear()
209198
}
210199
}
211200

212-
private fun sanitizeCollection(value: Collection<*>, depth: Int): List<Any?> {
213-
enter(value)
214-
try {
215-
// The value budget bounds allocation instead of the caller-provided collection size.
216-
val sanitized = mutableListOf<Any?>()
217-
for (childValue in value) {
218-
sanitized += sanitizeValue(childValue, depth + 1)
201+
/** Sanitizes [map], whose values are at [depth] + 1. The entry's root map has depth 0. */
202+
private fun sanitizeMap(map: Map<*, *>, depth: Int): Map<String, Any?> {
203+
enter(map)
204+
val sanitized = LinkedHashMap<String, Any?>()
205+
for ((key, value) in map) {
206+
val name = spendText(key.toString())
207+
if (sanitized.containsKey(name)) {
208+
throw duplicateKey(map, key, name)
219209
}
220-
return sanitized
221-
} finally {
222-
exit(value)
210+
sanitized[name] = sanitizeValue(value, depth + 1)
223211
}
212+
activeContainers.remove(map)
213+
return sanitized
224214
}
225215

226216
private fun sanitizeValue(value: Any?, depth: Int): Any? {
227-
visit(depth)
228-
val collection = value?.asSanitizableCollectionOrNull()
217+
// A value at depth n is nested in n containers, counting the entry's root map.
218+
if (depth > MAX_ARGUMENT_DEPTH) {
219+
throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING)
220+
}
221+
if (--remainingValues < 0) {
222+
throw DropArguments(ArgumentDropReason.MAX_COUNT, MAX_COUNT_WARNING)
223+
}
229224

230-
return when {
231-
value is Map<*, *> -> sanitizeMap(value, depth)
232-
collection != null -> sanitizeCollection(collection, depth)
233-
else -> sanitizeScalar(value)
225+
if (value is Map<*, *>) {
226+
return sanitizeMap(value, depth)
234227
}
228+
val collection = value?.asCollectionOrNull() ?: return sanitizeScalar(value)
229+
230+
enter(value)
231+
// Iterated without reading the collection's size, which the host app controls.
232+
val sanitized = ArrayList<Any?>()
233+
for (element in collection) {
234+
sanitized += sanitizeValue(element, depth + 1)
235+
}
236+
activeContainers.remove(value)
237+
return sanitized
235238
}
236239

237240
private fun sanitizeScalar(value: Any?): Any? =
238241
when (value) {
239242
null,
240243
is Boolean -> value
241-
is Number ->
242-
if (value.isNonFinite()) {
243-
value.toString().also { consumeCharacters(it.length) }
244-
} else value
245-
is String -> value.also { consumeCharacters(it.length) }
246-
is CharSequence,
247-
is Char -> value.toString().also { consumeCharacters(it.length) }
248-
is Enum<*> -> value.name.also { consumeCharacters(it.length) }
244+
// JSON has no NaN or infinity, and Sentry's JSON writer throws for them, which would drop
245+
// the whole event these arguments are attached to. We record them as strings instead.
246+
is Number -> if (value.isNonFinite()) spendText(value.toString()) else value
247+
is CharSequence -> spendText(value)
248+
is Char -> spendText(value.toString())
249+
is Enum<*> -> spendText(value.name)
249250
else -> {
250251
warningState.logUnsupportedValueWarning(value::class.simpleName, logger)
251-
value.toString().also { consumeCharacters(it.length) }
252+
spendText(value.toString())
252253
}
253254
}
254255

255-
private fun Any.asSanitizableCollectionOrNull(): Collection<*>? =
256-
when (this) {
257-
is Collection<*> -> this
258-
is Array<*> -> asList()
259-
is BooleanArray -> asList()
260-
is ByteArray -> asList()
261-
is ShortArray -> asList()
262-
is IntArray -> asList()
263-
is LongArray -> asList()
264-
is FloatArray -> asList()
265-
is DoubleArray -> asList()
266-
is CharArray -> asList()
267-
else -> null
268-
}
269-
270256
/**
271-
* Records a visit to one value, enforcing the per-entry depth cap and the shared per-update
272-
* value budget. Throws [DropSubtree] to abort the current subtree when either is exceeded.
257+
* Returns [text] as a [String] after spending its characters.
258+
*
259+
* Checks [text]'s length before converting it, so that host app text that doesn't fit isn't
260+
* copied, and again after, in case a custom [CharSequence]'s length doesn't match its text.
273261
*/
274-
private fun visit(depth: Int) {
275-
if (depth > MAX_ARGUMENT_DEPTH) {
276-
throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE)
277-
}
278-
if (--remainingValues < 0) {
279-
throw DropSubtree(MAX_COUNT_WARNING, ArgumentDropReason.MAX_COUNT)
280-
}
262+
private fun spendText(text: CharSequence): String {
263+
checkFits(text.length)
264+
val string = text.toString()
265+
checkFits(string.length)
266+
remainingCharacters -= string.length
267+
return string
281268
}
282269

283-
private fun consumeCharacters(count: Int) {
284-
if (count > remainingCharacters) {
285-
throw DropSubtree(MAX_CHARACTER_WARNING, ArgumentDropReason.CHARACTER_LIMIT)
270+
private fun checkFits(characters: Int) {
271+
if (characters > remainingCharacters) {
272+
throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, MAX_CHARACTER_WARNING)
286273
}
287-
remainingCharacters -= count
288274
}
289275

290276
private fun enter(container: Any) {
291277
if (activeContainers.put(container, Unit) != null) {
292-
throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE)
278+
throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, STRUCTURE_WARNING)
293279
}
294280
}
295281

296-
private fun exit(container: Any) {
297-
activeContainers.remove(container)
282+
/**
283+
* Names only the colliding keys' types, as the keys themselves may contain host data.
284+
* Collisions are rare, so we re-scan [map] instead of tracking the original keys of every map.
285+
*/
286+
private fun duplicateKey(map: Map<*, *>, key: Any?, name: String): DropArguments {
287+
val otherKey = map.keys.firstOrNull { it !== key && it.toString() == name }
288+
return DropArguments(
289+
ArgumentDropReason.DUPLICATE_KEY,
290+
"A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same string " +
291+
"as another key (${otherKey?.let { it::class.simpleName }}). Dropping this entry's " +
292+
"arguments.",
293+
)
298294
}
299295

300296
/**
301-
* Control-flow signal to abort sanitization of the current subtree. Internal to
302-
* [ArgumentSanitizer].
303-
*
304-
* [reason] distinguishes entry-local drops from update-wide budget exhaustion. Overrides
297+
* Control-flow signal to drop an entry's arguments, logging [warning]. Overrides
305298
* [fillInStackTrace] to skip stack-trace capture.
306299
*/
307-
private class DropSubtree(val warning: String, val reason: ArgumentDropReason) :
300+
private class DropArguments(val reason: ArgumentDropReason, val warning: String) :
308301
RuntimeException() {
309302
override fun fillInStackTrace(): Throwable = this
310303
}
@@ -387,8 +380,6 @@ internal data class NormalizedSentryBackStackEntry(
387380

388381
companion object {
389382

390-
const val UNKNOWN_ENTRY_NAME = "/unknown"
391-
392383
/**
393384
* Trims [name] and adds a "/" prefix if one isn't already present.
394385
*
@@ -426,32 +417,32 @@ internal data class NormalizedSentryBackStackEntry(
426417
* ```
427418
*/
428419
fun serialize(): Map<String, Any?> = buildMap {
429-
put("entry", name)
430-
argumentsWithMetadata().takeIf { it.isNotEmpty() }?.let { put("entry_arguments", it) }
420+
put(BACK_STACK_ENTRY_KEY, name)
421+
argumentsWithMetadata()
422+
.takeIf { it.isNotEmpty() }
423+
?.let { put(BACK_STACK_ENTRY_ARGUMENTS_KEY, it) }
431424
}
432425
}
433426

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

437-
/** Why host-provided arguments were unavailable in emitted nav state. */
438-
internal enum class ArgumentDropReason(
439-
val serializedValue: String,
440-
val exhaustsUpdateBudget: Boolean = false,
441-
) {
442-
443-
CHARACTER_LIMIT("max_character_limit_exceeded", exhaustsUpdateBudget = true),
444-
DUPLICATE_KEY("duplicate_key"),
445-
INVALID_STRUCTURE("invalid_structure"),
446-
MAPPING_FAILED("mapping_failed"),
447-
MAX_COUNT("max_argument_count_exceeded", exhaustsUpdateBudget = true),
448-
SANITIZATION_FAILED("sanitization_failed");
449-
450-
companion object {
451-
const val ARGUMENT_DROP_REASON_KEY = "dropped_by_sentry"
430+
/** Returns this collection, or this array as a list, or `null` if it's neither. */
431+
private fun Any.asCollectionOrNull(): Collection<*>? =
432+
when (this) {
433+
is Collection<*> -> this
434+
is Array<*> -> asList()
435+
is BooleanArray -> asList()
436+
is ByteArray -> asList()
437+
is ShortArray -> asList()
438+
is IntArray -> asList()
439+
is LongArray -> asList()
440+
is FloatArray -> asList()
441+
is DoubleArray -> asList()
442+
is CharArray -> asList()
443+
else -> null
452444
}
453-
}
454445

455-
/** Whether this is a NaN or infinite Double or Float. */
446+
/** Whether this is a NaN or infinite `Double` or `Float`. */
456447
private fun Number.isNonFinite(): Boolean =
457448
(this is Double && !isFinite()) || (this is Float && !isFinite())

0 commit comments

Comments
 (0)