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
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ package io.privkey.keep.nip55
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import android.os.SystemClock
import io.privkey.keep.uniffi.AutoSignDecision
import io.privkey.keep.uniffi.SigningRateLimiter
import io.privkey.keep.uniffi.StorageRead
import io.privkey.keep.storage.KeystoreEncryptedPrefs
import java.io.File
import java.security.KeyStore
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
Expand Down Expand Up @@ -195,13 +201,46 @@ class AndroidSigningRateLimiterStorageTest {
)
}

// A file that no longer parses loads as empty. Every one of the package's limit keys
// has to read as unknown then, never as unused, or the core starts fresh windows
// instead of rewriting the state as full, and corrupting the file resets the limits.
// On a file of its own: dropping the platform's cached copy of the real one would leave
// the app's own store reading a map that no longer matches the disk.
@Test
fun aCorruptedFileReadsEveryLimitKeyUnavailable() {
val pkg = "com.example.app"
val keys = listOf("cooled_off_", "cooled_off_elapsed_", "hourly_", "daily_").map { "$it:$pkg" }
try {
val own = AndroidSigningRateLimiterStorage(context, CORRUPT_PREFS)
keys.forEach { assertTrue(own.save(it, "1")) }
val file = File(context.dataDir, "shared_prefs/$CORRUPT_PREFS.xml")
val written = file.readText()
assertTrue("the entries must have reached the file", written.length > 40)

context.deleteSharedPreferences(CORRUPT_PREFS)
file.writeText(written.substring(0, written.length / 2))

val reopened = AndroidSigningRateLimiterStorage(context, CORRUPT_PREFS)
keys.forEach { assertEquals(it, StorageRead.Unavailable, reopened.load(it)) }
val decision = SigningRateLimiter(reopened).checkAndRecord(
pkg, SystemClock.elapsedRealtime().toULong(), System.currentTimeMillis().toULong()
)
assertFalse("a corrupted file must not allow auto-signing", decision is AutoSignDecision.Allowed)
} finally {
context.deleteSharedPreferences(CORRUPT_PREFS)
KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
.deleteEntry(KeystoreEncryptedPrefs.keyAliasFor(CORRUPT_PREFS))
}
}

@Test
fun aNeverWrittenKeyReadsAbsentSoTheWindowCanStartFresh() {
assertEquals(StorageRead.Absent, storage.load("com.example.never.written"))
}

companion object {
private const val PREFS_NAME = "nip55_rate_limiter"
private const val CORRUPT_PREFS = "nip55_rate_limiter_corrupt_test"

/** The one entry the encrypted store keeps under its literal name. */
private const val HMAC_KEY_PREF = "__hmac_key__"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,40 @@ class Nip55CrossProcessRequestInstrumentedTest {
}
}

// An opted-in caller whose limit state will not decrypt: the core rewrites it as reached
// and the request goes to the user, and the pause is in the event log in every build.
@Test
fun crossProcess_unreadableLimitState_pausesAutoSigningAndLogsIt() {
val safeguards = app().getAutoSigningSafeguards()!!
val log = app().getEventLogStore()!!
val daily = "daily_:$clientPkg"
val since = System.currentTimeMillis()
try {
safeguards.setOptedIn(clientPkg, true)
assertTrue(AndroidSigningRateLimiterStorage(context).save(daily, "x"))
corruptExistingValue(context, LIMITER_PREFS, daily) { it.putString(daily, "x") }

val raw = runClientQuery(rid("limits"), "io.privkey.keep.SIGN_EVENT", signProjection)
assertTrue("a paused caller goes to the user, not signed for: $raw", raw.endsWith("cursor=null"))
val entry = awaitLog(log, since) { it.source == clientPkg && it.category == EventLogCategory.SIGNER.name }
assertNotNull("the pause must be logged", entry)
assertEquals(EventLogLevel.WARN.name, entry!!.level)
assertTrue(entry.message, entry.message.contains("paused until"))
} finally {
safeguards.clearOptIn(clientPkg)
app().getSigningRateLimiter()?.clearCoolingOff(clientPkg)
}
}

private fun awaitLog(log: EventLogStore, since: Long, match: (EventLogEntry) -> Boolean): EventLogEntry? {
val deadline = System.currentTimeMillis() + 10_000
while (System.currentTimeMillis() < deadline) {
runBlocking { log.getRecent(50) }.firstOrNull { it.timestamp >= since && match(it) }?.let { return it }
Thread.sleep(200)
}
return null
}

private fun latestAuditId(): Long = runBlocking {
app().getPermissionStore()!!.getAuditLog(limit = 1).firstOrNull()?.id ?: 0L
}
Expand All @@ -430,6 +464,7 @@ class Nip55CrossProcessRequestInstrumentedTest {
const val RELAY_AUTH_KIND = 22242
const val RELAY_HOST = "relay.example.com"
const val OTHER_EXPIRED_PKG = "io.privkey.keeptest.otherexpired"
const val LIMITER_PREFS = "nip55_rate_limiter"

// Opt-in gate (mirrors FrostSignFixture.MANUAL_ARG): every test method reports
// SKIPPED unless invoked with -e crossProcessManual 1, so a local run without the
Expand Down
12 changes: 9 additions & 3 deletions app/src/main/kotlin/io/privkey/keep/KeepMobileApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,16 @@ class KeepMobileApp : Application() {
is ConnectionStatus.Error -> Triple(EventLogLevel.ERROR, "", status.message)
}

private fun logActivityEvent(category: EventLogCategory, level: EventLogLevel, source: String, message: String) {
val store = eventLogStore ?: return
fun logActivityEvent(
category: EventLogCategory,
level: EventLogLevel,
source: String,
message: String,
onNotLogged: () -> Unit = {},
) {
val store = eventLogStore ?: return onNotLogged()
applicationScope.launch {
runCatching { store.log(category, level, source, message) }
runCatching { store.log(category, level, source, message) }.onFailure { onNotLogged() }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@ private const val TAG = "RateLimiterStorage"
* unexpected-callback error and panics Rust on the signing path, so faults are
* converted into the failure value instead.
*/
class AndroidSigningRateLimiterStorage(context: Context) : SigningRateLimiterStorage {
class AndroidSigningRateLimiterStorage(
context: Context,
prefsName: String = PREFS_NAME,
) : SigningRateLimiterStorage {

private val prefs = KeystoreEncryptedPrefs.create(context, PREFS_NAME)
private val prefs = KeystoreEncryptedPrefs.create(context, prefsName)

override fun load(key: String): StorageRead =
runCatching {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey

enum class EventLogCategory { RELAY, BUNKER, PEER }
enum class EventLogCategory { RELAY, BUNKER, PEER, SIGNER }

enum class EventLogLevel { INFO, WARN, ERROR }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import java.security.MessageDigest
import java.security.SecureRandom
import java.time.Instant
import java.util.Calendar
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Semaphore
Expand Down Expand Up @@ -159,6 +160,25 @@ class Nip55ContentProvider : ContentProvider() {

private val app: KeepMobileApp? get() = context?.applicationContext as? KeepMobileApp

// Refused on every request while storage stays broken, so logged once per process.
private val storageFaultLogged = ConcurrentHashMap.newKeySet<String>()

// Logged in every build: either one changes how this app is signed for until it clears.
private fun logLimiterFault(app: KeepMobileApp, packageName: String, decision: AutoSignDecision) {
val message = when (decision) {
is AutoSignDecision.LimitStateUnreadable ->
"auto-signing limits could not be read and were reset as reached; auto-signing paused until " +
Instant.ofEpochMilli(decision.untilMs.toLong())
AutoSignDecision.StorageUnavailable ->
if (!storageFaultLogged.add(packageName)) return else "auto-signing limits could not be read or saved; every request asks for approval until storage recovers"
Comment thread
kwsantiago marked this conversation as resolved.
Resolved
else -> return
}
val level = if (decision is AutoSignDecision.StorageUnavailable) EventLogLevel.ERROR else EventLogLevel.WARN
app.logActivityEvent(EventLogCategory.SIGNER, level, packageName, message) {
if (decision is AutoSignDecision.StorageUnavailable) storageFaultLogged.remove(packageName)
}
}

// Run `block` under a real wall-clock bound. `block` may reach a blocking,
// non-cancellable FFI call, which `withTimeoutOrNull` cannot interrupt in place
// (there is no suspension point to cancel at). So the work runs on [orphanScope]
Expand Down Expand Up @@ -362,11 +382,12 @@ class Nip55ContentProvider : ContentProvider() {
} else {
runWithTimeout {
try {
// Logged here so a check that outlives the timeout still records it.
limiter.checkAndRecord(
callerPackage,
SystemClock.elapsedRealtime().toULong(),
System.currentTimeMillis().toULong()
)
).also { logLimiterFault(currentApp, callerPackage, it) }
} catch (e: Exception) {
if (BuildConfig.DEBUG) Log.w(TAG, "Rate limiter check failed, failing closed to UI: ${e::class.simpleName}")
null
Expand Down
2 changes: 1 addition & 1 deletion keep.version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
d9e33ccb15e235ebf5643c0239c252772e0ac24a
b8499dca0936adf69f418ccbace9464bde979072