Skip to content
Merged
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
7 changes: 7 additions & 0 deletions example/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ android {
jvmTarget = "17"
}
namespace 'io.radar.example'

sourceSets {
main {
// FraudKeyOverrideBridge calls the fraud SDK's internal key override only when sdk-fraud is included.
java.srcDirs += findProject(':sdk-fraud') != null ? 'src/withFraud/java' : 'src/withoutFraud/java'
}
}
}

dependencies {
Expand Down
15 changes: 15 additions & 0 deletions example/src/main/java/io/radar/example/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ class MainActivity : AppCompatActivity() {
activity = this,
)
settingsStore.environment.applyTo(this, settingsStore.host, settingsStore.verifiedHost)
applyFraudKeyOverride(settingsStore, logStore)
Log.i("radar-env", settingsStore.environmentSummary())
logStore.writeResult("radar-env: ${settingsStore.environmentSummary()}")
val authToken = settingsStore.resolvedAuthToken
Expand Down Expand Up @@ -202,6 +203,20 @@ class MainActivity : AppCompatActivity() {
private fun isGranted(permission: String): Boolean =
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED

/**
* Sets the saved fraud key override for this environment, if any, before the first verified
* request. Without one, the internal API isn't called and the SDK uses its built-in key. The
* environment is fixed for the life of the process, so the override never needs clearing.
*/
private fun applyFraudKeyOverride(settingsStore: SettingsStore, logStore: LogStore) {
val setting = settingsStore.resolvedFraudKeyOverride ?: return
try {
FraudKeyOverrideBridge.set(setting)
} catch (e: Exception) {
logStore.writeError("Fraud key override not applied", e.message)
}
}

@RequiresApi(Build.VERSION_CODES.O)
private fun createCustomNotification(): Notification {
val channelId = "radar_custom_channel"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ enum class RadarEnvironment(

fun verifiedHost(localUrl: String): String = fixedVerifiedHost ?: localUrl

/** Whether a fraud key override can be saved for this environment. Production always uses the SDK's key. */
val allowsFraudKeyOverride: Boolean get() = this != PRODUCTION

/** Writes the SDK's host overrides. */
fun applyTo(context: Context, host: String, verifiedHost: String) {
context.getSharedPreferences(SDK_PREFS, Context.MODE_PRIVATE).edit {
Expand Down
29 changes: 27 additions & 2 deletions example/src/main/java/io/radar/example/store/SettingsStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ import io.radar.example.MainActivity
import io.radar.sdk.Radar
import org.json.JSONObject

/** A saved fraud public key (base64) and key version that replace the SDK's built-in key. */
data class FraudKeyOverrideSetting(val publicKeyBase64: String, val keyVersion: Int)

/**
* SDK-backed identity + tracking snapshot, plus the persisted environment: which
* [RadarEnvironment] to use, a publishable key and host overrides per environment, and the Local server URL.
* [RadarEnvironment] to use, a publishable key, host overrides, and a fraud key override per environment, and the
* Local server URL.
*
* The environment applied at launch is fixed for the life of the process. Changing it goes
* through [saveEnvironment] followed by a restart (see `MainActivity.restart`).
Expand Down Expand Up @@ -39,6 +43,9 @@ class SettingsStore(context: Context) {
val host: String = apiHost(environment)
val verifiedHost: String = verifiedHostOverride(environment).ifBlank { environment.verifiedHost(localUrl) }

/** The fraud key override for [environment], or null to use the SDK's built-in production key. */
val resolvedFraudKeyOverride: FraudKeyOverrideSetting? = fraudKeyOverride(environment)

/** Which environments [resolvedPublishableKey] is valid on. */
var keyCheck by mutableStateOf<KeyCheck>(KeyCheck.NotChecked)
private set
Expand All @@ -60,6 +67,17 @@ class SettingsStore(context: Context) {

fun apiHost(env: RadarEnvironment): String = hostOverride(env).ifBlank { env.host(localUrl) }

/** The saved fraud public key (base64) for [env], or "" if none is set. Production is never overridden. */
fun fraudPublicKey(env: RadarEnvironment): String =
if (env.allowsFraudKeyOverride) prefs.getString("fraudPublicKey.${env.name}", null) ?: "" else ""

/** The saved fraud key version for [env], defaulting to 1. */
fun fraudKeyVersion(env: RadarEnvironment): Int = prefs.getInt("fraudKeyVersion.${env.name}", 1)

/** The fraud key override for [env], or null if none is saved. */
fun fraudKeyOverride(env: RadarEnvironment): FraudKeyOverrideSetting? =
fraudPublicKey(env).ifBlank { null }?.let { FraudKeyOverrideSetting(it, fraudKeyVersion(env)) }

/** Persists the environment settings. Takes effect on the next launch. */
fun saveEnvironment(
env: RadarEnvironment,
Expand All @@ -68,9 +86,15 @@ class SettingsStore(context: Context) {
verifiedHostOverride: String,
useAuthToken: Boolean,
authToken: String,
fraudPublicKey: String,
fraudKeyVersion: Int,
) {
prefs.edit(commit = true) {
putString(KEY_ENVIRONMENT, env.name)
if (env.allowsFraudKeyOverride) {
putString("fraudPublicKey.${env.name}", fraudPublicKey.filterNot { it.isWhitespace() })
putInt("fraudKeyVersion.${env.name}", fraudKeyVersion)
}
putString(keyPrefsKey(env), publishableKey.trim())
putBoolean("useAuthToken.${env.name}", useAuthToken)
putString("authToken.${env.name}", authToken.trim())
Expand Down Expand Up @@ -106,7 +130,8 @@ class SettingsStore(context: Context) {

/** Where requests go, e.g. `env = Staging; host = https://…; key = prj_test_pk_ab12…; key check = …`. */
fun environmentSummary(): String =
"env = ${environment.label}; host = $host; verified host = $verifiedHost; ${credentialSummary()}; key check = ${keyCheck.summary()}"
"env = ${environment.label}; host = $host; verified host = $verifiedHost; ${credentialSummary()}; " +
"fraud key = ${resolvedFraudKeyOverride?.let { "override v${it.keyVersion}" } ?: "built-in"}; key check = ${keyCheck.summary()}"

/** `key = prj_…` or `auth token = kid …, expires …`. */
private fun credentialSummary(): String = when {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import io.radar.example.store.LocalSettingsStore
import io.radar.example.store.RadarEnvironment

/**
* Picks the Radar environment, publishable key, and host overrides. Changes apply on relaunch.
* Picks the Radar environment, publishable key, host overrides, and fraud key override. Changes apply on relaunch.
*/
@Composable
fun EnvironmentSection() {
Expand All @@ -42,6 +42,9 @@ fun EnvironmentSection() {
var verifiedHost by remember(selected) { mutableStateOf(settings.verifiedHostOverride(selected)) }
var useAuthToken by remember(selected) { mutableStateOf(settings.useAuthToken(selected)) }
var authToken by remember(selected) { mutableStateOf(settings.authToken(selected)) }
var fraudPublicKey by remember(selected) { mutableStateOf(settings.fraudPublicKey(selected)) }
var fraudKeyVersion by remember(selected) { mutableStateOf(settings.fraudKeyVersion(selected).toString()) }
val parsedFraudKeyVersion = fraudKeyVersion.trim().toIntOrNull()?.takeIf { it > 0 }

Column(modifier = Modifier.fillMaxWidth()) {
Text("Environment", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
Expand Down Expand Up @@ -110,13 +113,39 @@ fun EnvironmentSection() {
color = MaterialTheme.colorScheme.onSurfaceVariant,
)

if (selected.allowsFraudKeyOverride) {
FieldEditor(
"${selected.label} fraud public key override",
fraudPublicKey,
{ fraudPublicKey = it },
placeholder = "Base64 P-256 public key (optional)",
)
FieldEditor("${selected.label} fraud key version", fraudKeyVersion, { fraudKeyVersion = it }, placeholder = "1")
Text(
"Encrypts fraud payloads to this key instead of the SDK's built-in production key. " +
"Leave empty to use the built-in key. Saved on this device.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}

Button(
onClick = {
settings.saveEnvironment(selected, key, host, verifiedHost, useAuthToken, authToken)
settings.saveEnvironment(
selected,
key,
host,
verifiedHost,
useAuthToken,
authToken,
fraudPublicKey,
parsedFraudKeyVersion ?: 1,
)
MainActivity.restart(context)
},
enabled = (selected != RadarEnvironment.LOCAL || settings.localUrl.isNotBlank() || (host.isNotBlank() && verifiedHost.isNotBlank())) &&
(!useAuthToken || authToken.isNotBlank()),
(!useAuthToken || authToken.isNotBlank()) &&
(fraudPublicKey.isBlank() || parsedFraudKeyVersion != null),
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
) { Text("Apply & restart") }
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package io.radar.example

import io.radar.example.store.FraudKeyOverrideSetting
import io.radar.sdk.fraud.internal.FraudKeyOverride
import io.radar.sdk.fraud.internal.RadarInternalApi

/**
* Sets the fraud SDK's internal key override. Compiled only when the sdk-fraud module is included
* (see build.gradle); `src/withoutFraud` has the stand-in.
*/
object FraudKeyOverrideBridge {
/** Sets [setting] as the fraud key override. Throws IllegalArgumentException if the key or version is invalid. */
@OptIn(RadarInternalApi::class)
fun set(setting: FraudKeyOverrideSetting) {
FraudKeyOverride.set(setting.publicKeyBase64, setting.keyVersion)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package io.radar.example

import io.radar.example.store.FraudKeyOverrideSetting

/**
* Stand-in used when the sdk-fraud module isn't included (see build.gradle). Without the fraud
* module there are no fraud payloads to encrypt.
*/
object FraudKeyOverrideBridge {
fun set(setting: FraudKeyOverrideSetting) {
throw IllegalStateException("The sdk-fraud module isn't included in this build")
}
}
2 changes: 1 addition & 1 deletion sdk-fraud
Loading