Cotton code
186 lines · 7.0 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.ClipDataimport android.content.ClipDescriptionimport android.content.ClipboardManagerimport android.content.Contextimport android.os.PersistableBundleimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Jobimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launchimport java.util.UUID/** The time-to-clear is attempted only while this process and its scope remain alive. */enum class SensitiveClipboardExpiry {    BestEffortWhileProcessRuns,    NotScheduled,}/** A clipboard operation failed, but never carries platform text that could contain a copied value. */enum class SensitiveClipboardIssue {    CopyFailed,    ClearFailed,    ExpirySchedulingFailed,}/** * Copies a credential without retaining it outside Android's clipboard service. * * Android has no expiry date on a ClipData item. [copy] schedules a best-effort clear, * and [clear] only removes a clip whose opaque label still belongs to this instance. */interface SensitiveClipboard {    fun copy(value: CharSequence): SensitiveClipboardExpiry    fun clear()}/** A cancellable task used solely to make expiry deterministic in tests. */fun interface ClipboardExpiryCancellation {    fun cancel()}fun interface ClipboardExpiryScheduler {    fun schedule(delayMillis: Long, task: () -> Unit): ClipboardExpiryCancellation}/** The process scope owns the best-effort expiry: it deliberately does not survive a process death. */class CoroutineClipboardExpiryScheduler(    private val scope: CoroutineScope,) : ClipboardExpiryScheduler {    override fun schedule(delayMillis: Long, task: () -> Unit): ClipboardExpiryCancellation {        val job: Job = scope.launch {            delay(delayMillis)            task()        }        return ClipboardExpiryCancellation(job::cancel)    }}/** * Only clip metadata is read back. In particular, an expiry never reads or compares the secret. */interface SensitiveClipboardPlatform {    fun writeSensitive(labelToken: String, value: CharSequence)    fun currentLabel(): CharSequence?    fun clear()}/** Android's global clipboard boundary. */class AndroidClipboardPlatform(context: Context) : SensitiveClipboardPlatform {    private val clipboard = context.getSystemService(ClipboardManager::class.java)    override fun writeSensitive(labelToken: String, value: CharSequence) {        val clip = ClipData.newPlainText(labelToken, value)        // Description extras are API 24; the sensitive marker is understood by Android 13 (API 33)+.        clip.description.extras = PersistableBundle().apply {            putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true)        }        clipboard.setPrimaryClip(clip)    }    override fun currentLabel(): CharSequence? = clipboard.primaryClipDescription?.label    override fun clear() {        // clearPrimaryClip was introduced in API 28, the application's minimum SDK.        clipboard.clearPrimaryClip()    }}/** * Uses a random label to identify one copy operation. The token does not encode the copied * value, and is held only until that copy is cleared or superseded. */class AndroidSensitiveClipboard(    private val platform: SensitiveClipboardPlatform,    private val scheduler: ClipboardExpiryScheduler,    private val expiryMillis: Long = DEFAULT_EXPIRY_MILLIS,    private val nextLabelToken: () -> String = { UUID.randomUUID().toString() },) : SensitiveClipboard {    private val lock = Any()    private var activeLabelToken: String? = null    private var pendingExpiry: ClipboardExpiryCancellation? = null    private val _issue = MutableStateFlow<SensitiveClipboardIssue?>(null)    /** Transient failure state for retry affordances. It neither contains nor retains a copied value. */    val issue: StateFlow<SensitiveClipboardIssue?> = _issue.asStateFlow()    constructor(context: Context, scope: CoroutineScope) : this(        platform = AndroidClipboardPlatform(context.applicationContext),        scheduler = CoroutineClipboardExpiryScheduler(scope),    )    init {        require(expiryMillis > 0) { "Sensitive clipboard expiry must be positive." }    }    override fun copy(value: CharSequence): SensitiveClipboardExpiry = synchronized(lock) {        val labelToken = nextLabelToken()        try {            platform.writeSensitive(labelToken, value)        } catch (_: Throwable) {            // Leave the previous token and timer intact: the failed write has not superseded it.            _issue.value = SensitiveClipboardIssue.CopyFailed            throw IllegalStateException("The password could not be copied.")        }        pendingExpiry?.cancel()        pendingExpiry = null        activeLabelToken = labelToken        _issue.value = null        try {            pendingExpiry = scheduler.schedule(expiryMillis) { clearIfStillOurs(labelToken) }            SensitiveClipboardExpiry.BestEffortWhileProcessRuns        } catch (_: Throwable) {            // The copy succeeded but has no process timer. Keep its token for an explicit clear.            _issue.value = SensitiveClipboardIssue.ExpirySchedulingFailed            SensitiveClipboardExpiry.NotScheduled        }    }    override fun clear(): Unit = synchronized(lock) {        activeLabelToken?.let(::clearIfStillOurs)        Unit    }    private fun clearIfStillOurs(labelToken: String) {        try {            synchronized(lock) {                if (activeLabelToken != labelToken) return                try {                    // This is a best-effort identity check: another process can replace the clip after the                    // read and before clearPrimaryClip(), because Android provides no compare-and-clear.                    val label = platform.currentLabel()                    if (label == null) {                        // Background clipboard access may be denied. Keep ownership for a                        // foreground retry rather than claiming the value was cleared.                        _issue.value = SensitiveClipboardIssue.ClearFailed                        return                    }                    if (label.contentEquals(labelToken)) {                        platform.clear()                    }                } catch (_: Throwable) {                    // Retain the token and pending timer so a later explicit clear can retry safely.                    _issue.value = SensitiveClipboardIssue.ClearFailed                    return                }                activeLabelToken = null                pendingExpiry?.cancel()                pendingExpiry = null                _issue.value = null            }        } catch (_: Throwable) {            // A scheduler callback must not fail the process scope's supervisor.            _issue.value = SensitiveClipboardIssue.ClearFailed        }    }    companion object {        const val DEFAULT_EXPIRY_MILLIS: Long = 60_000    }}