Skip to content

fix(transfer): require local initiation, pairing confirmation, and one-time session authorization - #6893

Open
SeniorZhai wants to merge 11 commits into
masterfrom
fix/device-transfer-session-auth
Open

SeniorZhai wants to merge 11 commits into
masterfrom
fix/device-transfer-session-auth

Conversation

@SeniorZhai

Copy link
Copy Markdown
Member

No description provided.

…-session-auth

# Conflicts:
#	app/src/main/java/one/mixin/android/ui/transfer/TransferActivity.kt
#	app/src/main/java/one/mixin/android/ui/transfer/TransferClient.kt
#	app/src/main/java/one/mixin/android/ui/transfer/TransferServer.kt
@gaotic

gaotic Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

AI review done for a8796e2 in 16m 58s · 3 comments

Quality: The transfer authorization changes are substantial, but the PR still has medium-to-high risk around expiry cleanup and interrupted restores. Static inspection confirmed all three defects, while the focused Gradle tests were blocked before execution because the wrapper could not create its cache directory.

Role Model Status
Reviewer GPT codex/gpt-6.2-sol · effort high ok
Reviewer Grok grok/grok-4.7@500k · effort medium ok
Summary codex/gpt-6.2-sol · effort medium ok

@gaotic gaotic Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review · Codex (Grok failed) · 7d39caa

git diff --check and XML parsing passed, and three targeted JVM checks reproduced the reported behaviors they covered. Android assembly, lint, and unit tests were blocked before execution because the wrapper could not download Gradle 9.9.2 and the installed Gradle could not initialize file locking in the sandbox.

toast(R.string.transfer_pairing_expired_or_cancelled)
return@setPositiveButton
}
pushRequest()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pass the approved authorization to pushRequest(). It currently replaces the approved session, then sendMessage() looks up the linked desktop again, so a desktop relink while the dialog is open can send the transfer credentials to a different session. Send the credentials only to the approved extension session and require that authorization when the server accepts CONNECT.

jobManager.addJobInBackground(AsyncProcessTransferAttachmentFileJob(getAttachmentPath()))
mutableList.clear()
transferSessionManager.cancelSession(currentAuthorization?.sessionId)
clearCacheDirectory()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deleting the staging directory here can leave imported messages with missing media. Message batches are committed before FINISH, so a connection drop can leave their rows in the database while this branch deletes attachments that already arrived. Preserve staged files that match committed messages, as the previous cleanup job did.

) {
val session = currentSession ?: return
if (session.accountId == accountId &&
(session.expectedExtensionSessionId == null || session.expectedExtensionSessionId == extensionSessionId) &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A cancellation from the linked desktop can abort an unrelated phone restore. Phone restores have a null expectedExtensionSessionId, which this condition treats as a match. The isolated check confirmed that the restore becomes CANCELLED and loses write authorization. Require an exact, non-null extension session match before applying a desktop cancellation.

onConnectionFailed,
val ip = requireNotNull(transferCommandData.ip)
val port = requireNotNull(transferCommandData.port)
val key = requireNotNull(transferCommandData.secretKey).decodeBase64()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirming a phone restore can crash when the QR code contains a nonblank, malformed Base64 key. Validation accepts it, then the decoder throws before TransferClient can handle the failure, and the confirmation coroutine has no exception handler. Decode and validate the key before showing the confirmation dialog and report invalid input as a data error.

super.onStop()
transferDisposable?.dispose()
transferSpeedDisposable?.dispose()
transferControlDisposable?.dispose()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A desktop restore can get stuck on Waiting if the reply arrives while this activity is stopped. onStop() removes the subscriber, the bus does not replay the reply, and the message is marked read. Returning to the screen leaves Start disabled. Retain the pending reply for the active session and handle it when the activity resumes.

@gaotic gaotic Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review · Codex (Grok failed) · 761a49e

Three defects remain after reviewing the changes since the previous revision. Both Git diff checks and XML parsing passed, and the simulated-clock JVM check reproduced expiry in both sending directions. Gradle failed during native-service initialization, before Android assembly, lint, or unit tests ran.

}
lifecycleScope.launch {
transferServer.startServer(selectConversation, selectDate) { transferData ->
transferServer.startServer(sessionId, selectConversation, selectDate) { transferData ->

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A desktop relink can redirect the credentials for an approved transfer. This call retains the local session ID, but sendMessage() looks up the linked desktop again when it runs, so the newly linked session can receive the connection details and key. Use the extension session recorded in the approval as the recipient and bind the server’s CONNECT check to that authorization.

jobManager.addJobInBackground(AsyncProcessTransferAttachmentFileJob(getAttachmentPath()))
mutableList.clear()
transferSessionManager.cancelSession(currentAuthorization?.sessionId)
clearCacheDirectory()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An interrupted restore can leave committed messages with missing attachments. processJson() commits batches before FINISH, and this branch deletes the staging directory on disconnect. The finally block also deletes files left behind when attachment processing aborts. Restore the cleanup job’s recovery behavior for staged files that match committed messages.

private fun expireIfNeeded(session: TransferSession) {
if (clock() <= session.expiresAtMillis) return
if (session.state == TransferSessionState.INITIATED || session.state == TransferSessionState.AWAITING_PAIRING ||
session.state == TransferSessionState.SENDING || (session.state == TransferSessionState.CONSUMED && session.direction.isSending)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applying the pairing deadline to SENDING can cut off an active transfer. A clock test confirmed that after four minutes of setup, both sending directions expire just over one minute into sending. The server checks that state before each socket write. Give active transfers a separate deadline that starts after the connection is verified.

@gaotic gaotic Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review · GPT + Grok · 45f3275

The PR is not ready to merge because five transfer-flow defects remain, including two regressions in the new permission queue and three previously reported issues that are still present. git diff --check and manifest XML validation passed, while Gradle tests could not start because the offline cache lacks org.gradle.toolchains.foojay-resolver-convention:1.0.0.

action: () -> Unit,
) {
if (Build.VERSION.SDK_INT < 37 ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_LOCAL_NETWORK) == PackageManager.PERMISSION_GRANTED

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This runtime gate is incompatible with the app's current targetSdk = 36. Android 17 grants local-network access implicitly to apps targeting SDK 36 or lower through INTERNET, while ACCESS_LOCAL_NETWORK and its runtime request apply when targeting SDK 37 or higher. With this manifest declaration and request, Android 17 can leave transfer blocked behind a permission the app has not opted into. Remove the declaration/request until the target SDK is raised, or gate the entire flow on a matching target-SDK migration.

binding.qrFl.fadeIn()
binding.initLl.isVisible = false
binding.waitingLl.isVisible = false
withLocalNetworkPermission {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The initial pushRequest() or pullRequest() action is queued with the default cancellableByDesktop = false. If the desktop sends CANCEL while the local-network permission sheet is open, cancelPendingDesktopCommands() removes only pairing actions, so granting the permission later still starts the transfer after the handler has reset the UI and created a replacement session. Mark the start action as cancellable, or invalidate all queued actions for the canceled session before processing the permission result.

scope.launch(Dispatchers.IO) {
try {
val accountId = Session.getAccountId() ?: return@launch
val sessionId = Session.getExtensionSessionId() ?: return@launch

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The approved transfer still sends its connection data to whichever desktop session is current when this coroutine runs. pushRequest(authorization.sessionId) preserves only the local transfer session ID, while this lookup can return a newly relinked extension session during the permission wait. Pass authorization.expectedExtensionSessionId through the send path and enforce the same bound session in the server's CONNECT validation so a relink cannot receive the key.

jobManager.addJobInBackground(AsyncProcessTransferAttachmentFileJob(getAttachmentPath()))
mutableList.clear()
transferSessionManager.cancelSession(currentAuthorization?.sessionId)
clearCacheDirectory()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An interrupted restore can leave committed messages without their attachments. processJson() inserts message batches before FINISH, but this disconnect path deletes the entire staging cache, and the success-path finally also deletes the attachment directory if processAttachmentFile() aborts midway. Preserve staged files for committed messages and let the attachment recovery job finish copying them on the next run before removing the staging data.

private fun expireIfNeeded(session: TransferSession) {
if (clock() <= session.expiresAtMillis) return
if (session.state == TransferSessionState.INITIATED || session.state == TransferSessionState.AWAITING_PAIRING ||
session.state == TransferSessionState.SENDING || (session.state == TransferSessionState.CONSUMED && session.direction.isSending)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The five-minute pairing deadline is still applied to SENDING. A transfer that spends most of that period in setup becomes EXPIRED during active transmission because TransferServer.requireActiveSession() checks the session before each socket write. Start a separate transfer deadline when the connection is verified, or otherwise exempt active sending from the pairing TTL while retaining a bounded transfer timeout.

@gaotic gaotic Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review · GPT + Grok · db74f31

Needs fixes before merge. All five findings from the previous review are still present at the PR head, and the latest commit only adds sender device IDs to transfer commands. Whitespace checks passed, XML validation passed, and Gradle unit tests were blocked before compilation by the missing offline org.gradle.toolchains.foojay-resolver-convention:1.0.0 plugin.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This runtime gate is incompatible with the app's current targetSdk = 36. Android 17 applies ACCESS_LOCAL_NETWORK runtime enforcement to apps targeting SDK 37 or higher, while SDK 36 and lower receive local-network access through INTERNET. With this declaration and the request in TransferActivity, Android 17 can leave transfers blocked behind a permission flow that does not apply to this target. Remove the declaration/request until the target-SDK migration, or gate the whole flow on the matching target SDK.

binding.qrFl.fadeIn()
binding.initLl.isVisible = false
binding.waitingLl.isVisible = false
withLocalNetworkPermission {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This start action is queued with cancellableByDesktop = false. If the desktop sends CANCEL while the local-network permission sheet is open, cancelPendingDesktopCommands() removes only cancellable entries, so granting permission later still invokes pushRequest() or pullRequest() after the cancellation handler has reset the session. Mark the start action cancellable, or invalidate all queued actions for the canceled session before processing the permission result.

scope.launch(Dispatchers.IO) {
try {
val accountId = Session.getAccountId() ?: return@launch
val sessionId = Session.getExtensionSessionId() ?: return@launch

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The approved transfer still sends its connection payload to whichever extension session is current when this coroutine runs. The authorization keeps expectedExtensionSessionId, but sendMessage() rereads Session.getExtensionSessionId() after the permission and approval waits. A relink in that interval can therefore receive the IP, port, code, and secret key. Carry the expected extension session ID through this send path and bind the server's CONNECT validation to the same peer session.

try {
processAttachmentFile(folder)
} finally {
folder.deleteRecursively()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This unconditional cleanup can delete attachments for messages already committed by processJson(). If attachment processing is interrupted or fails midway, the committed messages remain while their staged files are removed, so the attachment recovery job cannot restore them. Preserve staged files for committed messages and remove them only after attachment processing succeeds, including the interrupted-restore path.

private fun expireIfNeeded(session: TransferSession) {
if (clock() <= session.expiresAtMillis) return
if (session.state == TransferSessionState.INITIATED || session.state == TransferSessionState.AWAITING_PAIRING ||
session.state == TransferSessionState.SENDING || (session.state == TransferSessionState.CONSUMED && session.direction.isSending)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original five-minute deadline still expires SENDING sessions. TransferServer.requireActiveSession() calls getSessionState() before socket writes, so a transfer that spends most of the deadline in setup or runs longer than the remaining TTL becomes EXPIRED mid-transfer. Start a separate bounded transfer deadline when sending begins, or exempt active sending from the pairing TTL while retaining a transfer timeout.

…-session-auth

# Conflicts:
#	app/src/main/java/one/mixin/android/ui/transfer/TransferActivity.kt
#	app/src/test/java/one/mixin/android/ui/transfer/LocalNetworkPermissionQueueTest.kt

@gaotic gaotic Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review · GPT + Grok · d563a93

Needs fixes before merge. git diff --check passes and the relevant source paths were inspected. The focused Gradle unit-test command was blocked before execution because the wrapper could not download Gradle from services.gradle.org in this environment.

}
}
session.state = TransferSessionState.SENDING
session.transferExpiresAtMillis = null

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

beginSending() clears transferExpiresAtMillis, so while the server is waiting in listener.accept() the session still uses the original pairing deadline. If the desktop connects after that five-minute deadline, validateServerConnect() sees EXPIRED and the transfer is rejected before the two-hour transfer TTL is established. Initialize the bounded transfer deadline when sending starts, or otherwise keep the session valid through the connection wait, and add coverage for a late CONNECT.

clearCacheDirectory()
status.value = TransferStatus.FINISHED
} else {
preserveOrClearStagedAttachments()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When attachment processing fails, this branch preserves the staged files and then calls cancelSession(). exit(true) has already set quit = true, and cancellation makes getSessionState() return CANCELLED, so the guarded assignment to TransferStatus.ERROR can never run. The receive screen therefore remains in PROCESSING, while the background recovery job does not update the transfer status. Set the error state for this failure path before or independently of cancellation, while retaining the separate intentional-cancel behavior.

Clearing the transfer deadline made the peer's CONNECT subject to the original pairing deadline, so slow preparation could cause the connection to be rejected as expired.
The error status was gated on a session state that cancelSession had just overwritten, leaving the UI stuck in processing. Track user cancellation separately and set the status before cancelling the session.
Extract the attachment failure handling into a small internal function so it can be tested with the real session manager instead of mocks.

@gaotic gaotic Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review · GPT + Grok · 37419a0

Needs fixes before merge due to the stale expired-offer state while the server is blocked in accept(). git diff --check passed. The focused Gradle tests were attempted but were blocked when Gradle tried to download gradle-9.9.2 from services.gradle.org in this environment.


app/src/main/java/one/mixin/android/ui/transfer/TransferServer.kt:199

listener.accept() can remain blocked after the session's restarted pairing window expires because no socket timeout or expiry-driven close is applied. The UI stays in WAITING_FOR_CONNECTION with the QR/start state available, and a later peer is only rejected after it connects. Bound the accept wait to the session deadline or add an expiry watcher that closes the listener and transitions the status so stale offers are cleared promptly.

@gaotic gaotic Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review · GPT + Grok · a8796e2

Needs fixes before merge. git diff --check passed, and the post-review delta was inspected. The focused TransferSessionManager and TransferClient unit-test invocation could not run because /Users/binyang/.gradle is not writable.


app/src/main/java/one/mixin/android/ui/transfer/TransferClient.kt:545

When a restore ends before FINISH or authorization is lost, this branch clears mutableList without calling insertMessages or removing the FTS rows already created in processJson. A batch smaller than 1,000 messages is therefore absent from the message table while its messages_metas and FTS entries remain, producing search hits that cannot load details. Preserve the pending batch until a successful finish, or explicitly roll back its FTS metadata when aborting.


app/src/main/java/one/mixin/android/ui/transfer/TransferSessionManager.kt:278

A consumed receiver session is treated as active indefinitely. isAuthorizationActiveForWrite() does not check authorization.expiresAtMillis, and expireIfNeeded() only expires CONSUMED sessions for sending directions. Consequently, after pairing confirmation a peer can connect and send START long after the pairing deadline, and validateStartHandshake() still accepts it. Apply the authorization/session deadline to consumed receiver sessions in both the write check and handshake validation.


app/src/main/java/one/mixin/android/ui/transfer/TransferServer.kt:199

The server can remain blocked in listener.accept() after the session's restarted pairing deadline passes. No expiry task closes the listener and no accept timeout causes the loop to re-check the session, so the UI remains in WAITING_FOR_CONNECTION with a stale QR until a peer connects or the user exits. Close the listener when the session expires, or bound the accept wait and transition the status on expiry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant