Skip to content

Native Android client for Spotify, built with Jetpack Compose

The diagnostic hides tokens, cookies, the Authorization header, passwords, sign-in codes and e-mail addresses in bridge calls and in every line it keeps, and cuts long results and lines, while names, durations, status codes, track ids and context uris stay [skip ci]

kota-zo423330961fc1
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt
index d39bf50a..94207dd2 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt
@@ -176,7 +176,7 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {
pending[id] = waiter
try {
val started = System.currentTimeMillis()
- if (!quiet) logger?.invoke("call #$id $method${label?.let { " ($it)" }.orEmpty()} ${args.toString().take(200)}")
+ if (!quiet) logger?.invoke("call #$id $method${label?.let { " ($it)" }.orEmpty()} ${LogMask.shown(args.toString())}")
host.evaluate("window.Myspoti && window.Myspoti.call($id, ${json.encodeToString(JsonElement.serializer(), kotlinx.serialization.json.JsonPrimitive(method))}, $args).catch(() => {})")
return try {
// withTimeoutOrNull, not withTimeout: a timeout must surface as a
@@ -187,12 +187,12 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {
?: throw BridgeException("timeout after $timeoutMs ms: $method")
result.also {
if (quiet) return@also
- val shown = if (method == "token.get") "(token hidden)" else it.toString().take(200)
+ val shown = if (method == "token.get") "(token hidden)" else LogMask.shown(it.toString())
logger?.invoke("call #$id $method ok in ${System.currentTimeMillis() - started} ms: $shown")
}
} catch (e: Exception) {
if (e is BridgeException && e.message?.startsWith("timeout") == true) lastTimeoutAt = System.currentTimeMillis()
- logger?.invoke("call #$id $method${if (quiet) " " + args.toString().take(100) else ""} FAILED after ${System.currentTimeMillis() - started} ms: ${e.message}")
+ logger?.invoke("call #$id $method${if (quiet) " " + LogMask.shown(args.toString(), 100) else ""} FAILED after ${System.currentTimeMillis() - started} ms: ${LogMask.shown(e.message.orEmpty())}")
throw e
}
} finally {
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/LogMask.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/LogMask.kt
new file mode 100644
index 00000000..2cf7046c
--- /dev/null
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/LogMask.kt
@@ -0,0 +1,40 @@
+package app.myspoti.spotify.bridge
+
+/**
+ * What a log line may keep of a bridge call or a host message. The diagnostic is handed to other
+ * people, so the values that open an account (tokens, cookies, the Authorization header, passwords,
+ * sign-in codes) and the e-mail address are hidden before a line is written; everything a bug report
+ * reads (names, durations, status codes, track ids, context uris) is left as it is.
+ */
+object LogMask {
+ private const val HIDDEN = "(hidden)"
+
+ /** A key whose value is a secret, in JSON (`"access_token":"…"`) or as a header or form field. */
+ private const val SECRET_KEY = "[\\w-]*(?:token|cookie|authorization|password|passwd|secret|csrf|otp|verifier|auth_?code|sp_dc|sp_key)[\\w-]*|e-?mail"
+
+ private val jsonValue = Regex("(?i)(\"(?:$SECRET_KEY)\"\\s*:\\s*)(\"(?:[^\"\\\\]|\\\\.)*\"|[^,}\\]\\s]+)")
+ private val headerValue = Regex("(?i)\\b(authorization|cookie|set-cookie|proxy-authorization)(\\s*[:=]\\s*)[^\\r\\n]*")
+ private val queryValue = Regex("(?i)([?&;](?:$SECRET_KEY|code)=)[^&\\s\"']+")
+ private val bearer = Regex("(?i)\\b(bearer|basic)\\s+[A-Za-z0-9._~+/=-]+")
+ private val address = Regex("[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,}")
+
+ /** A run this long without a space is a token or a blob, never a title or an id (a track id has 22 characters). */
+ private val blob = Regex("[A-Za-z0-9_=.-]{120,}")
+
+ /** [text] with its secrets replaced by "(hidden)". */
+ fun redact(text: String): String {
+ var out = text
+ if (out.contains('"')) out = jsonValue.replace(out) { "${it.groupValues[1]}\"$HIDDEN\"" }
+ out = headerValue.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}$HIDDEN" }
+ out = queryValue.replace(out) { "${it.groupValues[1]}$HIDDEN" }
+ out = bearer.replace(out) { "${it.groupValues[1]} $HIDDEN" }
+ if (out.contains('@')) out = address.replace(out, "(e-mail hidden)")
+ return blob.replace(out, "(long value hidden)")
+ }
+
+ /** [text] redacted, then cut to [max] characters with the number cut. */
+ fun shown(text: String, max: Int = 200): String {
+ val clean = redact(text)
+ return if (clean.length <= max) clean else clean.take(max) + "… (+${clean.length - max})"
+ }
+}
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/LogMaskTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/LogMaskTest.kt
new file mode 100644
index 00000000..5a481347
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/LogMaskTest.kt
@@ -0,0 +1,37 @@
+package app.myspoti.spotify.bridge
+
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+
+class LogMaskTest {
+ @Test fun `tokens, cookies, passwords and e-mail in JSON are hidden, the rest stays`() {
+ val out = LogMask.redact("""{"accessToken":"BQabc","uri":"spotify:track:4uLU6hMCjMI75M1A2tKUQC","email":"[email protected]","password":"hunter2","ms":1200}""")
+ assertEquals("""{"accessToken":"(hidden)","uri":"spotify:track:4uLU6hMCjMI75M1A2tKUQC","email":"(hidden)","password":"(hidden)","ms":1200}""", out)
+ }
+
+ @Test fun `headers, bearer values and query secrets are hidden`() {
+ assertEquals("Authorization: (hidden)", LogMask.redact("Authorization: Bearer abc.def"))
+ assertEquals("Cookie: (hidden)", LogMask.redact("Cookie: sp_dc=xyz; sp_key=1"))
+ assertEquals("https://x/cb?code=(hidden)&state=ok", LogMask.redact("https://x/cb?code=1234&state=ok"))
+ assertEquals("sent Bearer (hidden) twice", LogMask.redact("sent Bearer abc123 twice"))
+ }
+
+ @Test fun `a stray address and a long blob are hidden`() {
+ assertEquals("user (e-mail hidden) failed", LogMask.redact("user [email protected] failed"))
+ assertEquals("token (long value hidden)", LogMask.redact("token " + "A".repeat(200)))
+ }
+
+ @Test fun `what a bug report reads is kept`() {
+ val line = "call #4 player.play (queue) {\"context\":\"spotify:playlist:37i9dQZF1DXcBWIGoYBM5M\",\"state=playing\":1} ok in 85 ms: status=402 code=COMMAND_FAILED"
+ assertEquals(line, LogMask.redact(line))
+ }
+
+ @Test fun `shown cuts a big result and says by how much`() {
+ val out = LogMask.shown("x".repeat(50), 20)
+ assertTrue(out.startsWith("x".repeat(20)))
+ assertTrue(out.endsWith("(+30)"))
+ assertFalse(LogMask.shown("short").contains("+"))
+ }
+}
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt
index ed648254..72086590 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt
@@ -1,6 +1,7 @@
package app.myspoti.host.android
import android.content.Context
+import app.myspoti.spotify.bridge.LogMask
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
@@ -23,6 +24,9 @@ object Logbook {
*/
private const val MAX_LINES = 6000
+ /** The longest line kept; the longest ones written on purpose (devices, identity) stay under it. */
+ private const val MAX_LINE = 2000
+
/** Guarded by its own monitor: [log] is called from the main thread, OkHttp threads and coroutines. */
private val lines = ArrayDeque<String>(MAX_LINES)
private val stamp = SimpleDateFormat("HH:mm:ss.SSS", Locale.US)
@@ -32,7 +36,9 @@ object Logbook {
* Records [line] and mirrors it to Logcat with the same message, so the exported report
* and `adb logcat -s Myspoti` show the same thing. Safe from any thread.
*/
- fun log(line: String) {
+ fun log(raw: String) {
+ // Secrets are hidden and a huge line cut here, once, for every caller (see LogMask).
+ val line = LogMask.shown(raw, MAX_LINE)
android.util.Log.d(WebPlayerHost.LOG, line)
synchronized(lines) {
lines.addLast("${stamp.format(Date())} $line")
@@ -72,7 +78,7 @@ object Logbook {
* where it is known, the latest value wins.
*/
private val facts = java.util.concurrent.ConcurrentHashMap<String, String>()
- fun fact(key: String, value: String) { facts[key] = value }
+ fun fact(key: String, value: String) { facts[key] = LogMask.redact(value) }
/** More header lines the app knows of (its extensions), asked when the report is written. */
@Volatile var headerExtras: (() -> List<Pair<String, String>>)? = null