Skip to content

Commit 19c6402

Browse files
committed
ref(nav3): Unify bounded argument conversion
1 parent 8fb26b4 commit 19c6402

10 files changed

Lines changed: 2187 additions & 354 deletions

File tree

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

Lines changed: 461 additions & 0 deletions
Large diffs are not rendered by default.

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

Lines changed: 43 additions & 165 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,9 @@ 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
118
import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY
129
import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME
1310
import io.sentry.util.ExceptionUtils
14-
import java.util.IdentityHashMap
1511

1612
/**
1713
* Converts the host app back stack into a list of [NormalizedSentryBackStackEntry]s.
@@ -139,189 +135,75 @@ internal class BackStackConverter<T : Any>(
139135
)
140136

141137
/**
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.
138+
* Sanitizes a back stack entry's raw argument inputs and returns them in a
139+
* [serializable form][SanitizedArguments.values].
144140
*
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.
141+
* Internally, this class processes argument inputs returned by the [entryMapper] passed to the
142+
* outer converter instance. Those inputs can come from built-in or custom
143+
* [BackStackEntryMapper]s.
144+
*
145+
* Built-in mappers supply their own [ArgumentSource], while custom mappers typically supply an
146+
* ordinary map. [HostArgumentSource] adapts ordinary maps to the [ArgumentSource] contract, so
147+
* both paths can be handled by the same processing pipeline.
148148
*/
149149
internal class ArgumentSanitizer(
150150
private val logger: ILogger,
151151
private val warningState: WarningState,
152152
) {
153153

154-
private val activeContainers = IdentityHashMap<Any, Unit>()
155-
private var remainingValues = MAX_ARGUMENT_VALUES
156-
private var remainingCharacters = MAX_ARGUMENT_CHARACTERS
154+
// One instance per sanitizer, so the budgets span every entry of a back stack update.
155+
private val budget = ArgumentBudget()
157156
private var dropReason: ArgumentDropReason? = null
158157

159158
/**
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).
159+
* Sanitizes one entry's raw argument inputs and returns the result.
160+
*
161+
* [SanitizedArguments.values] will be empty if [raw] is empty or if the arguments were dropped.
162+
* Arguments can be dropped if:
163+
*
164+
* - a previously processed entry exceeded the shared value or character budget;
165+
* - an argument constraint is violated; or
166+
* - conversion fails.
167+
*
168+
* [SanitizedArguments.dropReason] will be non-null if and only if arguments are dropped.
163169
*/
164170
@Suppress("TooGenericExceptionCaught")
165171
fun sanitizeEntry(raw: Map<String, Any?>): SanitizedArguments {
166172
dropReason?.let { reason ->
167173
return SanitizedArguments(emptyMap(), reason)
168174
}
169175

176+
// Use the raw inputs' own source implementation when available; otherwise, provide them with
177+
// an adapter.
178+
val source =
179+
raw as? ArgumentSource
180+
?: HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) }
181+
val sink = TreeArgumentWriter(budget, rootIdentity = raw)
182+
183+
// A constraint violation the sink recorded takes precedence over whatever the source threw,
184+
// as for ArgumentSink.throwIfFailed. Here it's the reason the arguments are dropped with.
170185
return try {
171-
SanitizedArguments(sanitizeMap(raw, depth = 0))
172-
} catch (drop: DropSubtree) {
173-
if (drop.reason.exhaustsUpdateBudget) {
174-
dropReason = drop.reason
175-
}
176-
logger.log(WARNING, drop.warning)
177-
SanitizedArguments(emptyMap(), drop.reason)
186+
source.writeTo(sink)
187+
SanitizedArguments(sink.argumentsOrThrow())
188+
} catch (drop: DropArguments) {
189+
drop(sink.failure ?: drop)
178190
} catch (t: Throwable) {
179191
// Extracted maps may invoke host app code while iterating or stringifying values.
180192
ExceptionUtils.rethrowIfFatal(t)
181-
logger.log(WARNING, STRUCTURE_WARNING, t)
182-
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
207-
} finally {
208-
exit(value)
209-
}
210-
}
211-
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)
219-
}
220-
return sanitized
221-
} finally {
222-
exit(value)
223-
}
224-
}
225-
226-
private fun sanitizeValue(value: Any?, depth: Int): Any? {
227-
visit(depth)
228-
val collection = value?.asSanitizableCollectionOrNull()
229-
230-
return when {
231-
value is Map<*, *> -> sanitizeMap(value, depth)
232-
collection != null -> sanitizeCollection(collection, depth)
233-
else -> sanitizeScalar(value)
234-
}
235-
}
236-
237-
private fun sanitizeScalar(value: Any?): Any? =
238-
when (value) {
239-
null,
240-
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) }
249-
else -> {
250-
warningState.logUnsupportedValueWarning(value::class.simpleName, logger)
251-
value.toString().also { consumeCharacters(it.length) }
193+
sink.failure?.let {
194+
return drop(it)
252195
}
196+
logger.log(WARNING, DropArguments.STRUCTURE_WARNING, t)
197+
SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED)
253198
}
254-
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-
270-
/**
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.
273-
*/
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-
}
281-
}
282-
283-
private fun consumeCharacters(count: Int) {
284-
if (count > remainingCharacters) {
285-
throw DropSubtree(MAX_CHARACTER_WARNING, ArgumentDropReason.CHARACTER_LIMIT)
286-
}
287-
remainingCharacters -= count
288199
}
289200

290-
private fun enter(container: Any) {
291-
if (activeContainers.put(container, Unit) != null) {
292-
throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE)
201+
private fun drop(drop: DropArguments): SanitizedArguments {
202+
if (drop.reason.exhaustsUpdateBudget) {
203+
dropReason = drop.reason
293204
}
294-
}
295-
296-
private fun exit(container: Any) {
297-
activeContainers.remove(container)
298-
}
299-
300-
/**
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
305-
* [fillInStackTrace] to skip stack-trace capture.
306-
*/
307-
private class DropSubtree(val warning: String, val reason: ArgumentDropReason) :
308-
RuntimeException() {
309-
override fun fillInStackTrace(): Throwable = this
310-
}
311-
312-
companion object {
313-
314-
const val MAX_CHARACTER_WARNING =
315-
"Nav3 back stack update exceeded the argument character limit. Dropping arguments for " +
316-
"this and older entries."
317-
318-
const val MAX_COUNT_WARNING =
319-
"Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " +
320-
"and older entries."
321-
322-
const val STRUCTURE_WARNING =
323-
"Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " +
324-
"entry's arguments."
205+
drop.warning?.let { logger.log(WARNING, it) }
206+
return SanitizedArguments(emptyMap(), drop.reason)
325207
}
326208
}
327209

@@ -451,7 +333,3 @@ internal enum class ArgumentDropReason(
451333
const val ARGUMENT_DROP_REASON_KEY = "dropped_by_sentry"
452334
}
453335
}
454-
455-
/** Whether this is a NaN or infinite Double or Float. */
456-
private fun Number.isNonFinite(): Boolean =
457-
(this is Double && !isFinite()) || (this is Float && !isFinite())
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package io.sentry.compose.navigation3.internal.backstack
2+
3+
import com.google.common.truth.Truth.assertThat
4+
import kotlin.test.assertFailsWith
5+
import org.junit.Test
6+
7+
class ArgumentBudgetTest {
8+
9+
// spendText(CharSequence)
10+
11+
@Test
12+
fun `spendText(CharSequence) - returns text exactly as long as the remaining characters as a String`() {
13+
val budget = budgetWithCharactersRemaining(2)
14+
15+
val spent = budget.spendText(StringBuilder("ab"))
16+
17+
assertThat(spent).isEqualTo("ab")
18+
}
19+
20+
@Test
21+
fun `spendText(CharSequence) - spends the characters of the text`() {
22+
val budget = budgetWithCharactersRemaining(2)
23+
budget.spendText(StringBuilder("ab"))
24+
25+
val drop = assertFailsWith<DropArguments> { budget.spendText(StringBuilder("c")) }
26+
27+
assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT)
28+
assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING)
29+
}
30+
31+
@Test
32+
fun `spendText(CharSequence) - spends the characters of the text rather than its reported length`() {
33+
val budget = budgetWithCharactersRemaining(2)
34+
budget.spendText(CountingText(length = 0, text = "ab"))
35+
36+
val drop = assertFailsWith<DropArguments> { budget.spendText(StringBuilder("c")) }
37+
38+
assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT)
39+
}
40+
41+
@Test
42+
fun `spendText(CharSequence) - throws for the character limit without converting text that's too long`() {
43+
val budget = budgetWithCharactersRemaining(1)
44+
val text = CountingText(length = 2, text = "ab")
45+
46+
val drop = assertFailsWith<DropArguments> { budget.spendText(text) }
47+
48+
assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT)
49+
assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING)
50+
assertThat(text.toStringCalls).isEqualTo(0)
51+
}
52+
53+
@Test
54+
fun `spendText(CharSequence) - throws for the character limit when text is longer than its reported length`() {
55+
val budget = budgetWithCharactersRemaining(1)
56+
57+
val drop =
58+
assertFailsWith<DropArguments> { budget.spendText(CountingText(length = 1, text = "ab")) }
59+
60+
assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT)
61+
assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING)
62+
}
63+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package io.sentry.compose.navigation3.internal.backstack
2+
3+
import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS
4+
import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES
5+
6+
/** Returns a budget with only [remaining] values left, as if other entries spent the rest. */
7+
internal fun budgetWithValuesRemaining(remaining: Int): ArgumentBudget =
8+
ArgumentBudget().apply { repeat(MAX_ARGUMENT_VALUES - remaining) { spendValue() } }
9+
10+
/** Returns a budget with only [remaining] characters left, as if other entries spent the rest. */
11+
internal fun budgetWithCharactersRemaining(remaining: Int): ArgumentBudget =
12+
ArgumentBudget().apply { spendText("x".repeat(MAX_ARGUMENT_CHARACTERS - remaining)) }

0 commit comments

Comments
 (0)