diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt new file mode 100644 index 0000000000..2db1eab44c --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoder.kt @@ -0,0 +1,456 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.ArgumentSink +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.util.HttpUtils +import io.sentry.util.UrlUtils +import java.math.BigInteger +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerializationException +import kotlinx.serialization.SerializationStrategy +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.StructureKind +import kotlinx.serialization.encoding.AbstractEncoder +import kotlinx.serialization.encoding.CompositeEncoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.modules.EmptySerializersModule +import kotlinx.serialization.modules.SerializersModule + +/** + * Encodes a `@Serializable` back stack entry's properties as maps, lists, and scalars for use as + * [SentryBackStackEntry.arguments]. + * + * **Encoding formats** + * + * Uses a custom tree encoder because kotlinx-serialization-core provides no output format and Nav3 + * apps may not include kotlinx-serialization-json. + * + * - Classes and objects become property maps. Objects without properties record no arguments. + * + * - Lists and sets become lists. Maps use stringified scalar keys, such as strings, numbers, or + * enums. Structured map keys are rejected, matching kotlinx-serialization-json's defaults. + * + * - Enums use their serial names. Value classes use their underlying values. + * + * - Unsigned numbers (`UByte`, `UShort`, `UInt`, `ULong`) retain their unsigned values. + * + * - Polymorphic properties become `{"type": , "value": }`. + * + * - Entries encoded as scalars, such as by a custom string serializer, become `{"value": }`. + * + * - Properties marked `@Transient` are omitted. + * + * **Argument limits** + * + * Writes through [ArgumentSink], which enforces the same size and structural limits as for custom + * mappers. Violations throw [DropArguments], bounding traversal and allocation for cyclic, deeply + * nested, or large entries. + * + * Custom serializers can recurse without nesting properties, bypassing the sink's depth limit. The + * encoder separately limits nested serializer calls to [MAX_SERIALIZER_NESTING]. + * + * **Sensitive data** + * + * Values under property names or map keys matching Sentry's + * [sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist) + * are replaced with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE] without invoking their serializers. + * + * [ValueEncoder.encodeInline] also checks value classes' underlying property names, which aren't + * written as keys. [SensitiveKeyFilter] checks every output key as a safeguard against missed + * encoder checks. + * + * The denylist originates from filtering HTTP headers, cookies, and query parameters. This encoder + * applies it to navigation arguments as a baseline for sensitive-data filtering. + */ +internal object KotlinxPropertiesEncoder { + + /** Key for top-level values encoded without a map, such as by a custom serializer. */ + const val VALUE_KEY: String = "value" + + /** + * Encodes [value] with [serializer], writing its top-level properties to [sink]'s root map. + * + * Throws [SerializationException] when a value cannot be encoded, such as when a contextual or + * open polymorphic property has no registered serializer. Throws [DropArguments] when an argument + * limit is exceeded. + * + * Limit failures, including [MAX_SERIALIZER_NESTING], are recorded in [ArgumentSink.failure]. A + * serializer can catch [DropArguments] and then throw a different exception or return normally. + * Callers must check [ArgumentSink.failure] to determine whether to drop the arguments. + */ + fun encode(serializer: KSerializer, value: Any, sink: ArgumentSink) { + val filteredSink = SensitiveKeyFilter(sink) + RootEncoder(filteredSink, SerializerNesting(filteredSink)) + .encodeSerializableValue(serializer, value) + } + + /** Encodes a single value and writes it to [sink]. Structures are delegated to child encoders. */ + private open class ValueEncoder( + protected val sink: ArgumentSink, + protected val nesting: SerializerNesting, + ) : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + protected open fun put(value: Any?) { + sink.scalar(value) + } + + /** Replaces a filtered value with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE]. */ + protected open fun putFiltered() { + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + } + + override fun encodeSerializableValue(serializer: SerializationStrategy, value: T) { + nesting.enter() + try { + serializer.serialize(this, value) + } finally { + nesting.exit() + } + } + + override fun encodeValue(value: Any) { + put(value) + } + + override fun encodeNull() { + put(null) + } + + override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) { + put(enumDescriptor.getElementName(index)) + } + + override fun encodeInline(descriptor: SerialDescriptor): Encoder = + when { + descriptor.serialName in UNSIGNED_SERIAL_NAMES -> UnsignedEncoder(::put) + // A value class records only its underlying value, so its underlying property's name + // never reaches encodeElement. We check it here instead. + descriptor.hasSensitiveUnderlyingProperty() -> { + putFiltered() + DiscardingEncoder + } + else -> this + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder = + // The sink checks the depth as the structure begins, so a cyclic or deeply nested entry + // stops here instead of recursing until the stack overflows. + when (descriptor.kind) { + StructureKind.LIST -> { + sink.beginList() + ListEncoder(sink, nesting) + } + StructureKind.MAP -> { + sink.beginMap() + MapEncoder(sink, nesting) + } + else -> { + sink.beginMap() + ClassEncoder(sink, nesting) + } + } + } + + /** + * Encodes the entry itself. A class's properties, or a map's entries, are written to the sink's + * root map. Anything else (e.g., a custom serializer that encodes to a string) is written under + * [VALUE_KEY]. + */ + private class RootEncoder(sink: ArgumentSink, nesting: SerializerNesting) : + ValueEncoder(sink, nesting) { + + override fun put(value: Any?) { + sink.key(VALUE_KEY) + sink.scalar(value) + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder = + when (descriptor.kind) { + StructureKind.LIST -> { + sink.key(VALUE_KEY) + super.beginStructure(descriptor) + } + StructureKind.MAP -> MapEncoder(sink, nesting, isRoot = true) + else -> ClassEncoder(sink, nesting, isRoot = true) + } + } + + /** + * Writes the elements of a class, object, or polymorphic value as a map. + * + * If [isRoot] is true, uses the sink's already-open root map. + */ + private class ClassEncoder( + sink: ArgumentSink, + nesting: SerializerNesting, + private val isRoot: Boolean = false, + ) : ValueEncoder(sink, nesting) { + + override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean { + val name = descriptor.getElementName(index) + sink.key(name) + if (isSensitive(name)) { + // Skipping the element keeps a sensitive value's own serializers from running. + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + return false + } + return true + } + + override fun endStructure(descriptor: SerialDescriptor) { + if (!isRoot) { + sink.end() + } + } + } + + /** Writes the elements of a list or set. */ + private class ListEncoder(sink: ArgumentSink, nesting: SerializerNesting) : + ValueEncoder(sink, nesting) { + + override fun endStructure(descriptor: SerialDescriptor) { + sink.end() + } + } + + /** + * Writes alternating map keys and values. If [isRoot] is true, uses the sink's already-open root + * map. + * + * Keys must be scalars and are recorded as strings, matching kotlinx-serialization-json's + * defaults. Stringifying structured keys could exhaust memory before the sink checks their size. + * + * Sensitive key text causes the value to be filtered. If the key itself was filtered because of a + * sensitive value-class property, its original text is unavailable, so the value is filtered too. + */ + private class MapEncoder( + sink: ArgumentSink, + nesting: SerializerNesting, + private val isRoot: Boolean = false, + ) : ValueEncoder(sink, nesting) { + + private var isKey = true + private var isCurrentValueSensitive = false + + override fun encodeElement(descriptor: SerialDescriptor, index: Int): Boolean { + isKey = index % 2 == 0 + // Each key is encoded before its value, so isCurrentValueSensitive already applies to it. + if (!isKey && isCurrentValueSensitive) { + put(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + return false + } + return true + } + + override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { + if (isKey) { + throw SerializationException( + "Back stack entry has a map key that's a structure (${descriptor.serialName}). Only " + + "scalar map keys are supported.", + ) + } + return super.beginStructure(descriptor) + } + + override fun put(value: Any?) { + if (isKey) { + val key = value.toString() + // Let the sink reject oversized keys before the denylist scan allocates a lowercase copy. + sink.key(key) + isCurrentValueSensitive = isSensitive(key) + } else { + sink.scalar(value) + } + } + + override fun putFiltered() { + if (isKey) { + sink.key(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + isCurrentValueSensitive = true + } else { + super.putFiltered() + } + } + + override fun endStructure(descriptor: SerialDescriptor) { + if (!isRoot) { + sink.end() + } + } + } + + /** + * Maximum nested [Encoder.encodeSerializableValue] calls per entry. + * + * Allows room for property serializers and polymorphic or value-class wrappers within + * [MAX_ARGUMENT_DEPTH]. Guards against stack overflow when serializers recurse without nesting + * properties, which the argument depth limit can't detect. + */ + const val MAX_SERIALIZER_NESTING: Int = 64 + + /** + * Serial names of the unsigned number types, whose serializers encode them inline as their + * same-width signed storage value (e.g. `UInt.MAX_VALUE` as `-1`). + */ + private val UNSIGNED_SERIAL_NAMES = + setOf("kotlin.UByte", "kotlin.UShort", "kotlin.UInt", "kotlin.ULong") + + /** Whether this describes a value class whose underlying property's name is sensitive. */ + private fun SerialDescriptor.hasSensitiveUnderlyingProperty(): Boolean = + isInline && elementsCount == 1 && isSensitive(getElementName(0)) + + /** + * Discards a value class's underlying value after its filtered substitute has been recorded. + * + * Skips nested serializers, matching the handling of sensitive properties. + */ + private object DiscardingEncoder : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + override fun encodeValue(value: Any) = Unit + + override fun encodeNull() = Unit + + override fun encodeSerializableValue(serializer: SerializationStrategy, value: T) = Unit + + override fun encodeNullableSerializableValue( + serializer: SerializationStrategy, + value: T?, + ) = Unit + } + + /** + * Converts the signed storage value of an unsigned number back to its unsigned value and hands it + * to [put]. `ULong`s beyond `Long.MAX_VALUE` become [BigInteger]s. + */ + private class UnsignedEncoder(private val put: (Any?) -> Unit) : AbstractEncoder() { + + override val serializersModule: SerializersModule = EmptySerializersModule() + + override fun encodeValue(value: Any) { + put( + when (value) { + is Byte -> value.toUByte().toInt() + is Short -> value.toUShort().toInt() + is Int -> value.toUInt().toLong() + is Long -> if (value >= 0) value else BigInteger(value.toULong().toString()) + else -> value + }, + ) + } + } + + /** + * Limits nested [Encoder.encodeSerializableValue] calls for one entry, rejecting it through + * [sink] when nesting exceeds [MAX_SERIALIZER_NESTING]. + * + * After any sink failure, [enter] rethrows that failure to prevent further serializer calls, even + * if a serializer catches the original exception. + */ + private class SerializerNesting(private val sink: ArgumentSink) { + + private var calls = 0 + + fun enter() { + sink.failure?.let { throw it } + if (++calls > MAX_SERIALIZER_NESTING) { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + } + + fun exit() { + calls-- + } + } + + /** + * Replaces values under sensitive keys with [UrlUtils.SENSITIVE_DATA_SUBSTITUTE] before + * forwarding them to [sink]. Nested maps and lists under those keys are discarded. + * + * All encoders write through this filter to keep sensitive values out of the output. They also + * check keys before invoking serializers, avoiding work and potential failures for values that + * will be filtered. + */ + internal class SensitiveKeyFilter(private val sink: ArgumentSink) : ArgumentSink { + + /** The number of open maps and lists being discarded, or 0 if none. */ + private var discardDepth = 0 + private var isNextValueSensitive = false + + override val failure: DropArguments? + get() = sink.failure + + override fun beginMap(identity: Any?) { + begin { sink.beginMap(identity) } + } + + override fun beginList(identity: Any?) { + begin { sink.beginList(identity) } + } + + override fun key(name: String) { + if (discardDepth > 0) { + return + } + sink.key(name) + isNextValueSensitive = isSensitive(name) + } + + override fun scalar(value: Any?) { + if (discardDepth > 0) { + return + } + sink.scalar(if (isNextValueSensitive) UrlUtils.SENSITIVE_DATA_SUBSTITUTE else value) + isNextValueSensitive = false + } + + /** + * Delegates [compute] to [sink] so limits are checked before computing the value. + * + * Skips computation for filtered or discarded values. + */ + override fun computedScalar(compute: () -> Any?) { + if (discardDepth > 0) { + return + } + val isSensitive = isNextValueSensitive + sink.computedScalar { if (isSensitive) UrlUtils.SENSITIVE_DATA_SUBSTITUTE else compute() } + isNextValueSensitive = false + } + + override fun end() { + if (discardDepth > 0) { + discardDepth-- + } else { + sink.end() + } + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing = + sink.reject(reason, warning) + + private inline fun begin(beginInSink: () -> Unit) { + when { + discardDepth > 0 -> discardDepth++ + isNextValueSensitive -> { + sink.scalar(UrlUtils.SENSITIVE_DATA_SUBSTITUTE) + isNextValueSensitive = false + discardDepth = 1 + } + else -> beginInSink() + } + } + } + + /** Whether [key] is sensitive and its value should be filtered. */ + private fun isSensitive(key: String): Boolean = HttpUtils.containsSensitiveDataKey(key) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt new file mode 100644 index 0000000000..36e09db8ec --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxEncoding.kt @@ -0,0 +1,22 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentSink +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import kotlinx.serialization.KSerializer + +/** + * Encodes the properties of [value] with [serializer] into a map, with a budget of its own. Throws + * as [KotlinxPropertiesEncoder.encode] does. + */ +internal fun encodeToMap(serializer: KSerializer, value: T): Map { + val sink = TreeArgumentWriter(ArgumentBudget()) + encodeInto(serializer, value, sink) + return sink.argumentsOrThrow() +} + +/** Encodes the properties of [value] with [serializer] into [sink]. */ +@Suppress("UNCHECKED_CAST") +internal fun encodeInto(serializer: KSerializer, value: T, sink: ArgumentSink) { + KotlinxPropertiesEncoder.encode(serializer as KSerializer, value, sink) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt new file mode 100644 index 0000000000..6f3fa0c41e --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderFilteringTest.kt @@ -0,0 +1,516 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.util.UrlUtils +import kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderFilteringTest { + + @Serializable + enum class Sort { + @SerialName("price_asc") PRICE_ASC, + NEWEST, + } + + @Serializable @JvmInline value class ProductId(val value: String) + + @Serializable data class WithSensitiveProperty(val query: String, val password: String) + + @Serializable data class WithNullableSecret(val id: String, val password: String?) + + @Serializable data class WithSensitiveMapKey(val params: Map) + + @Serializable + data class WithSensitiveKeysInList(val nested: Map>>) + + @Serializable @JvmInline value class HeaderName(val name: String) + + @Serializable data class WithHeaderNameMapKeys(val headers: Map) + + /** A value class whose underlying property's name (`key`) is sensitive. */ + @Serializable @JvmInline value class SensitiveHeaderName(val key: String) + + @Serializable + data class WithSensitiveValueClassMapKeys(val headers: Map) + + @Serializable data class WithSensitiveValueClassMapValues(val params: Map) + + /** A map key that encodes as a [SensitiveHeaderName] when [isSecret], or else as its [name]. */ + @Serializable(with = MixedHeaderSerializer::class) + data class MixedHeader(val name: String, val isSecret: Boolean) + + object MixedHeaderSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.MixedHeader", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: MixedHeader) { + if (value.isSecret) { + encoder.encodeSerializableValue( + SensitiveHeaderName.serializer(), + SensitiveHeaderName(value.name), + ) + } else { + encoder.encodeString(value.name) + } + } + + override fun deserialize(decoder: Decoder): MixedHeader = + MixedHeader(decoder.decodeString(), isSecret = false) + } + + @Serializable data class WithMixedHeaderMapKeys(val headers: Map) + + @Serializable + data class WithSerialNames( + @SerialName("position") val side: String, + @SerialName("apiKey") val label: String, + ) + + @Serializable @JvmInline value class TokenRef(val token: String) + + @Serializable + data class WithSensitiveValueClassPropertyName( + val productId: ProductId, + val sessionRef: ProductId, + ) + + @Serializable + data class WithSensitiveUnderlyingPropertyName(val productId: ProductId, val reference: TokenRef) + + @Serializable data class WithValueClassList(val references: List) + + @Serializable data class Credentials(val user: String) + + @Serializable @JvmInline value class CredentialsRef(val credentials: Credentials) + + @Serializable data class WithStructuredValueClass(val owner: CredentialsRef) + + @Serializable data class WithLargeSecret(val id: String, val refreshTokens: List) + + @Serializable data class WithLargeSecretMapValue(val params: Map>) + + @Serializable + data class WithUnencodableSecret( + val id: String, + @Serializable(with = ThrowingSerializer::class) val authToken: String, + ) + + @Serializable + data class WithUnencodableSecretMapValue( + val params: Map, + ) + + /** A value class whose underlying property's name (`token`) is sensitive. */ + @Serializable + @JvmInline + value class UnencodableSecretRef( + @Serializable(with = ThrowingSerializer::class) val token: String, + ) + + @Serializable data class WithUnencodableSecretRef(val id: String, val ref: UnencodableSecretRef) + + object ThrowingSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.Throwing", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: String): Unit = error("serializer ran") + + override fun deserialize(decoder: Decoder): String = decoder.decodeString() + } + + @Serializable @JvmInline value class Wrapped(val raw: String) + + @Serializable + data class SecretsProfile(val name: String, @SerialName("PASSWORD") val password: String) + + @Serializable data class SecretsItem(val sku: String, val apiKey: String) + + @Serializable + sealed interface SecretsOrigin { + @Serializable + @SerialName("login") + data class Login(val user: String, val authToken: String) : SecretsOrigin + } + + /** Places sensitive keys at every structural position the encoder supports. */ + @Serializable + data class SecretsEverywhere( + val query: String, + val authToken: String, + val password: String?, + val sort: Sort, + val profile: SecretsProfile, + val items: List, + val headers: Map, + val filters: Map>, + val rows: List>, + val grid: List>>, + val label: Wrapped, + val sessionSecret: Wrapped, + val origin: SecretsOrigin, + val authOrigin: SecretsOrigin, + val refreshTokens: List, + val credentials: Map, + val reference: TokenRef, + ) + + // Sensitive values + + @Test + fun `encode() - replaces the values of sensitive properties with the Filtered substitute`() { + val entry = WithSensitiveProperty(query = "shoes", password = "secret") + + val encoded = encodeToMap(WithSensitiveProperty.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("query" to "shoes", "password" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces a null sensitive property with the Filtered substitute`() { + val entry = WithNullableSecret(id = "1", password = null) + + val encoded = encodeToMap(WithNullableSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "password" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces the values of sensitive map keys with the Filtered substitute`() { + val entry = WithSensitiveMapKey(mapOf("query" to "shoes", "authToken" to "secret")) + + val encoded = encodeToMap(WithSensitiveMapKey.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "params" to mapOf("query" to "shoes", "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces the values of sensitive map keys in maps nested in lists with the Filtered substitute`() { + val entry = + WithSensitiveKeysInList( + nested = mapOf("items" to listOf(mapOf("authToken" to "secret", "query" to "shoes"))), + ) + + val encoded = encodeToMap(WithSensitiveKeysInList.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "nested" to + mapOf( + "items" to + listOf( + mapOf("authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE, "query" to "shoes"), + ), + ), + ), + ) + } + + @Test + fun `encode() - replaces the values of value class map keys whose text is sensitive with the Filtered substitute`() { + val entry = + WithHeaderNameMapKeys( + mapOf(HeaderName("Accept") to "json", HeaderName("Authorization") to "Bearer abc123"), + ) + + val encoded = encodeToMap(WithHeaderNameMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf("Accept" to "json", "Authorization" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces map entries with the Filtered substitute if their key's underlying property is sensitive`() { + val entry = + WithSensitiveValueClassMapKeys( + mapOf( + SensitiveHeaderName("Authorization") to "Bearer LEAKED-SECRET-1", + SensitiveHeaderName("X-Api-Key") to "LEAKED-SECRET-2", + // Filtered by its underlying property name even though its text isn't sensitive. + SensitiveHeaderName("Accept") to "LEAKED-SECRET-3", + ), + ) + + val encoded = encodeToMap(WithSensitiveValueClassMapKeys.serializer(), entry) + + // The filtered keys share one text, so they collapse to a single entry. + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf(UrlUtils.SENSITIVE_DATA_SUBSTITUTE to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + assertThat(leavesOf(encoded).values.filter { it.contains("LEAKED-SECRET") }).isEmpty() + } + + @Test + fun `encode() - replaces a map value with the Filtered substitute based only on its own key`() { + val entry = + WithMixedHeaderMapKeys( + mapOf( + MixedHeader("Accept", isSecret = false) to "VISIBLE-1", + MixedHeader("Authorization", isSecret = true) to "LEAKED-SECRET-1", + MixedHeader("Accept-Language", isSecret = false) to "VISIBLE-2", + ), + ) + + val encoded = encodeToMap(WithMixedHeaderMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "headers" to + mapOf( + "Accept" to "VISIBLE-1", + UrlUtils.SENSITIVE_DATA_SUBSTITUTE to UrlUtils.SENSITIVE_DATA_SUBSTITUTE, + "Accept-Language" to "VISIBLE-2", + ), + ), + ) + } + + // Security regression test: a filtered key must not overwrite or merge with a visible entry. + @Test + fun `encode() - drops the arguments for a duplicate key when a filtered map key matches an unfiltered key's text`() { + val entry = + WithMixedHeaderMapKeys( + mapOf( + MixedHeader(UrlUtils.SENSITIVE_DATA_SUBSTITUTE, isSecret = false) to "VISIBLE", + MixedHeader("Authorization", isSecret = true) to "LEAKED-SECRET", + ), + ) + + val exception = + assertFailsWith { + encodeToMap(WithMixedHeaderMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - replaces map values with the Filtered substitute when their underlying property is sensitive`() { + val entry = WithSensitiveValueClassMapValues(mapOf("reference" to TokenRef("abc123"))) + + val encoded = encodeToMap(WithSensitiveValueClassMapValues.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("params" to mapOf("reference" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE))) + } + + @Test + fun `encode() - replaces the values of properties whose serial name is sensitive with the Filtered substitute`() { + val entry = WithSerialNames(side = "left", label = "secret") + + val encoded = encodeToMap(WithSerialNames.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("position" to "left", "apiKey" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces value class properties whose property name is sensitive with the Filtered substitute`() { + val entry = + WithSensitiveValueClassPropertyName( + productId = ProductId("p-1"), + sessionRef = ProductId("secret"), + ) + + val encoded = encodeToMap(WithSensitiveValueClassPropertyName.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("productId" to "p-1", "sessionRef" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces properties with the Filtered substitute when their underlying property is sensitive`() { + val entry = + WithSensitiveUnderlyingPropertyName(productId = ProductId("p-1"), reference = TokenRef("abc")) + + val encoded = encodeToMap(WithSensitiveUnderlyingPropertyName.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("productId" to "p-1", "reference" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces a top-level value with the Filtered substitute when its underlying property is sensitive`() { + val encoded = encodeToMap(TokenRef.serializer(), TokenRef("abc123")) + + assertThat(encoded) + .isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - replaces list elements with the Filtered substitute when their underlying property is sensitive`() { + val entry = WithValueClassList(listOf(TokenRef("abc"), TokenRef("def"))) + + val encoded = encodeToMap(WithValueClassList.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "references" to + listOf(UrlUtils.SENSITIVE_DATA_SUBSTITUTE, UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - replaces a wrapped structure with the Filtered substitute if its underlying property is sensitive`() { + val entry = WithStructuredValueClass(CredentialsRef(Credentials(user = "jane"))) + + val encoded = encodeToMap(WithStructuredValueClass.serializer(), entry) + + assertThat(encoded).isEqualTo(mapOf("owner" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - counts a sensitive property as one value regardless of its size`() { + val entry = + WithLargeSecret(id = "1", refreshTokens = List(MAX_ARGUMENT_VALUES + 1) { "token$it" }) + + val encoded = encodeToMap(WithLargeSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "refreshTokens" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - counts a sensitive map value as one value regardless of its size`() { + val entry = + WithLargeSecretMapValue( + params = mapOf("query" to listOf(1), "authToken" to List(MAX_ARGUMENT_VALUES + 1) { it }), + ) + + val encoded = encodeToMap(WithLargeSecretMapValue.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "params" to + mapOf("query" to listOf(1), "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE), + ), + ) + } + + @Test + fun `encode() - doesn't run the serializers of sensitive properties`() { + val entry = WithUnencodableSecret(id = "1", authToken = "secret") + + val encoded = encodeToMap(WithUnencodableSecret.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("id" to "1", "authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `encode() - doesn't run the serializers of sensitive map values`() { + val entry = WithUnencodableSecretMapValue(mapOf("authToken" to "secret")) + + val encoded = encodeToMap(WithUnencodableSecretMapValue.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("params" to mapOf("authToken" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE))) + } + + @Test + fun `encode() - doesn't run the serializers wrapped by a value class with a sensitive underlying property`() { + val entry = WithUnencodableSecretRef(id = "1", ref = UnencodableSecretRef("secret")) + + val encoded = encodeToMap(WithUnencodableSecretRef.serializer(), entry) + + assertThat(encoded).isEqualTo(mapOf("id" to "1", "ref" to UrlUtils.SENSITIVE_DATA_SUBSTITUTE)) + } + + /** + * Deliberately structure-agnostic: rather than asserting the encoded shape, this walks the whole + * output looking for any secret at the structural positions [SecretsEverywhere] covers. It checks + * the end result only, so it passes whether the encoders' own checks or `SensitiveKeyFilter` + * filter each value; it can't tell whether an encoding path bypasses the encoders' checks. + */ + @Test + fun `encode() - doesn't record the values of sensitive keys anywhere in the encoded tree`() { + val entry = + SecretsEverywhere( + query = "VISIBLE-1", + authToken = "LEAKED-SECRET-1", + password = "LEAKED-SECRET-2", + sort = Sort.NEWEST, + profile = SecretsProfile(name = "VISIBLE-2", password = "LEAKED-SECRET-3"), + items = + listOf( + SecretsItem(sku = "VISIBLE-3", apiKey = "LEAKED-SECRET-4"), + SecretsItem(sku = "VISIBLE-4", apiKey = "LEAKED-SECRET-5"), + ), + headers = mapOf("accept" to "VISIBLE-5", "X-Api-Key" to "LEAKED-SECRET-6"), + filters = mapOf("color" to mapOf("shade" to "VISIBLE-6", "sessionId" to "LEAKED-SECRET-7")), + rows = listOf(mapOf("note" to "VISIBLE-7", "Bearer" to "LEAKED-SECRET-8")), + grid = listOf(listOf(mapOf("cell" to "VISIBLE-8", "jwt" to "LEAKED-SECRET-9"))), + label = Wrapped("VISIBLE-9"), + sessionSecret = Wrapped("LEAKED-SECRET-10"), + origin = SecretsOrigin.Login(user = "VISIBLE-10", authToken = "LEAKED-SECRET-11"), + authOrigin = SecretsOrigin.Login(user = "LEAKED-SECRET-12", authToken = "LEAKED-SECRET-13"), + refreshTokens = listOf("LEAKED-SECRET-14", "LEAKED-SECRET-15"), + credentials = mapOf("user" to "LEAKED-SECRET-16"), + reference = TokenRef("LEAKED-SECRET-17"), + ) + + val leaves = leavesOf(encodeToMap(SecretsEverywhere.serializer(), entry)) + + assertThat(leaves.filterValues { it.contains("LEAKED-SECRET") }).isEmpty() + assertThat(leaves.values).containsAtLeastElementsIn((1..10).map { "VISIBLE-$it" } + "NEWEST") + // authToken, password, PASSWORD, apiKey (x2), X-Api-Key, sessionId, Bearer, jwt, + // sessionSecret, origin's authToken, authOrigin, refreshTokens, credentials, and reference + // (whose value class wraps a token). + assertThat(leaves.values.count { it == UrlUtils.SENSITIVE_DATA_SUBSTITUTE }).isEqualTo(15) + } + + /** + * Flattens [value] into its map keys and scalar values, stringified and keyed by their path, so + * that a failing assertion names where each one sits. + */ + private fun leavesOf( + value: Any?, + path: String = "", + leaves: MutableMap = LinkedHashMap(), + ): Map { + when (value) { + is Map<*, *> -> + value.forEach { (key, child) -> + leaves["$path.$key (key)"] = key.toString() + leavesOf(child, "$path.$key", leaves) + } + is Iterable<*> -> + value.forEachIndexed { index, child -> leavesOf(child, "$path[$index]", leaves) } + else -> leaves[path] = value.toString() + } + return leaves + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt new file mode 100644 index 0000000000..ea2bafa11b --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderLimitsTest.kt @@ -0,0 +1,422 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +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 +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import io.sentry.compose.navigation3.internal.backstack.budgetWithValuesRemaining +import kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderLimitsTest { + + @Serializable + class SelfReferencing { + var next: SelfReferencing? = null + } + + /** Nests a polymorphic and a value class serializer at every other level. */ + @Serializable @JvmInline value class LayerRef(val layer: Layer) + + @Serializable + sealed interface Layer { + @Serializable @SerialName("node") data class Node(val child: LayerRef) : Layer + + @Serializable @SerialName("leaf") data class Leaf(val value: String) : Layer + } + + /** + * Encodes a link with [LinkSerializer], and if that throws [DropArguments], records it and + * encodes a fallback with [recover] instead. + */ + internal class RecoveringLinkSerializer(private val recover: (Encoder) -> Unit) : + KSerializer { + var caught: DropArguments? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.RecoveringLink", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + try { + encoder.encodeSerializableValue(LinkSerializer, value) + } catch (e: DropArguments) { + caught = e + recover(encoder) + } + } + + override fun deserialize(decoder: Decoder): Link = Link(decoder.decodeString()) + } + + /** A value that [CatchingWriteSerializer] encodes. */ + private class Code(val code: String) + + /** Writes nothing, counting its calls in [calls]. */ + private class WritesNothingSerializer : KSerializer { + var calls = 0 + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.WritesNothing", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: String) { + calls++ + } + + override fun deserialize(decoder: Decoder): String = throw UnsupportedOperationException() + } + + /** + * Writes the code, recording a [DropArguments] that throws in [caught], then encodes a fallback + * with [fallback]. + */ + private class CatchingWriteSerializer(private val fallback: KSerializer) : + KSerializer { + var caught: DropArguments? = null + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.CatchingWrite", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Code) { + try { + encoder.encodeString(value.code) + } catch (e: DropArguments) { + caught = e + } + encoder.encodeSerializableValue(fallback, "fallback") + } + + override fun deserialize(decoder: Decoder): Code = throw UnsupportedOperationException() + } + + // Character limit + + @Test + fun `encode() - encodes an entry with the maximum number of characters, counting property names`() { + // The Box's property name and its value together are the maximum. + val value = "x".repeat(MAX_ARGUMENT_CHARACTERS - "value".length) + val (serializer, entry) = boxed(depth = 1, value = value, String.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to value)) + } + + @Test + fun `encode() - drops the arguments for the character limit when property names put an entry one character over`() { + val value = "x".repeat(MAX_ARGUMENT_CHARACTERS - "value".length + 1) + val (serializer, entry) = boxed(depth = 1, value = value, String.serializer()) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(exception.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + } + + @Test + fun `encode() - encodes a map key of the maximum number of characters`() { + // A top-level map has no property names, and Int values, so the key is the only text counted. + val value = mapOf("k".repeat(MAX_ARGUMENT_CHARACTERS) to 1) + val (serializer, entry) = + boxed(depth = 0, value = value, MapSerializer(String.serializer(), Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(value) + } + + @Test + fun `encode() - drops the arguments for the character limit when a map key is too long`() { + val (serializer, entry) = + boxed( + depth = 0, + value = mapOf("k".repeat(MAX_ARGUMENT_CHARACTERS + 1) to 1), + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(exception.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + } + + // Depth limit + + @Test + fun `encode() - encodes a value at the maximum depth`() { + val (serializer, entry) = boxed(depth = MAX_ARGUMENT_DEPTH, value = "leaf", String.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = "leaf")) + } + + @Test + fun `encode() - encodes polymorphic and value class properties at the maximum depth`() { + // The leaf's value sits at depth 2, and each node nests its child two levels deeper. + val nodes = (MAX_ARGUMENT_DEPTH - 2) / 2 + var layer: Layer = Layer.Leaf("leaf") + repeat(nodes) { layer = Layer.Node(LayerRef(layer)) } + + val encoded = encodeToMap(LayerRef.serializer(), LayerRef(layer)) + + var expected: Map = mapOf("type" to "leaf", "value" to mapOf("value" to "leaf")) + repeat(nodes) { expected = mapOf("type" to "node", "value" to mapOf("child" to expected)) } + assertThat(encoded).isEqualTo(expected) + } + + @Test + fun `encode() - drops the arguments for invalid structure when a value is nested past the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH + 1, value = "leaf", String.serializer()) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for a list, so an empty list fits at the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH, value = emptyList(), ListSerializer(String.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded) + .isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = emptyList())) + } + + @Test + fun `encode() - adds one level of depth for a list, so a list's elements can't be past the maximum depth`() { + val (serializer, entry) = + boxed(depth = MAX_ARGUMENT_DEPTH, value = listOf("a"), ListSerializer(String.serializer())) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for a map, so a map's values can't be past the maximum depth`() { + val (serializer, entry) = + boxed( + depth = MAX_ARGUMENT_DEPTH, + value = mapOf("a" to 1), + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - adds one level of depth for an object, so an object without properties fits at the maximum depth`() { + val (serializer, entry) = boxed(depth = MAX_ARGUMENT_DEPTH, value = Home, Home.serializer()) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded) + .isEqualTo(boxedArguments(depth = MAX_ARGUMENT_DEPTH, value = emptyMap())) + } + + @Test + fun `encode() - stops at the depth limit when an entry references itself`() { + val entry = SelfReferencing().apply { next = this } + + val exception = + assertFailsWith { encodeToMap(SelfReferencing.serializer(), entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArguments.STRUCTURE_WARNING) + } + + // Value limit + + @Test + fun `encode() - encodes an entry with the maximum number of values`() { + // The list property and its elements are the maximum. + val values = List(MAX_ARGUMENT_VALUES - 1) { it } + val (serializer, entry) = boxed(depth = 1, value = values, ListSerializer(Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to values)) + } + + @Test + fun `encode() - drops the arguments for count when an entry has one value too many`() { + val (serializer, entry) = + boxed(depth = 1, value = List(MAX_ARGUMENT_VALUES) { it }, ListSerializer(Int.serializer())) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(exception.warning).isEqualTo(DropArguments.MAX_COUNT_WARNING) + } + + @Test + fun `encode() - doesn't count map keys as values`() { + // The map property and its values are the maximum; counting the keys would exceed it. + val values = (0 until MAX_ARGUMENT_VALUES - 1).associate { "item$it" to it } + val (serializer, entry) = + boxed(depth = 1, value = values, MapSerializer(String.serializer(), Int.serializer())) + + val encoded = encodeToMap(serializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to values)) + } + + @Test + fun `encode() - drops the arguments for count when a map has one value too many`() { + val (serializer, entry) = + boxed( + depth = 1, + value = (0 until MAX_ARGUMENT_VALUES).associate { "item$it" to it }, + MapSerializer(String.serializer(), Int.serializer()), + ) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(exception.warning).isEqualTo(DropArguments.MAX_COUNT_WARNING) + } + + // Serializer nesting limit + + @Test + fun `encode() - encodes custom serializers nested up to the maximum number of calls`() { + // The top-level serializer is the first call, and each next link nests one more. + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val encoded = encodeToMap(LinkSerializer, entry) + + assertThat(encoded).isEqualTo(mapOf("value" to "leaf")) + } + + @Test + fun `encode() - counts only nested serializer calls toward the nesting limit`() { + // Each element's serializer call returns before the next element's begins. + val values = List(KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) { it } + + val encoded = encodeToMap(ListSerializer(Int.serializer()), values) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to values)) + } + + @Test + fun `encode() - drops the arguments for invalid structure when custom serializers nest too many calls deep`() { + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) + + val exception = assertFailsWith { encodeToMap(LinkSerializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - drops the arguments for invalid structure when a custom serializer recurses through a cycle`() { + val entry = Link("leaf").apply { next = this } + + val exception = assertFailsWith { encodeToMap(LinkSerializer, entry) } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - records the nesting failure on the sink`() { + val sink = TreeArgumentWriter(ArgumentBudget()) + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING + 1) + + val exception = assertFailsWith { encodeInto(LinkSerializer, entry, sink) } + + assertThat(sink.failure).isSameInstanceAs(exception) + } + + @Test + fun `encode() - keeps failing when a serializer catches the nesting failure and calls another serializer`() { + // The recovering serializer is the first call, so its link chain nests one call too many. + val serializer = RecoveringLinkSerializer { + it.encodeSerializableValue(String.serializer(), "fallback") + } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - throws the caught nesting failure when a serializer catches it and writes a value directly`() { + val serializer = RecoveringLinkSerializer { it.encodeString("fallback") } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val exception = assertFailsWith { encodeToMap(serializer, entry) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(exception.warning).isEqualTo(DropArguments.STRUCTURE_WARNING) + } + + @Test + fun `encode() - keeps the nesting failure on the sink when a serializer catches it and returns`() { + val sink = TreeArgumentWriter(ArgumentBudget()) + val serializer = RecoveringLinkSerializer {} + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + encodeInto(serializer, entry, sink) + + val exception = assertFailsWith { sink.argumentsOrThrow() } + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `encode() - propagates a serializer's exception in place of the nesting failure, which the sink keeps`() { + val error = SerializationException("replaced") + val sink = TreeArgumentWriter(ArgumentBudget()) + val serializer = RecoveringLinkSerializer { throw error } + val entry = linked(length = KotlinxPropertiesEncoder.MAX_SERIALIZER_NESTING) + + val thrown = assertFailsWith { encodeInto(serializer, entry, sink) } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(sink.failure).isSameInstanceAs(serializer.caught) + assertThat(sink.failure?.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + @Test + fun `encode() - doesn't run another serializer after a serializer catches the sink's broken limit`() { + val fallback = WritesNothingSerializer() + val serializer = CatchingWriteSerializer(fallback) + val sink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + + val exception = assertFailsWith { encodeInto(serializer, Code("x"), sink) } + + assertThat(exception).isSameInstanceAs(serializer.caught) + assertThat(exception.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(fallback.calls).isEqualTo(0) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt new file mode 100644 index 0000000000..0fe2cfe547 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxPropertiesEncoderTest.kt @@ -0,0 +1,508 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import java.math.BigInteger +import kotlin.jvm.JvmInline +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Polymorphic +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.Transient +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.junit.Test + +class KotlinxPropertiesEncoderTest { + + @Serializable + data class Product( + val name: String, + val inStock: Boolean, + val price: Double, + val grade: Char, + val quantity: Long, + val note: String?, + ) + + @Serializable data class Filters(val minPrice: Int, val brands: List) + + @Serializable data class WithNestedClass(val query: String, val filters: Filters) + + @Serializable data class WithCollections(val names: List, val tags: Set) + + @Serializable + enum class Sort { + @SerialName("price_asc") PRICE_ASC, + NEWEST, + } + + @Serializable data class WithEnums(val primary: Sort, val secondary: Sort) + + @Serializable @JvmInline value class ProductId(val value: String) + + @Serializable data class WithValueClass(val productId: ProductId) + + @Serializable data class WithDefault(val query: String, val page: Int = 1) + + @Serializable + data class WithTransient(val query: String, @Transient val cached: String = "not recorded") + + @Serializable + sealed interface Origin { + @Serializable @SerialName("search") data class Search(val query: String) : Origin + + @Serializable @SerialName("deeplink") data object DeepLink : Origin + } + + @Serializable data class WithOrigin(val productId: String, val origin: Origin) + + @Serializable(with = CustomSerializer::class) data class CustomSerialized(val id: String) + + object CustomSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: CustomSerialized) { + encoder.encodeString(value.id) + } + + override fun deserialize(decoder: Decoder): CustomSerialized = + CustomSerialized(decoder.decodeString()) + } + + @Serializable + data class WithUnsignedNumbers( + val uByte: UByte, + val uShort: UShort, + val uInt: UInt, + val uLong: ULong, + ) + + @Serializable data class WithULong(val uLong: ULong) + + @Serializable + data class WithSignedNumbers(val byte: Byte, val short: Short, val int: Int, val long: Long) + + @Serializable data class WithIntMapKeys(val counts: Map) + + @Serializable + data class WithEncodedMapKeys(val bySort: Map, val byRank: Map) + + @Serializable data class WithNullableMapKeys(val counts: Map) + + @Serializable + data class WithWrappedMapKeys( + val byProduct: Map, + val byCustom: Map, + ) + + /** A key that's recorded by its [name] alone, so keys that differ only in [version] collide. */ + @Serializable(with = VersionedNameSerializer::class) + data class VersionedName(val name: String, val version: Int) + + object VersionedNameSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.VersionedName", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: VersionedName) { + encoder.encodeString(value.name) + } + + override fun deserialize(decoder: Decoder): VersionedName = + VersionedName(decoder.decodeString(), version = 0) + } + + @Serializable data class WithVersionedNameMapKeys(val byName: Map) + + @Serializable data class Point(val x: Int) + + @Serializable data class WithPointMapKeys(val byPoint: Map) + + @Serializable @JvmInline value class PointRef(val point: Point) + + @Serializable data class WithPointRefMapKeys(val byPointRef: Map) + + @Serializable data class WithListMapKeys(val byList: Map, Int>) + + @Serializable data class WithMapMapKeys(val byMap: Map, Int>) + + @Serializable data class WithOriginMapKeys(val byOrigin: Map) + + @Serializable data class WithNestedPointMapKeys(val groups: List>) + + interface OpenOrigin + + @Serializable data class WithOpenPolymorphic(val id: String, @Polymorphic val origin: OpenOrigin) + + // Encoded shapes + + @Test + fun `encode() - encodes a class as a map from property name to value`() { + val entry = + Product( + name = "shoes", + inStock = false, + price = 0.5, + grade = 'A', + quantity = 3L, + note = null, + ) + + val encoded = encodeToMap(Product.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf( + "name" to "shoes", + "inStock" to false, + "price" to 0.5, + "grade" to "A", + "quantity" to 3L, + "note" to null, + ), + ) + } + + @Test + fun `encode() - encodes a nested class as a nested map`() { + val entry = WithNestedClass("shoes", Filters(minPrice = 10, brands = listOf("a"))) + + val encoded = encodeToMap(WithNestedClass.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("query" to "shoes", "filters" to mapOf("minPrice" to 10, "brands" to listOf("a"))), + ) + } + + @Test + fun `encode() - encodes lists and sets as lists`() { + val entry = WithCollections(names = listOf("a", null), tags = setOf("new", "sale")) + + val encoded = encodeToMap(WithCollections.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("names" to listOf("a", null), "tags" to listOf("new", "sale"))) + } + + @Test + fun `encode() - encodes enums by their serial name`() { + val encoded = encodeToMap(WithEnums.serializer(), WithEnums(Sort.PRICE_ASC, Sort.NEWEST)) + + assertThat(encoded).isEqualTo(mapOf("primary" to "price_asc", "secondary" to "NEWEST")) + } + + @Test + fun `encode() - encodes value classes by their underlying value`() { + val encoded = encodeToMap(WithValueClass.serializer(), WithValueClass(ProductId("p-1"))) + + assertThat(encoded).isEqualTo(mapOf("productId" to "p-1")) + } + + @Test + fun `encode() - encodes properties that have their default values`() { + val encoded = encodeToMap(WithDefault.serializer(), WithDefault(query = "shoes")) + + assertThat(encoded).isEqualTo(mapOf("query" to "shoes", "page" to 1)) + } + + @Test + fun `encode() - omits @Transient properties`() { + val encoded = encodeToMap(WithTransient.serializer(), WithTransient(query = "shoes")) + + assertThat(encoded).isEqualTo(mapOf("query" to "shoes")) + } + + @Test + fun `encode() - encodes polymorphic properties as their serial name and value`() { + val search = encodeToMap(WithOrigin.serializer(), WithOrigin("p-1", Origin.Search("shoes"))) + val deepLink = encodeToMap(WithOrigin.serializer(), WithOrigin("p-1", Origin.DeepLink)) + + assertThat(search) + .isEqualTo( + mapOf( + "productId" to "p-1", + "origin" to mapOf("type" to "search", "value" to mapOf("query" to "shoes")), + ), + ) + assertThat(deepLink) + .isEqualTo( + mapOf( + "productId" to "p-1", + "origin" to mapOf("type" to "deeplink", "value" to emptyMap()), + ), + ) + } + + @Test + fun `encode() - encodes an object without properties as an empty map`() { + val encoded = encodeToMap(Home.serializer(), Home) + + assertThat(encoded).isEmpty() + } + + @Test + fun `encode() - wraps a top-level value that doesn't encode to a structure under the value key`() { + val encoded = encodeToMap(CustomSerializer, CustomSerialized("abc")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "abc")) + } + + @Test + fun `encode() - wraps a top-level list under the value key`() { + val encoded = encodeToMap(ListSerializer(String.serializer()), listOf("a", "b")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to listOf("a", "b"))) + } + + @Test + fun `encode() - encodes a top-level map's entries as the arguments`() { + val encoded = + encodeToMap(MapSerializer(String.serializer(), Int.serializer()), mapOf("page" to 2)) + + assertThat(encoded).isEqualTo(mapOf("page" to 2)) + } + + @Test + fun `encode() - wraps a top-level value class's underlying value under the value key`() { + val encoded = encodeToMap(ProductId.serializer(), ProductId("p-1")) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "p-1")) + } + + @Test + fun `encode() - wraps a top-level enum's serial name under the value key`() { + val encoded = encodeToMap(Sort.serializer(), Sort.PRICE_ASC) + + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to "price_asc")) + } + + @Test + fun `encode() - encodes a top-level polymorphic value's serial name and value as the arguments`() { + val encoded = encodeToMap(Origin.serializer(), Origin.Search("shoes")) + + assertThat(encoded).isEqualTo(mapOf("type" to "search", "value" to mapOf("query" to "shoes"))) + } + + // Numbers + + @Test + fun `encode() - encodes unsigned numbers by their unsigned value`() { + val entry = + WithUnsignedNumbers( + uByte = UByte.MAX_VALUE, + uShort = UShort.MAX_VALUE, + uInt = UInt.MAX_VALUE, + uLong = Long.MAX_VALUE.toULong(), + ) + + val encoded = encodeToMap(WithUnsignedNumbers.serializer(), entry) + + val uByteMax: Int = 255 + val uShortMax: Int = 65_535 + val uIntMax: Long = 4_294_967_295L + assertThat(encoded) + .isEqualTo( + mapOf( + "uByte" to uByteMax, + "uShort" to uShortMax, + "uInt" to uIntMax, + "uLong" to Long.MAX_VALUE, + ), + ) + } + + @Test + fun `encode() - wraps a top-level unsigned number's unsigned value under the value key`() { + val encoded = encodeToMap(UInt.serializer(), UInt.MAX_VALUE) + + val uIntMax: Long = 4_294_967_295L + assertThat(encoded).isEqualTo(mapOf(KotlinxPropertiesEncoder.VALUE_KEY to uIntMax)) + } + + @Test + fun `encode() - encodes a ULong above Long MAX_VALUE as a BigInteger`() { + val encoded = encodeToMap(WithULong.serializer(), WithULong(ULong.MAX_VALUE)) + + assertThat(encoded).isEqualTo(mapOf("uLong" to BigInteger("18446744073709551615"))) + } + + @Test + fun `encode() - encodes negative signed numbers as-is`() { + val entry = WithSignedNumbers(byte = -1, short = -1, int = -1, long = -1L) + + val encoded = encodeToMap(WithSignedNumbers.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("byte" to (-1).toByte(), "short" to (-1).toShort(), "int" to -1, "long" to -1L), + ) + } + + // Map keys + + @Test + fun `encode() - converts map keys to strings`() { + val encoded = encodeToMap(WithIntMapKeys.serializer(), WithIntMapKeys(mapOf(1 to 2L))) + + assertThat(encoded).isEqualTo(mapOf("counts" to mapOf("1" to 2L))) + } + + @Test + fun `encode() - converts enum and unsigned map keys to strings of their encoded values`() { + val entry = + WithEncodedMapKeys(bySort = mapOf(Sort.PRICE_ASC to 1), byRank = mapOf(UInt.MAX_VALUE to 2)) + + val encoded = encodeToMap(WithEncodedMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo( + mapOf("bySort" to mapOf("price_asc" to 1), "byRank" to mapOf("4294967295" to 2)), + ) + } + + @Test + fun `encode() - converts a null map key to the string null`() { + val encoded = + encodeToMap(WithNullableMapKeys.serializer(), WithNullableMapKeys(mapOf(null to 1))) + + assertThat(encoded).isEqualTo(mapOf("counts" to mapOf("null" to 1))) + } + + @Test + fun `encode() - converts value class and custom serializer map keys to strings`() { + val entry = + WithWrappedMapKeys( + byProduct = mapOf(ProductId("p-1") to 1), + byCustom = mapOf(CustomSerialized("c-1") to 2), + ) + + val encoded = encodeToMap(WithWrappedMapKeys.serializer(), entry) + + assertThat(encoded) + .isEqualTo(mapOf("byProduct" to mapOf("p-1" to 1), "byCustom" to mapOf("c-1" to 2))) + } + + @Test + fun `encode() - drops the arguments for a duplicate key when a null map key and the string null are both keys`() { + val entry = WithNullableMapKeys(mapOf(null to 1, "null" to 2)) + + val exception = + assertFailsWith { + encodeToMap(WithNullableMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - drops the arguments for a duplicate key when a custom serializer encodes two keys as one string`() { + val entry = + WithVersionedNameMapKeys(mapOf(VersionedName("home", 1) to 1, VersionedName("home", 2) to 2)) + + val exception = + assertFailsWith { + encodeToMap(WithVersionedNameMapKeys.serializer(), entry) + } + + assertThat(exception.reason).isEqualTo(ArgumentDropReason.DUPLICATE_KEY) + } + + @Test + fun `encode() - throws for a class map key`() { + val entry = WithPointMapKeys(mapOf(Point(1) to 2)) + + assertFailsWith { + encodeToMap(WithPointMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a value class map key that wraps a class`() { + val entry = WithPointRefMapKeys(mapOf(PointRef(Point(1)) to 2)) + + assertFailsWith { + encodeToMap(WithPointRefMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a list map key`() { + // Converting this key to a string would copy the one 16 KiB string 4,000 times (~64 MiB). + val longString = "a".repeat(16 * 1024) + val entry = WithListMapKeys(mapOf(List(4_000) { longString } to 1)) + + assertFailsWith { + encodeToMap(WithListMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a map map key`() { + val entry = WithMapMapKeys(mapOf(mapOf("a" to 1) to 2)) + + assertFailsWith { + encodeToMap(WithMapMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a polymorphic map key`() { + val entry = WithOriginMapKeys(mapOf(Origin.Search("shoes") to 1)) + + assertFailsWith { + encodeToMap(WithOriginMapKeys.serializer(), entry) + } + } + + @Test + fun `encode() - throws for a class map key in a map nested in a list`() { + val entry = WithNestedPointMapKeys(listOf(mapOf(Point(1) to 2))) + + assertFailsWith { + encodeToMap(WithNestedPointMapKeys.serializer(), entry) + } + } + + // Unsupported properties + + @Test + fun `encode() - throws for a contextual property without a registered serializer`() { + val entry = WithContextual("1", Unregistered("2")) + + assertFailsWith { + encodeToMap(WithContextual.serializer(), entry) + } + } + + @Test + fun `encode() - throws for an open polymorphic property without a registered serializer`() { + val entry = WithOpenPolymorphic("1", object : OpenOrigin {}) + + assertFailsWith { + encodeToMap(WithOpenPolymorphic.serializer(), entry) + } + } + + // Serializer failures + + @Test + fun `encode() - propagates a serializer's exception unchanged`() { + val error = IllegalStateException("boom") + val serializer = RecordingSerializer(Detail.serializer()).apply { this.error = error } + + val thrown = assertFailsWith { encodeToMap(serializer, Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt new file mode 100644 index 0000000000..2c5518f5d7 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/SensitiveKeyFilterTest.kt @@ -0,0 +1,326 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import io.sentry.compose.navigation3.internal.backstack.budgetWithValuesRemaining +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxPropertiesEncoder.SensitiveKeyFilter +import io.sentry.util.UrlUtils.SENSITIVE_DATA_SUBSTITUTE +import kotlin.test.assertFailsWith +import org.junit.Test + +class SensitiveKeyFilterTest { + + private val sink = TreeArgumentWriter(ArgumentBudget()) + private val filter = SensitiveKeyFilter(sink) + + // Keys, values, maps, and lists under non-sensitive keys + + @Test + fun `passes keys, scalars, maps, and lists under non-sensitive keys to the sink`() { + filter.key("query") + filter.scalar("shoes") + filter.key("filters") + filter.beginMap() + filter.key("brands") + filter.beginList() + filter.scalar("a") + filter.end() + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo(mapOf("query" to "shoes", "filters" to mapOf("brands" to listOf("a")))) + } + + // Scalars + + @Test + fun `scalar() - writes the substitute in place of a scalar under a sensitive key`() { + filter.key("password") + filter.scalar("hunter2") + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("password" to SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `scalar() - writes a scalar under a non-sensitive key that follows a sensitive key`() { + filter.key("password") + filter.scalar("hunter2") + filter.key("page") + filter.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("password" to SENSITIVE_DATA_SUBSTITUTE, "page" to 2)) + } + + @Test + fun `scalar() - writes list elements under a non-sensitive key, even if they look like sensitive keys`() { + filter.key("tags") + filter.beginList() + filter.scalar("password") + filter.scalar("token") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("tags" to listOf("password", "token"))) + } + + @Test + fun `scalar() - writes the substitute under the sensitive keys of maps in a list`() { + filter.key("rows") + filter.beginList() + filter.beginMap() + filter.key("jwt") + filter.scalar("t-1") + filter.key("note") + filter.scalar("visible") + filter.end() + filter.scalar("plain") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf( + "rows" to listOf(mapOf("jwt" to SENSITIVE_DATA_SUBSTITUTE, "note" to "visible"), "plain"), + ), + ) + } + + // Computed scalars + + @Test + fun `computedScalar() - writes the computed value under a non-sensitive key`() { + filter.key("query") + filter.computedScalar { "shoes" } + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("query" to "shoes")) + } + + @Test + fun `computedScalar() - writes the substitute under a sensitive key without computing the value`() { + var computed = false + + filter.key("password") + filter.computedScalar { + computed = true + "hunter2" + } + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("password" to SENSITIVE_DATA_SUBSTITUTE)) + assertThat(computed).isFalse() + } + + @Test + fun `computedScalar() - writes nothing and doesn't compute the value in a map under a sensitive key`() { + var computed = false + + filter.key("credentials") + filter.beginMap() + filter.key("user") + filter.computedScalar { + computed = true + "alice" + } + filter.end() + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("credentials" to SENSITIVE_DATA_SUBSTITUTE)) + assertThat(computed).isFalse() + } + + @Test + fun `computedScalar() - resets sensitivity for the next value after writing a filtered value`() { + filter.key("rows") + filter.beginList() + filter.beginMap() + filter.key("jwt") + filter.computedScalar { "t-1" } + filter.end() + filter.computedScalar { "plain" } + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo(mapOf("rows" to listOf(mapOf("jwt" to SENSITIVE_DATA_SUBSTITUTE), "plain"))) + } + + @Test + fun `computedScalar() - throws the sink's broken limit without computing the value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + val limitedFilter = SensitiveKeyFilter(limitedSink) + var computed = false + limitedFilter.key("query") + + val thrown = + assertFailsWith { + limitedFilter.computedScalar { + computed = true + "shoes" + } + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(computed).isFalse() + } + + // Maps + + @Test + fun `beginMap() - writes the substitute in place of a map under a sensitive key`() { + filter.key("credentials") + filter.beginMap() + filter.key("user") + filter.scalar("alice") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("credentials" to SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `beginMap() - discards the nested maps, lists, and keys of a map under a sensitive key`() { + filter.key("credentials") + filter.beginMap() + filter.key("history") + filter.beginList() + filter.beginMap() + filter.key("user") + filter.scalar("alice") + filter.end() + filter.end() + filter.key("note") + filter.scalar("visible?") + filter.end() + filter.key("page") + filter.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("credentials" to SENSITIVE_DATA_SUBSTITUTE, "page" to 2)) + } + + @Test + fun `beginMap() - passes the map's identity to the sink`() { + val map = Any() + filter.key("filters") + filter.beginMap(map) + filter.key("nested") + + val drop = assertFailsWith { filter.beginMap(map) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + // Lists + + @Test + fun `beginList() - writes the substitute in place of a list under a sensitive key`() { + filter.key("refreshTokens") + filter.beginList() + filter.scalar("t-1") + filter.scalar("t-2") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("refreshTokens" to SENSITIVE_DATA_SUBSTITUTE)) + } + + @Test + fun `beginList() - passes the list's identity to the sink`() { + val list = Any() + filter.key("rows") + filter.beginList(list) + + val drop = assertFailsWith { filter.beginList(list) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + } + + // Ends of maps and lists + + @Test + fun `end() - resumes writing the containing map after a discarded map ends`() { + filter.key("filters") + filter.beginMap() + filter.key("token") + filter.beginMap() + filter.key("value") + filter.scalar("t-1") + filter.end() + filter.key("color") + filter.scalar("red") + filter.end() + filter.key("page") + filter.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf( + "filters" to mapOf("token" to SENSITIVE_DATA_SUBSTITUTE, "color" to "red"), + "page" to 2, + ), + ) + } + + @Test + fun `end() - writes a map under a non-sensitive key that follows a discarded map`() { + filter.key("password") + filter.beginMap() + filter.end() + filter.key("filters") + filter.beginMap() + filter.key("color") + filter.scalar("red") + filter.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf("password" to SENSITIVE_DATA_SUBSTITUTE, "filters" to mapOf("color" to "red")), + ) + } + + // Rejected limits + + @Test + fun `reject() - rejects the limit on the sink`() { + val drop = + assertFailsWith { + filter.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `reject() - rejects the limit on the sink within a map under a sensitive key`() { + // The filter discards writes under a sensitive key, but not limits a source rejects. + filter.key("credentials") + filter.beginMap() + + val drop = + assertFailsWith { + filter.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + + assertThat(sink.failure).isSameInstanceAs(drop) + } +} diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 5caa7674c9..ddd232ecd0 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -8023,6 +8023,7 @@ public abstract interface class io/sentry/util/HintUtils$SentryNullableConsumer public final class io/sentry/util/HttpUtils { public fun ()V + public static fun containsSensitiveDataKey (Ljava/lang/String;)Z public static fun containsSensitiveHeader (Ljava/lang/String;)Z public static fun filterHeaders (Ljava/util/Map;Lio/sentry/KeyValueCollectionBehavior;)Ljava/util/Map; public static fun filterQueryParams (Ljava/lang/String;Lio/sentry/KeyValueCollectionBehavior;)Ljava/lang/String; diff --git a/sentry/src/main/java/io/sentry/util/HttpUtils.java b/sentry/src/main/java/io/sentry/util/HttpUtils.java index 73da780805..088bfe93e6 100644 --- a/sentry/src/main/java/io/sentry/util/HttpUtils.java +++ b/sentry/src/main/java/io/sentry/util/HttpUtils.java @@ -135,7 +135,11 @@ public static boolean containsSensitiveHeader(final @NotNull String header) { } } - static boolean containsSensitiveDataKey(final @NotNull String key) { + /** + * Returns whether {@code key} contains a term from the Data Collection spec's sensitive denylist, + * matched partially and case-insensitively. + */ + public static boolean containsSensitiveDataKey(final @NotNull String key) { return containsTerm(key, SENSITIVE_DATA_KEYS); } diff --git a/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt b/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt index c0791642b5..61ca5bfde0 100644 --- a/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt @@ -113,4 +113,17 @@ class HttpUtilsTest { "[Filtered]", ) } + + @Test + fun `sensitive data key check matches keys containing denylist terms in any case`() { + assertThat(HttpUtils.containsSensitiveDataKey("authToken")).isTrue() + assertThat(HttpUtils.containsSensitiveDataKey("X-API-KEY")).isTrue() + assertThat(HttpUtils.containsSensitiveDataKey("SessionId")).isTrue() + } + + @Test + fun `sensitive data key check doesn't match keys without denylist terms`() { + assertThat(HttpUtils.containsSensitiveDataKey("productId")).isFalse() + assertThat(HttpUtils.containsSensitiveDataKey("query")).isFalse() + } }