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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
### Features

- Nav3: Add `BackStackEntryMapper.SerialName`, a convenience mapper that names back stack entries after their kotlinx.serialization serial names ([#6703](https://github.com/getsentry/sentry-java/pull/6703))
- Nav3: Add `BackStackEntryMapper.SerialNameAndProperties`, which is like `SerialName` except that it also records the properties of each back stack entry as arguments ([#6706](https://github.com/getsentry/sentry-java/pull/6706))

### Dependencies

Expand Down
3 changes: 2 additions & 1 deletion sentry-android-navigation3/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ Use `SentryNavEffect` alongside your `NavDisplay` to record navigation transacti
users move around your app. Configure the data you want captured via `SentryNavOptions`.

Because Nav3 back stacks can have arbitrary key types, host apps need to provide `SentryNavEffect` with a mapping between their back stack
keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` mapper).
keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` and
`SerialNameAndProperties` mappers).

See the [Navigation for Android docs](https://docs.sentry.io/platforms/android/integrations/navigation/) for additional details, including
configuration, supported setups, and limitations.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ public abstract interface class io/sentry/compose/navigation3/BackStackEntryMapp

public final class io/sentry/compose/navigation3/BackStackEntryMapper$Companion {
public final fun getSerialName ()Lio/sentry/compose/navigation3/BackStackEntryMapper;
public final fun getSerialNameAndProperties ()Lio/sentry/compose/navigation3/BackStackEntryMapper;
}

public final class io/sentry/compose/navigation3/BuildConfig {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,17 @@ public class SentryBackStackEntry(
/**
* Maps a back stack entry to a displayable name and optional diagnostic arguments.
*
* If you use kotlinx.serialization, see [SerialName] for convenient, out-of-the-box mappers.
* Otherwise, provide your own implementation. (Note: Custom implementations can always fall back to
* `SerialName` for any entries that don't have to be special-cased.)
* If you use kotlinx.serialization, see [SerialName] and [SerialNameAndProperties] for convenient,
* out-of-the-box mappers. Otherwise, provide your own implementation. (Note: Custom implementations
* can always fall back to `SerialName` or `SerialNameAndProperties` for any entries that don't have
* to be special-cased.)
*
* **Privacy / PII**
*
* Custom mappers are responsible for filtering their own arguments.
* Built-in mappers that capture entry properties apply limited sensitive-data filtering before
* recording arguments; see [SerialNameAndProperties] for the filtering rules. Custom mappers are
* responsible for filtering their own arguments; Sentry does not apply its built-in sensitive-data
* filtering to arguments they supply themselves.
*
* Only return names and arguments that are known to be safe or have been pre-scrubbed. All
* arguments remain subject to size and structural limits.
Expand Down Expand Up @@ -144,6 +148,8 @@ public fun interface BackStackEntryMapper<in T : Any> {
* would return `"ProductDetail"` as the destination's name, but would ***not*** return the
* destination's properties (`userId` and `productId`).
*
* To return both entry names and properties, see [SerialNameAndProperties].
*
* **Name == SerialDescriptor.serialName**
*
* This mapper names each back stack entry after the entry's
Expand Down Expand Up @@ -177,8 +183,8 @@ public fun interface BackStackEntryMapper<in T : Any> {
*
* Entries share a Sentry name whenever their serializers share a serial name. In particular:
*
* - All constants of an enum are named after the enum. A `@SerialName` on a constant does not
* change the destination name.
* - All constants of an enum are named after the enum. A `@SerialName` on a constant only
* changes how [SerialNameAndProperties] records the constant as an argument.
*
* - Classes that use the same custom serializer (`@Serializable(with = ...)`) are named after
* that serializer's descriptor, which ignores a `@SerialName` on the class.
Expand All @@ -189,5 +195,72 @@ public fun interface BackStackEntryMapper<in T : Any> {
@get:ApiStatus.Experimental
public val SerialName: BackStackEntryMapper<Any>
get() = BuiltInBackStackEntryMappers.serialName

/**
* Like [SerialName], but also returns the properties of each back stack entry as Sentry
* arguments.
*
* For instance, given:
* ```
* @Serializable
* @SerialName("ProductDetail")
* data class ProductDetail(
* val userId: String,
* val productId: String
* ) : NavKey
* ```
*
* when navigating to `ProductDetail(userId = "123abc", productId = "zyx987")`, this mapper
* would return `"ProductDetail"` as the destination's name, along with the following arguments:
* ```json
* {
* "userId": "123abc",
* "productId": "zyx987"
* }
* ```
*
* Returns `null` for any entries that can't be named (see [SerialName]). Sentry displays these
* entries as `"/unknown"` with no arguments.
*
* The argument limits described in [BackStackEntryMapper] apply.
*
* **Privacy / PII**
*
* This mapper returns arguments for every property of each back stack entry passed to it, which
* may include private data or PII. Almost all properties are sent as-is (see below for limited
* exceptions in the case of sensitive secrets). Neither `sendDefaultPii` nor the
* `dataCollection` options change what this mapper returns.
*
* Modify your use of this mapper if any entry in your back stack contains info you don't want
* sent to Sentry. For instance, i) use this mapper for all entries but filter out any
* properties you want to omit, or ii) use a custom [BackStackEntryMapper] that special-cases
* entries with sensitive info or PII and falls back to this mapper (or [SerialName]) for
* entries without it. See
* [Choosing Which Arguments to Send](https://docs.sentry.io/platforms/android/integrations/navigation/#choosing-which-arguments-to-send)
* for examples.
*
* **Limited filtering for sensitive secrets**
*
* Values are replaced with `"[Filtered]"` when their property's targeted name (i.e., their
* `@SerialName` if they have one, or else the property's name) contains a term from
* [Sentry's sensitive denylist](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist)
* (ignoring case). This filters secrets like `authToken`, but leaves PII like `userEmail`
* unchanged.
*
* Matching follows the same rule Sentry SDKs use for HTTP headers, cookies, and query
* parameters, meaning it may filter harmless properties like `insideCart` (`sid`) or `keyword`
* (`key`).
*
* **Encoding and encoding failures**
*
* Properties are encoded on the first argument read, including by `equals` or `hashCode`.
*
* Failures preserve the entry's name and replace its arguments with a drop reason, e.g.,
* `{"dropped_by_sentry": "encoding_failed"}`. Encoding errors are logged once per entry type
* when `debug` is enabled.
*/
@get:ApiStatus.Experimental
public val SerialNameAndProperties: BackStackEntryMapper<Any>
get() = BuiltInBackStackEntryMappers.serialNameAndProperties
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,52 @@ import java.util.IdentityHashMap
* implementations are expected to materialize the provided info into a tree of Sentry arguments,
* where the tree has a bounded size and height.
*
* **The argument conversion subsystem**
*
* With Nav3, host apps manage their own nav back stack, which they implement as a list of
* arbitrarily typed entries. In order to be displayed in Sentry, each of those entries has to be
* mapped to a Sentry name (e.g., ProductDetailScreen) and zero or more arguments (e.g., productId).
* There are two ways for host apps to provide us with those mappings:
*
* 1. via a custom `BackStackEntryMapper`; or
*
* 2. via one of our own built-in mappers (viz., `BackStackEntryMapper.SerialName` or
* `BackStackEntryMapper.SerialNameAndProperties`).
*
* `ArgumentSink` and `ArgumentSource` create the seam that lets us support variable processing on
* the source side (the host app's logic vs built-in logic) but uniform processing on the sink side
* (argument pruning, protecting against constraint violation, and tree materialization).
*
* Here are the moving parts:
* ```text
* ArgumentSource
* Custom mapper Built-in mappers
* ┌────────────────────┐ ┌───────────────────────┐
* │ HostArgumentSource │ │ KotlinxArgumentSource │
* │ (plain host map) │ │ (drives encoder) │
* └────────┬───────────┘ └────────┬──────────────┘
* │ │ via
* │ KotlinxPropertiesEncoder + SensitiveKeyFilter
* │ │
* └──────────────┬──────────────┘
* ▼
* ┌───────────────────────────────┐
* │ ArgumentSink │
* └───────────────────────────────┘
* ▲ sole impl
* ┌───────────────┴───────────────┐
* │ TreeArgumentWriter │
* │ │ ┌────────────────┐
* │ Enforce + materialize: │ spends ──▶│ ArgumentBudget │
* │ • builds the argument tree │ └────────────────┘
* │ • prevents constraint │ ┌────────────────┐
* │ violation (e.g., cycles) │ throws ──▶│ DropArguments │
* └───────────────────────────────┘ └────────────────┘
*
* Note: BackStackConverter.ArgumentSanitizer owns the ArgumentBudget and
* selects the ArgumentSource based on what the host app provides.
* ```
*
* Receives one back stack entry's arguments as a [source][ArgumentSource] produces them, enforcing
* the argument limits as it goes.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,23 @@ internal object BuiltInBackStackEntryMappers {
// threads may each create and probe a mapper and log warnings, and all but the first
// published instance would be discarded.
create(logger) {
KotlinxBackStackEntryMapper(logger = logger)
KotlinxBackStackEntryMapper(includeProperties = false, logger = logger)
}
}

/**
* Like [serialName], but also returns the properties of each back stack entry as Sentry
* arguments.
*
* Falls back to [UnavailableBackStackEntryMapper] if a mapper can't be created.
*
* See [BackStackEntryMapper.SerialNameAndProperties] for more details.
*/
val serialNameAndProperties: BackStackEntryMapper<Any> by
lazy(LazyThreadSafetyMode.PUBLICATION) {
// PUBLICATION, as for serialName.
create(logger) {
KotlinxBackStackEntryMapper(includeProperties = true, logger = logger)
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
# `io.sentry.compose.navigation3.internal.backstack`

Converts host back stacks into bounded Sentry names and arguments.
Package contains code for generating Sentry data from a host app's back stack.

## Conventions

### Properties vs. arguments

Code in this package uses the term "properties" for the fields and values it reads from a back stack entry and "arguments" for the values
a `BackStackEntryMapper` supplies for Sentry to record, i.e., `SentryBackStackEntry.arguments`. Arguments include the mapper's output before
sanitization, which may modify or drop them before Sentry records them. Hence
`SerialNameAndProperties` and `KotlinxPropertiesEncoder`, but `SentryBackStackEntry(arguments = ...)`.

When a host app uses a built-in `BackStackEntryMapper`, we're responsible for mapping entry properties to corresponding arguments. When the
host app implements its own `BackStackEntryMapper`, it performs the mapping on its end and hands the resulting arguments to us.
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package io.sentry.compose.navigation3.internal.backstack.kotlinx

import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget
import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason
import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY
import io.sentry.compose.navigation3.internal.backstack.ArgumentSink
import io.sentry.compose.navigation3.internal.backstack.ArgumentSource
import io.sentry.compose.navigation3.internal.backstack.DropArguments
import io.sentry.compose.navigation3.internal.backstack.HostArgumentSource
import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter
import io.sentry.util.ExceptionUtils
import kotlinx.serialization.KSerializer

/**
* The [ArgumentSource] for our built-in `BackStackEntryMapper`s.
*
* It keeps a reference to the [backStackEntry] whose properties it reads, as well as the
* [serializer] needed to encode them, for as long as the map itself is reachable. (The SDK doesn't
* retain these maps past a back stack update, but a host app that keeps a mapper's result also
* keeps its entry.)
*
* Encoding is performed on demand and cached in order to:
*
* - guarantee a single, consistent snapshot for all consumers; and
* - avoid doing work for arguments that will be dropped or never read.
*
* If the arguments are dropped, reading them as a map returns only the drop reason.
*
* In general, all failures are reported to [onFailure]. The sole exception is an argument
* constraint violated while writing to the `ArgumentSanitizer`'s sink. The sanitizer reports that
* instead, as those limits can depend on what fraction of the [ArgumentBudget] the update's other
* entries spent.
*/
internal class KotlinxArgumentSource(
private val backStackEntry: Any,
private val serializer: KSerializer<Any>,
private val onFailure: (Throwable) -> Unit,
) : AbstractMap<String, Any?>(), ArgumentSource {

private val copy: Lazy<EncodedCopy> =
// PUBLICATION so that no lock is held while encoding runs the host app's serializers, which
// could otherwise deadlock on a lock held by the app. Readers that race on the first read may
// each encode, but all of them see the copy published first.
lazy(LazyThreadSafetyMode.PUBLICATION) { encodeCopy() }

override val entries: Set<Map.Entry<String, Any?>>
get() = copy.value.arguments.entries

/**
* Writes the entry's arguments to [sink], encoding its properties if needed. Uses the previously
* cached copy instead if it was encoded successfully.
*
* Throws [DropArguments] if the arguments can't be written, either with the reason for the
* constraint they violated, or with [ArgumentDropReason.ENCODING_FAILED] if encoding failed.
*/
override fun writeTo(sink: ArgumentSink) {
val cached = if (copy.isInitialized()) copy.value else null
if (cached != null && !cached.isDropped) {
cached.writeTo(sink)
} else {
// A failed copy used a separate budget. Encode again so values written before the failure
// consume the update's shared budget; rethrowing the cached failure would leave extra room
// for older entries' arguments.
encode(sink)
}
}

@Suppress("ThrowsCount")
private fun encode(sink: ArgumentSink) {
try {
KotlinxPropertiesEncoder.encode(serializer, backStackEntry, sink)
} catch (e: DropArguments) {
// Prefer the sink's first failure because it determines whether older entries keep their
// arguments.
throw sink.failure ?: e
} catch (e: LinkageError) {
// Preserve the entry's name and drop its properties. The creation-time probe checks encoder
// compatibility but can't exercise every path. This LinkageError may be specific to the
// entry's serializers, so we keep the failure local to this type.
sink.failure?.let { throw it }
onFailure(e)
throw DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null)
} catch (@Suppress("TooGenericExceptionCaught") t: Throwable) {
// App serializers and map-key toString() calls may throw anything. Catch broadly to log once
// per type.
ExceptionUtils.rethrowIfFatal(t)

// A serializer may replace a constraint violation with its own exception. Prefer the sink's
// recorded failure because it determines whether older entries keep their arguments.
sink.failure?.let { throw it }
onFailure(t)
throw DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null)
}
}

private fun encodeCopy(): EncodedCopy {
val sink = TreeArgumentWriter(ArgumentBudget())

return try {
encode(sink)
EncodedCopy(sink.argumentsOrThrow(), isDropped = false)
} catch (e: DropArguments) {
// encode already reported an encoding failure.
if (e.reason != ArgumentDropReason.ENCODING_FAILED) {
onFailure(e)
}
EncodedCopy(mapOf(ARGUMENT_DROP_REASON_KEY to e.reason.serializedValue), isDropped = true)
}
}

/** Cached arguments encoded from a single back stack entry's properties. */
private class EncodedCopy(
/**
* The encoded arguments, or, if they were dropped, only the drop reason under
* [ARGUMENT_DROP_REASON_KEY].
*
* A host app mapper that copies or filters a dropped entry's arguments passes the reason on as
* an ordinary argument. Sentry then records it as it would for this mapper's own output, rather
* than recording no arguments and no reason.
*/
val arguments: Map<String, Any?>,
/**
* Whether the back stack entry's arguments were dropped, because of an encoding failure or a
* violated argument constraint.
*/
val isDropped: Boolean,
) : ArgumentSource {

/** Writes the encoded arguments to [sink]. Only for a copy that wasn't [dropped][isDropped]. */
override fun writeTo(sink: ArgumentSink) {
check(!isDropped) { "A dropped copy is encoded again instead of written." }
// The copy holds only plain maps, lists, and values the sink supports.
HostArgumentSource(arguments, onUnsupportedValue = {}).writeTo(sink)
}
}
}

/**
* The arguments of a back stack entry whose properties can't be encoded because the app's
* kotlinx.serialization version doesn't support the properties encoder.
*
* Handles encoding failures like [KotlinxArgumentSource]: map reads return `{"dropped_by_sentry":
* "encoding_failed"}`, and writes drop the entry's arguments with
* [ArgumentDropReason.ENCODING_FAILED].
*/
internal object KotlinxUnencodableArguments : AbstractMap<String, Any?>(), ArgumentSource {

private val dropReason =
mapOf(ARGUMENT_DROP_REASON_KEY to ArgumentDropReason.ENCODING_FAILED.serializedValue)

override val entries: Set<Map.Entry<String, Any?>>
get() = dropReason.entries

override fun writeTo(sink: ArgumentSink) {
throw DropArguments(ArgumentDropReason.ENCODING_FAILED, warning = null)
}
}
Loading
Loading