package com.cottondb.android.platform import android.content.ClipDescription import android.content.ClipboardManager import android.content.Intent import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SensitiveClipboardTest { private val instrumentation = InstrumentationRegistry.getInstrumentation() private val context = instrumentation.targetContext private var activity: PermissionHarnessActivity? = null @After fun finishHarness() { instrumentation.runOnMainSync { activity?.finish() } } @Test fun expirationClearsOnlyTheCopyWhoseOpaqueLabelIsStillCurrent() { val platform = RecordingClipboardPlatform() val scheduler = ManualClipboardExpiryScheduler() val clipboard = AndroidSensitiveClipboard(platform, scheduler, nextLabelToken = { "copy-one" }) assertEquals(SensitiveClipboardExpiry.BestEffortWhileProcessRuns, clipboard.copy("synthetic")) platform.replaceWithExternalLabel("newer-app-copy") scheduler.runNext() assertEquals("newer-app-copy", platform.currentLabel()) assertFalse(platform.wasCleared) } @Test fun explicitClearAlsoLeavesANewerExternalCopyAlone() { val platform = RecordingClipboardPlatform() val scheduler = ManualClipboardExpiryScheduler() val clipboard = AndroidSensitiveClipboard(platform, scheduler, nextLabelToken = { "copy-one" }) clipboard.copy("synthetic") platform.replaceWithExternalLabel("newer-app-copy") clipboard.clear() assertEquals("newer-app-copy", platform.currentLabel()) assertFalse(platform.wasCleared) } @Test fun replacingOurCopyCancelsTheOldExpiration() { val platform = RecordingClipboardPlatform() val scheduler = ManualClipboardExpiryScheduler() var number = 0 val clipboard = AndroidSensitiveClipboard(platform, scheduler, nextLabelToken = { "copy-${++number}" }) clipboard.copy("first synthetic") clipboard.copy("second synthetic") scheduler.runAll() assertNull(platform.currentLabel()) assertTrue(platform.wasCleared) } @Test fun failedClearKeepsOwnershipForAnExplicitRetry() { val platform = RecordingClipboardPlatform().apply { failClear = true } val scheduler = ManualClipboardExpiryScheduler() val clipboard = AndroidSensitiveClipboard(platform, scheduler, nextLabelToken = { "copy-one" }) clipboard.copy("synthetic") scheduler.runNext() assertEquals(SensitiveClipboardIssue.ClearFailed, clipboard.issue.value) assertEquals("copy-one", platform.currentLabel()) platform.failClear = false clipboard.clear() assertNull(platform.currentLabel()) assertNull(clipboard.issue.value) } @Test fun deniedMetadataReadKeepsOwnershipUntilForegroundRetry() { val platform = RecordingClipboardPlatform() val scheduler = ManualClipboardExpiryScheduler() val clipboard = AndroidSensitiveClipboard(platform, scheduler, nextLabelToken = { "copy-one" }) clipboard.copy("synthetic") platform.denyRead = true scheduler.runNext() assertEquals(SensitiveClipboardIssue.ClearFailed, clipboard.issue.value) assertFalse(platform.wasCleared) platform.denyRead = false clipboard.clear() assertTrue(platform.wasCleared) assertNull(clipboard.issue.value) } @Test fun failedCopyLeavesThePreviousTimerResponsibleForItsClip() { val platform = RecordingClipboardPlatform() val scheduler = ManualClipboardExpiryScheduler() var number = 0 val clipboard = AndroidSensitiveClipboard(platform, scheduler, nextLabelToken = { "copy-${++number}" }) clipboard.copy("first synthetic") platform.failWrite = true var failed = false try { clipboard.copy("second synthetic") } catch (_: IllegalStateException) { // The copy failure is observable as a named state without retaining its value. failed = true } assertTrue(failed) assertEquals(SensitiveClipboardIssue.CopyFailed, clipboard.issue.value) scheduler.runNext() assertNull(platform.currentLabel()) } @Test fun androidBoundaryMarksTheClipSensitive() { startHarness() val systemClipboard = context.getSystemService(ClipboardManager::class.java) val platform = AndroidClipboardPlatform(context) val label = "clipboard-instrumentation-token" try { platform.writeSensitive(label, "synthetic") val description = systemClipboard.primaryClipDescription assertEquals(label, description?.label) assertTrue(description?.extras?.getBoolean(ClipDescription.EXTRA_IS_SENSITIVE) == true) } finally { // Do not erase a clip installed by another app while this test was running. if (systemClipboard.primaryClipDescription?.label?.contentEquals(label) == true) { platform.clear() } } } private class RecordingClipboardPlatform : SensitiveClipboardPlatform { private var label: String? = null var wasCleared = false private set var failWrite = false var failClear = false var denyRead = false override fun writeSensitive(labelToken: String, value: CharSequence) { if (failWrite) throw IllegalStateException("write failed") label = labelToken } override fun currentLabel(): CharSequence? = if (denyRead) null else label override fun clear() { if (failClear) throw IllegalStateException("clear failed") label = null wasCleared = true } fun replaceWithExternalLabel(externalLabel: String) { label = externalLabel } } private fun startHarness(): PermissionHarnessActivity { activity?.let { return it } val started = instrumentation.startActivitySync( Intent(context, PermissionHarnessActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), ) check(started is PermissionHarnessActivity) { "Unexpected foreground harness: $started" } return started.also { activity = it } } private class ManualClipboardExpiryScheduler : ClipboardExpiryScheduler { private val tasks = mutableListOf() override fun schedule(delayMillis: Long, task: () -> Unit): ClipboardExpiryCancellation { val scheduled = ScheduledTask(task) tasks += scheduled return ClipboardExpiryCancellation { scheduled.cancelled = true } } fun runNext() { tasks.removeFirst().runIfActive() } fun runAll() { while (tasks.isNotEmpty()) runNext() } private class ScheduledTask(private val task: () -> Unit) { var cancelled = false fun runIfActive() { if (!cancelled) task() } } } }