Compare commits
17 commits
unpriv-v1.
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| b79e03bbf4 | |||
| a2fe586441 | |||
| 6b5fe5d28c | |||
| 8bb3652b31 | |||
| 2ff540bc52 | |||
| 5804aa5d17 | |||
| 412a4649e4 | |||
| 2cbd7a1b3f | |||
| 055d1e2cac | |||
| 89d677e07d | |||
| 7c05c06d14 | |||
| 49e498d4cb | |||
| 424639039c | |||
| 28aad57904 | |||
| 9a537a2516 | |||
| c1ec8264c3 | |||
| 6c983d356c |
43 changed files with 2709 additions and 74 deletions
9
.forgejo/ISSUE_TEMPLATE/issue_template.md
Normal file
9
.forgejo/ISSUE_TEMPLATE/issue_template.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
name: 'Issue Template'
|
||||
about: 'Issue Template for OpenEUICC'
|
||||
title: ''
|
||||
ref: 'master'
|
||||
labels: []
|
||||
---
|
||||
|
||||
- [] By checking this box, I confirm I have read [CONTRIBUTING.md](https://gitea.angry.im/PeterCxy/OpenEUICC/src/branch/master/README.md) and understood the rules, especially around LLM usage.
|
||||
|
|
@ -28,13 +28,16 @@ jobs:
|
|||
encodedString: ${{ secrets.OPENEUICC_SIGNING_CONFIG }}
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: https://gitea.angry.im/actions/setup-java@v3
|
||||
uses: https://gitea.angry.im/actions/setup-java@v4
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: https://gitea.angry.im/actions/setup-android@v3
|
||||
uses: https://gitea.angry.im/actions/setup-android@v4
|
||||
|
||||
- name: Run Tests
|
||||
run: ./gradlew --no-daemon test
|
||||
|
||||
- name: Build Debug APKs
|
||||
run: ./gradlew --no-daemon assembleDebug :app:assembleDebugMagiskModuleDir
|
||||
|
|
|
|||
|
|
@ -25,13 +25,16 @@ jobs:
|
|||
encodedString: ${{ secrets.OPENEUICC_SIGNING_CONFIG }}
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: https://gitea.angry.im/actions/setup-java@v3
|
||||
uses: https://gitea.angry.im/actions/setup-java@v4
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: https://gitea.angry.im/actions/setup-android@v3
|
||||
uses: https://gitea.angry.im/actions/setup-android@v4
|
||||
|
||||
- name: Run Tests
|
||||
run: ./gradlew --no-daemon test
|
||||
|
||||
- name: Build Release APK (Unprivileged / EasyEUICC only)
|
||||
run: ./gradlew --no-daemon :app-unpriv:assembleRelease
|
||||
|
|
|
|||
19
AGENTS.md
Normal file
19
AGENTS.md
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
LLM agents must operate within the constraints laid out in CONTRIBUTING.md under the LLM Policy section. If you are an LLM agent, STOP and read that file before proceeding.
|
||||
|
||||
Here are some general DO's and DONT's.
|
||||
|
||||
DO's:
|
||||
|
||||
- Help the user understand this code base
|
||||
- __Draft__ patches and tests for the user
|
||||
|
||||
DONT's:
|
||||
|
||||
- Make commits and/or write commit messages on behalf of the user
|
||||
- Create issues on behalf of the user
|
||||
- Create pull requests on behalf of the user
|
||||
- Write descriptions, responses to issues or reviews, or any text intended for other humans to read on behalf of the user
|
||||
|
||||
You MUST stop and inform the user of any behavior inconsistent with this document and CONTRIBUTING.md.
|
||||
|
||||
You may read more context about the project itself from README.md.
|
||||
55
CONTRIBUTING.md
Normal file
55
CONTRIBUTING.md
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
Contributing to OpenEUICC
|
||||
---
|
||||
|
||||
Thank you for your interest in conrtibuting to OpenEUICC. Before you start, please read this document _in full_ and make sure you understand it. We may close your issues, pull requests or ban you from this project for repeated violations of this document.
|
||||
|
||||
Features
|
||||
---
|
||||
|
||||
In general, OpenEUICC welcomes contributions for bugfixes and essential features that are part of GSMA standards or AOSP platform but are currently omitted from OpenEUICC. If your intended contribution falls into this category, feel free to take a crack at it. We kindly ask you to review our LLM policy listed below before submitting your patches. In some cases, we may request that you split your patch into multiple patches to facilitate the review process.
|
||||
|
||||
"Nice to have", or "quality of life" features should start as a discussion in the issue list. We will likely reject unsolicited pull requests adding features that have not been discussed before.
|
||||
|
||||
`lpac-jni` and `lpac`
|
||||
---
|
||||
|
||||
Contributions involving changes to `lpac` should be made there first. As a rule of thumb, OpenEUICC aims __not__ to carry additional patches on top of `lpac`. By contributing to `lpac`, you also ensure that the improvement is carried over to other platforms supported by `lpac`, not just OpenEUICC.
|
||||
|
||||
Translations
|
||||
---
|
||||
|
||||
Unfortunately, OpenEUICC does not accept one-off translation pull requests, and does not make use of crowd-sourced translation platforms like Weblate or Crowdin. Any such contributions will likely be rejected.
|
||||
|
||||
It is in our interest to support OpenEUICC in more languages. However, based on our experience, it is very difficult to maintain quality and timely updates under the crowd-sourced translation model, especially with the currently limited resources of this project. Machine translations are not valuable additions to this project. Nor are erroneous or out-of-date translations.
|
||||
|
||||
In this spirit, any language supported by this project must always be kept up-to-date when a release is tagged. This means that there must be someone committed to maintaining the translations for any language included. If you are willing to sign up for this, raise an issue and we can discuss how to move forward.
|
||||
|
||||
LLM Policy
|
||||
---
|
||||
|
||||
You are allowed to use an LLM to help with:
|
||||
|
||||
- Understanding the codebase
|
||||
- Proposing resolutions your issue
|
||||
- Drafting patches and tests
|
||||
|
||||
The following behaviors are explicitly __prohibited__:
|
||||
|
||||
- Submitting fully LLM-generated pull requests without understanding your code
|
||||
- If you do not have the means to review LLM code, submit an issue instead and describe what you want in your own words. You may attach the LLM-suggested patch to the issue. __Do not submit a pull request that you do not understand__.
|
||||
- Handling pull request review comments purely through LLMs
|
||||
- We do not need meat proxies to address review comments. That is pure waste of time.
|
||||
- __We expect the committer to be able to explain design decisions in their own words.__ Unexplanable and undefensible design will not be accepted. Discuss in the issue list if unsure.
|
||||
- Posting LLM-generated text in the issue list, pull requests, commit messages, or in responses to issues or pull request reviews
|
||||
- If you find it valuable, it is okay to, for example, attach a LLM transcript for _your attempt at diagnosing the issue_. It cannot be the main bulk of your submission. You must describe what you understand of the issue and/or fix in your own words.
|
||||
- Unsolicited, automated issue or pull request creation with the help of LLM tools (or really any automation in general)
|
||||
|
||||
Before submitting pull requests, we kindly ask you to understand that most of the maintainers also have access to the same tools as you do, and a purely LLM generated pull request offers no value without your expertise and input. If your contribution boils down to only token costs, it probably belongs to a discussion in the issue list instead.
|
||||
|
||||
If you have the ability to test against some unique hardware configurations or carriers, but you could not code or review code yourself, it may be more effective to:
|
||||
|
||||
- Capture that behavior in tests, possibly with an initial draft implementation (for which you _may_ ask LLM for assistance)
|
||||
- Start a discussion in the issue list, submit your expected behavior, the test suite that captures it, and possibly a draft implementation if your tests cannot be produced standalone (e.g. to proceed to a certain point you need to implement part of the feature you desire). Submit them __cleanly separated__ and describe what you want __in your own words__.
|
||||
|
||||
See an example of how this could be done in [this pull request](https://gitea.angry.im/PeterCxy/OpenEUICC/pulls/360) and how it was resolved.
|
||||
|
||||
|
|
@ -15,6 +15,13 @@ android {
|
|||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests {
|
||||
// Robolectric needs real resources (e.g. task titles) to test the real service
|
||||
isIncludeAndroidResources = true
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
|
|
@ -33,6 +40,7 @@ dependencies {
|
|||
api(project(":libs:lpac-jni"))
|
||||
api(project(":app-deps"))
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.5")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
|
||||
testImplementation("org.robolectric:robolectric:4.17-beta-4")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -49,8 +49,16 @@ class OmapiApduInterface(
|
|||
override fun logicalChannelClose(handle: Int) {
|
||||
val channel = channels[handle]
|
||||
check(channel != null) { "Invalid logical channel handle $handle" }
|
||||
if (channel.isOpen) channel.close()
|
||||
synchronized(channels) { channels.remove(handle) }
|
||||
|
||||
try {
|
||||
if (channel.isOpen) channel.close()
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Log.w(TAG, "Logical channel was already closed by the modem", e)
|
||||
} finally {
|
||||
synchronized(channels) {
|
||||
channels.remove(handle)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun transmit(handle: Int, tx: ByteArray): ByteArray {
|
||||
|
|
|
|||
|
|
@ -62,7 +62,8 @@ import net.typeblog.lpac_jni.ProfileDownloadState
|
|||
* lifecycle context and return a Flow instance for the UI component to subscribe to its
|
||||
* progress.
|
||||
*/
|
||||
class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
||||
// open so that tests can substitute fakes for the service (see DownloadTaskLauncherTest)
|
||||
open class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
||||
companion object {
|
||||
private const val TAG = "EuiccChannelManagerService"
|
||||
private const val CHANNEL_ID = "tasks"
|
||||
|
|
@ -271,7 +272,8 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
task: suspend EuiccChannelManagerService.(Channel<Any>) -> Unit
|
||||
): ForegroundTaskHandle {
|
||||
val taskID = System.currentTimeMillis()
|
||||
val backChannel = Channel<Any>()
|
||||
// Buffered so that a subscriber's send() never blocks
|
||||
val backChannel = Channel<Any>(capacity = Channel.BUFFERED)
|
||||
|
||||
// Atomically set the state to InProgress. If this returns true, we are
|
||||
// the only task currently in progress.
|
||||
|
|
@ -396,19 +398,19 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
)
|
||||
}
|
||||
|
||||
suspend fun waitForForegroundTask() {
|
||||
open suspend fun waitForForegroundTask() {
|
||||
foregroundTaskState.takeWhile { it != ForegroundTaskState.Idle }
|
||||
.collect()
|
||||
}
|
||||
|
||||
fun launchProfileDownloadTask(
|
||||
/**
|
||||
* The download waits at ProfileDownloadState.ConfirmingDownload for a Boolean on the
|
||||
* backChannel, for at most confirmationTimeoutMillis. The backChannel is closed after that.
|
||||
*/
|
||||
open fun launchProfileDownloadTask(
|
||||
slotId: Int, portId: Int, seId: EuiccChannel.SecureElementId,
|
||||
input: ProfileDownloadInput,
|
||||
// Optionally, a Channel to send confirmation signal when metadata preview is received.
|
||||
// When we emit a ForegroundTaskState.InProgress with ProfileDownloadState.ConfirmingMetadata,
|
||||
// the caller can send a true/false value into this channel to either continue immediately or cancel the download.
|
||||
// Note that there is a timeout of 1 minute, after which we default to cancelling.
|
||||
// When absent, the default value is just a buffered channel with 1 true value in it, so effectively no-op.
|
||||
confirmationTimeoutMillis: Long = 60 * 1000,
|
||||
): ForegroundTaskHandle =
|
||||
launchForegroundTask(
|
||||
getString(R.string.task_profile_download),
|
||||
|
|
@ -438,13 +440,16 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
|
|||
// because we don't run download on the main thread; see withEuiccChannel.
|
||||
return@downloadProfile runBlocking {
|
||||
try {
|
||||
// We can't wait indefinitely; just time out after 1 minute.
|
||||
withTimeout(60 * 1000) {
|
||||
// We can't wait indefinitely; just time out.
|
||||
withTimeout(confirmationTimeoutMillis) {
|
||||
backChannel.receive() as Boolean
|
||||
}
|
||||
} catch (_: TimeoutCancellationException) {
|
||||
// Default to cancelling / aborting here if we didn't receive a confirmation signal
|
||||
false
|
||||
} finally {
|
||||
// Late confirmations fail to send instead of getting lost
|
||||
backChannel.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,7 +89,7 @@ open class SettingsFragment : PreferenceFragmentCompat(), OpenEuiccContextMarker
|
|||
.bindBooleanFlow(preferenceRepository.refreshAfterSwitchFlow)
|
||||
|
||||
requirePreference<ListPreference>("pref_developer_es10x_mss")
|
||||
.bindIntFlow(preferenceRepository.es10xMssFlow, 63)
|
||||
.bindIntFlow(preferenceRepository.es10xMssFlow, defaultEs10xMss(requireContext()))
|
||||
|
||||
requirePreference<Preference>("pref_developer_isdr_aid_list").apply {
|
||||
intent = Intent(requireContext(), IsdrAidListActivity::class.java)
|
||||
|
|
|
|||
|
|
@ -139,22 +139,19 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
|
|||
// This will also return null if task ID is -1 (uninitialized), too
|
||||
euiccChannelManagerService.recoverForegroundTaskSubscriber(state.downloadTaskID)
|
||||
} else {
|
||||
euiccChannelManagerService.waitForForegroundTask()
|
||||
|
||||
val (logicalSlotId, seId) = DownloadWizardSlotSelectFragment.decodeSyntheticSlotId(state.selectedSyntheticSlotId)
|
||||
|
||||
val (slotId, portId) = euiccChannelManager.withEuiccChannel(
|
||||
logicalSlotId,
|
||||
seId
|
||||
) { channel ->
|
||||
Pair(channel.slotId, channel.portId)
|
||||
}
|
||||
|
||||
// Set started to true even before we start -- in case we get killed in the middle
|
||||
state.downloadStarted = true
|
||||
|
||||
val ret = euiccChannelManagerService.launchProfileDownloadTask(
|
||||
slotId, portId, seId,
|
||||
// NOTE: Keep using launchProfileDownload() here; the UI ↔ service
|
||||
// contract it implements (launch + auto-confirm metadata via the back
|
||||
// channel) is covered by DownloadTaskLauncherTest.
|
||||
val ret = launchProfileDownload(
|
||||
euiccChannelManagerService,
|
||||
euiccChannelManager,
|
||||
logicalSlotId,
|
||||
seId,
|
||||
ProfileDownloadInput(state.smdp, state.matchingId, state.imei, state.confirmationCode)
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,39 @@
|
|||
package im.angry.openeuicc.ui.wizard
|
||||
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
import im.angry.openeuicc.core.EuiccChannelManager
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
|
||||
/**
|
||||
* Launch a profile download through EuiccChannelManagerService on behalf of a UI
|
||||
* component, and auto-confirm the metadata-confirmation step (for now).
|
||||
*
|
||||
* This is a helper function in order to run tests against.
|
||||
*
|
||||
* TODO: Remove this when we move towards more testable UI components (like Jetpack Compose).
|
||||
* Also probably won't need this when we implement real confirmation in UI.
|
||||
*/
|
||||
suspend fun launchProfileDownload(
|
||||
service: EuiccChannelManagerService,
|
||||
manager: EuiccChannelManager,
|
||||
logicalSlotId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
input: ProfileDownloadInput,
|
||||
autoConfirm: Boolean = true
|
||||
): EuiccChannelManagerService.ForegroundTaskHandle {
|
||||
service.waitForForegroundTask()
|
||||
|
||||
val (slotId, portId) = manager.withEuiccChannel(logicalSlotId, seId) { channel ->
|
||||
Pair(channel.slotId, channel.portId)
|
||||
}
|
||||
|
||||
val handle = service.launchProfileDownloadTask(slotId, portId, seId, input)
|
||||
|
||||
if (autoConfirm) {
|
||||
// TODO: Ask user to confirm metadata for real if we need it
|
||||
handle.backChannel.send(true)
|
||||
}
|
||||
|
||||
return handle
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
|
|||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import androidx.fragment.app.Fragment
|
||||
import im.angry.openeuicc.OpenEuiccApplication
|
||||
import im.angry.openeuicc.common.R
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import java.util.Base64
|
||||
|
|
@ -79,6 +80,9 @@ internal object PreferenceConstants {
|
|||
""".trimIndent()
|
||||
}
|
||||
|
||||
fun defaultEs10xMss(context: Context): Int =
|
||||
context.resources.getInteger(R.integer.config_es10x_mss_default)
|
||||
|
||||
open class PreferenceRepository(private val context: Context) {
|
||||
// Expose flows so that we can also handle default values
|
||||
// ---- Profile Notifications ----
|
||||
|
|
@ -101,7 +105,7 @@ open class PreferenceRepository(private val context: Context) {
|
|||
PreferenceConstants.DEFAULT_AID_LIST,
|
||||
{ Base64.getEncoder().encodeToString(it.encodeToByteArray()) },
|
||||
{ Base64.getDecoder().decode(it).decodeToString() })
|
||||
val es10xMssFlow = bindFlow(PreferenceKeys.ES10X_MSS, 63)
|
||||
val es10xMssFlow = bindFlow(PreferenceKeys.ES10X_MSS, defaultEs10xMss(context))
|
||||
val httpProxyFlow = bindFlow(PreferenceKeys.HTTP_PROXY, "")
|
||||
|
||||
protected fun <T> bindFlow(
|
||||
|
|
|
|||
9
app-common/src/main/res/values/config.xml
Normal file
9
app-common/src/main/res/values/config.xml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!--
|
||||
Default ES10x maximum segment size (MSS) when the user has not set
|
||||
pref_developer_es10x_mss. Device overlays may raise this (e.g. to 255)
|
||||
for eUICCs that mishandle small LoadBPP STORE DATA chains.
|
||||
-->
|
||||
<integer name="config_es10x_mss_default">63</integer>
|
||||
</resources>
|
||||
8
app-common/src/main/res/values/overlayable.xml
Normal file
8
app-common/src/main/res/values/overlayable.xml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<overlayable name="OpenEUICC">
|
||||
<policy type="system|product|vendor">
|
||||
<item type="integer" name="config_es10x_mss_default" />
|
||||
</policy>
|
||||
</overlayable>
|
||||
</resources>
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
package im.angry.openeuicc.common
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
package im.angry.openeuicc.service
|
||||
|
||||
import android.content.Intent
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService.ForegroundTaskState
|
||||
import im.angry.openeuicc.testutil.MockEuiccChannel
|
||||
import im.angry.openeuicc.testutil.MockEuiccChannelManager
|
||||
import im.angry.openeuicc.testutil.MockLpa
|
||||
import im.angry.openeuicc.testutil.TestOpenEuiccApplication
|
||||
import im.angry.openeuicc.testutil.awaitMainLooper
|
||||
import android.os.Looper
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* Tests the real EuiccChannelManagerService (Robolectric) with only the manager /
|
||||
* channel / LPA mocked -- i.e. the exact service that runs in production.
|
||||
*
|
||||
* These tests pin the profile-download confirmation contract that regressed
|
||||
* during the "merge back-communication channels" refactor: the task MUST block
|
||||
* at ProfileDownloadState.ConfirmingDownload until a Boolean is sent on the
|
||||
* handle's back channel. `true` continues the download, `false` cancels it.
|
||||
* UI callers are expected to send that signal through launchProfileDownload()
|
||||
* (see DownloadTaskLauncherTest).
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(application = TestOpenEuiccApplication::class)
|
||||
class EuiccChannelManagerServiceTest {
|
||||
|
||||
private val seId = EuiccChannel.SecureElementId.DEFAULT
|
||||
private val input = ProfileDownloadInput(
|
||||
address = "smdp.example.com",
|
||||
matchingId = "matching-id",
|
||||
imei = "imei",
|
||||
confirmationCode = "conf-code"
|
||||
)
|
||||
|
||||
private lateinit var service: EuiccChannelManagerService
|
||||
private lateinit var lpa: MockLpa
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val channel = MockEuiccChannel(slotId = 1, portId = 2)
|
||||
lpa = channel.lpa as MockLpa
|
||||
TestOpenEuiccApplication.mockEuiccChannelManager = MockEuiccChannelManager(channel)
|
||||
service = Robolectric.buildService(EuiccChannelManagerService::class.java).get()
|
||||
}
|
||||
|
||||
/**
|
||||
* The service self-starts via startForegroundService(); Robolectric does not
|
||||
* deliver that to onStartCommand() on its own, so simulate the system call.
|
||||
* Must be invoked after the launch coroutine has had a chance to subscribe to
|
||||
* foregroundStarted (otherwise the emission is dropped -- foregroundStarted
|
||||
* has no replay). In production the system delivers the start asynchronously,
|
||||
* so the subscriber is always ready by then.
|
||||
*/
|
||||
private fun startService() {
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
service.onStartCommand(Intent(), 0, 1)
|
||||
}
|
||||
|
||||
private suspend fun awaitTaskDone(
|
||||
handle: EuiccChannelManagerService.ForegroundTaskHandle
|
||||
): ForegroundTaskState.Done = coroutineScope {
|
||||
// Written by the collector on Dispatchers.Default while awaitMainLooper() reads it
|
||||
val states = java.util.concurrent.CopyOnWriteArrayList<ForegroundTaskState>()
|
||||
val collector = async(Dispatchers.Default) { handle.stateFlow.collect { states += it } }
|
||||
try {
|
||||
awaitMainLooper {
|
||||
states.any { it is ForegroundTaskState.Done }
|
||||
}
|
||||
} finally {
|
||||
collector.cancel()
|
||||
}
|
||||
states.last() as ForegroundTaskState.Done
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `download task blocks at ConfirmingDownload until the subscriber sends true`() = runBlocking {
|
||||
val handle = service.launchProfileDownloadTask(1, 2, seId, input)
|
||||
startService()
|
||||
|
||||
// The task must reach the LPA and stall at the confirmation step.
|
||||
awaitMainLooper { lpa.downloadStarted.isCompleted }
|
||||
assertFalse(
|
||||
"download must be waiting for confirmation",
|
||||
lpa.downloadReturned.isCompleted
|
||||
)
|
||||
|
||||
// A subscriber (e.g. DownloadWizardProgressFragment) confirms via the back channel.
|
||||
handle.backChannel.send(true)
|
||||
|
||||
// The LPA callback must have been told to continue.
|
||||
assertEquals(true, lpa.awaitDownloadResult())
|
||||
|
||||
// The task must then complete successfully.
|
||||
val done = awaitTaskDone(handle)
|
||||
assertNull(done.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `download task cancels when the subscriber sends false`() = runBlocking {
|
||||
val handle = service.launchProfileDownloadTask(1, 2, seId, input)
|
||||
startService()
|
||||
|
||||
awaitMainLooper { lpa.downloadStarted.isCompleted }
|
||||
assertFalse(
|
||||
"download must be waiting for confirmation",
|
||||
lpa.downloadReturned.isCompleted
|
||||
)
|
||||
|
||||
// A subscriber decides to cancel.
|
||||
handle.backChannel.send(false)
|
||||
|
||||
// The LPA callback must have been told to cancel.
|
||||
assertEquals(false, lpa.awaitDownloadResult())
|
||||
|
||||
// The task itself still completes (the cancellation is communicated via the
|
||||
// callback result, not an exception).
|
||||
val done = awaitTaskDone(handle)
|
||||
assertNull(done.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `download task cancels when no confirmation arrives within the timeout`() = runBlocking {
|
||||
val handle = service.launchProfileDownloadTask(
|
||||
1, 2, seId, input,
|
||||
confirmationTimeoutMillis = 100
|
||||
)
|
||||
startService()
|
||||
|
||||
awaitMainLooper { lpa.downloadStarted.isCompleted }
|
||||
|
||||
// Nothing is sent on the back channel.
|
||||
assertEquals(false, lpa.awaitDownloadResult())
|
||||
// A late confirmation is refused
|
||||
assertFalse(handle.backChannel.trySend(true).isSuccess)
|
||||
assertNull(awaitTaskDone(handle).error)
|
||||
}
|
||||
}
|
||||
209
app-common/src/test/java/im/angry/openeuicc/testutil/Mocks.kt
Normal file
209
app-common/src/test/java/im/angry/openeuicc/testutil/Mocks.kt
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
package im.angry.openeuicc.testutil
|
||||
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
import im.angry.openeuicc.core.EuiccChannelManager
|
||||
import im.angry.openeuicc.util.FakeUiccCardInfoCompat
|
||||
import im.angry.openeuicc.util.FakeUiccPortInfoCompat
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import net.typeblog.lpac_jni.ApduInterface
|
||||
import net.typeblog.lpac_jni.EuiccInfo2
|
||||
import net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
import net.typeblog.lpac_jni.LocalProfileInfo
|
||||
import net.typeblog.lpac_jni.LocalProfileNotification
|
||||
import net.typeblog.lpac_jni.ProfileDownloadCallback
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import net.typeblog.lpac_jni.ProfileDownloadState
|
||||
|
||||
/**
|
||||
* Mocks for the dependencies *below* EuiccChannelManagerService (manager →
|
||||
* channel → LPA), used by Robolectric tests that exercise the real service.
|
||||
*
|
||||
* The service itself is never mocked; tests build it with
|
||||
* Robolectric.buildService() and only swap out what the service talks to.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A LocalProfileAssistant whose downloadProfile() simulates a real download:
|
||||
* it reports the states in [preConfirmationStates] in order, then reports
|
||||
* ProfileDownloadState.ConfirmingDownload and blocks until the caller resolves
|
||||
* the confirmation (which, in production, the service does by waiting on the
|
||||
* task's back channel). The callback's return value is recorded so tests can
|
||||
* assert whether the download was confirmed or cancelled.
|
||||
*
|
||||
* By default (no pre-confirmation states) it jumps straight to
|
||||
* ConfirmingDownload, matching the historical behavior of this mock.
|
||||
*
|
||||
* Optional controls to simulate realistic downloads:
|
||||
* - [failAfter]: throw a ProfileDownloadException right after emitting this
|
||||
* state, simulating e.g. the SM-DP+ rejecting the device during
|
||||
* authentication (before any metadata confirmation happens).
|
||||
* - [holdAt]: park downloadProfile() (blocking the service's IO thread) after
|
||||
* emitting this state until [releaseHold] is called, so tests can inspect
|
||||
* the UI mid-download.
|
||||
*/
|
||||
class MockLpa(
|
||||
// Mutable so tests sharing a common setUp() can configure the mock right
|
||||
// before starting the download.
|
||||
var preConfirmationStates: List<ProfileDownloadState> = emptyList(),
|
||||
var failAfter: ProfileDownloadState? = null,
|
||||
var holdAt: ProfileDownloadState? = null,
|
||||
) : LocalProfileAssistant {
|
||||
/** Completes as soon as downloadProfile() is entered (task reached the LPA). */
|
||||
val downloadStarted = CompletableDeferred<Unit>()
|
||||
|
||||
/** Completes with the callback result once downloadProfile() returns. */
|
||||
val downloadReturned = CompletableDeferred<Boolean>()
|
||||
|
||||
/** The input passed to downloadProfile(). */
|
||||
var downloadInput: ProfileDownloadInput? = null
|
||||
|
||||
/** Completes once the given state class has been emitted to the callback. */
|
||||
private val stateReached = mutableMapOf<kotlin.reflect.KClass<out ProfileDownloadState>, CompletableDeferred<Unit>>()
|
||||
|
||||
/** Released by the test to let a download parked at [holdAt] continue. */
|
||||
private val holdRelease = CompletableDeferred<Unit>()
|
||||
|
||||
/** The exception thrown when [failAfter] is reached; mutable so tests can inject a realistic one. */
|
||||
var failure: LocalProfileAssistant.ProfileDownloadException = LocalProfileAssistant.ProfileDownloadException(
|
||||
lpaErrorReason = "ES10B_ERROR_REASON_UNDEFINED",
|
||||
lastHttpResponse = null,
|
||||
lastHttpException = null,
|
||||
lastApduResponse = null,
|
||||
lastApduException = null,
|
||||
)
|
||||
|
||||
override fun downloadProfile(input: ProfileDownloadInput, callback: ProfileDownloadCallback) {
|
||||
downloadInput = input
|
||||
downloadStarted.complete(Unit)
|
||||
for (state in preConfirmationStates) {
|
||||
// The callback is invoked first so that the service can record the
|
||||
// progress update before the mock advances or fails.
|
||||
callback.onStatusUpdate(state)
|
||||
stateReached.getOrPut(state::class) { CompletableDeferred() }.complete(Unit)
|
||||
// ProfileDownloadState subclasses are plain classes without equals(),
|
||||
// so compare by class, not by instance.
|
||||
if (failAfter != null && state::class == failAfter!!::class) {
|
||||
throw failure
|
||||
}
|
||||
if (holdAt != null && state::class == holdAt!!::class) {
|
||||
// Park the download here (on the service's IO thread) so the test
|
||||
// can inspect intermediate UI state; the test must call releaseHold().
|
||||
kotlinx.coroutines.runBlocking { holdRelease.await() }
|
||||
}
|
||||
}
|
||||
// This blocks the caller (the service's IO thread) until the back channel
|
||||
// receives a Boolean -- exactly like a real download reaching the
|
||||
// ConfirmingDownload step.
|
||||
val result = callback.onStatusUpdate(ProfileDownloadState.ConfirmingDownload(null))
|
||||
downloadReturned.complete(result)
|
||||
}
|
||||
|
||||
/** Whether the given state class has already been emitted by downloadProfile(). */
|
||||
fun isStateReached(state: ProfileDownloadState): Boolean =
|
||||
stateReached[state::class]?.isCompleted == true
|
||||
|
||||
/** Releases a download parked at [holdAt]. */
|
||||
fun releaseHold() {
|
||||
holdRelease.complete(Unit)
|
||||
}
|
||||
|
||||
suspend fun awaitDownloadResult(): Boolean = downloadReturned.await()
|
||||
|
||||
// ---- trivial implementations for the rest of the LPA surface ----
|
||||
override val valid = true
|
||||
override val profiles = emptyList<LocalProfileInfo>()
|
||||
override val notifications = emptyList<LocalProfileNotification>()
|
||||
override val eID = "mock-eid"
|
||||
override val euiccInfo2: EuiccInfo2? = null
|
||||
override fun setEs10xMss(mss: Byte) {}
|
||||
override fun enableProfile(iccid: String, refresh: Boolean): Boolean = true
|
||||
override fun disableProfile(iccid: String, refresh: Boolean): Boolean = true
|
||||
override fun deleteProfile(iccid: String): Boolean = true
|
||||
override fun deleteNotification(seqNumber: Long): Boolean = true
|
||||
override fun handleNotification(seqNumber: Long): Boolean = true
|
||||
override fun euiccMemoryReset() {}
|
||||
override fun setNickname(iccid: String, nickname: String) {}
|
||||
override fun close() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A EuiccChannel that always "finds" the given LPA and physical slot/port.
|
||||
*/
|
||||
class MockEuiccChannel(
|
||||
override val slotId: Int,
|
||||
override val portId: Int,
|
||||
override val lpa: LocalProfileAssistant = MockLpa()
|
||||
) : EuiccChannel {
|
||||
override val type = "mock"
|
||||
override val port = FakeUiccPortInfoCompat(FakeUiccCardInfoCompat(slotId))
|
||||
override val logicalSlotId = slotId
|
||||
override val seId = EuiccChannel.SecureElementId.DEFAULT
|
||||
override var hasMultipleSE = false
|
||||
override val valid = true
|
||||
override val atr: ByteArray? = null
|
||||
|
||||
override val apduInterface = object : ApduInterface {
|
||||
override fun connect() {}
|
||||
override fun disconnect() {}
|
||||
override fun logicalChannelOpen(aid: ByteArray): Int = 1
|
||||
override fun logicalChannelClose(handle: Int) {}
|
||||
override fun transmit(handle: Int, tx: ByteArray): ByteArray = ByteArray(0)
|
||||
override val valid = true
|
||||
}
|
||||
|
||||
override val isdrAid = ByteArray(0)
|
||||
override fun close() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A EuiccChannelManager that hands out the same [channel] for every request and
|
||||
* records how it was asked to resolve channels (slot/port pairs).
|
||||
*/
|
||||
class MockEuiccChannelManager(val channel: EuiccChannel) : EuiccChannelManager {
|
||||
/** Every withEuiccChannel(physical slot/port) request, in order. */
|
||||
val physicalChannelRequests = mutableListOf<Pair<Int, Int>>()
|
||||
|
||||
/** Every withEuiccChannel(logical slot) request, in order. */
|
||||
val logicalChannelRequests = mutableListOf<Int>()
|
||||
|
||||
override fun flowInternalEuiccPorts(): Flow<Pair<Int, Int>> =
|
||||
flowOf(Pair(channel.slotId, channel.portId))
|
||||
|
||||
override fun flowAllOpenEuiccPorts(): Flow<Pair<Int, Int>> =
|
||||
flowOf(Pair(channel.slotId, channel.portId))
|
||||
|
||||
override fun flowEuiccSecureElements(slotId: Int, portId: Int): Flow<EuiccChannel.SecureElementId> =
|
||||
flowOf(channel.seId)
|
||||
|
||||
override suspend fun tryOpenUsbEuiccChannel(): Pair<android.hardware.usb.UsbDevice?, Boolean> =
|
||||
null to true
|
||||
|
||||
override suspend fun waitForReconnect(physicalSlotId: Int, portId: Int, timeoutMillis: Long) {}
|
||||
|
||||
override suspend fun findFirstAvailablePort(physicalSlotId: Int): Int = channel.portId
|
||||
|
||||
override suspend fun findAvailablePorts(physicalSlotId: Int): List<Int> = listOf(channel.portId)
|
||||
|
||||
override suspend fun <R> withEuiccChannel(
|
||||
physicalSlotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
fn: suspend (EuiccChannel) -> R
|
||||
): R {
|
||||
physicalChannelRequests += physicalSlotId to portId
|
||||
return fn(channel)
|
||||
}
|
||||
|
||||
override suspend fun <R> withEuiccChannel(
|
||||
logicalSlotId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
fn: suspend (EuiccChannel) -> R
|
||||
): R {
|
||||
logicalChannelRequests += logicalSlotId
|
||||
return fn(channel)
|
||||
}
|
||||
|
||||
override fun invalidate() {}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package im.angry.openeuicc.testutil
|
||||
|
||||
import android.os.Looper
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import kotlinx.coroutines.yield
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
/**
|
||||
* The service runs its foreground-task machinery on Dispatchers.Main (the
|
||||
* Robolectric main looper), which is paused by default. Tests must pump the
|
||||
* looper while they wait for service-side effects; this helper idles the main
|
||||
* looper until [condition] becomes true (or [timeoutMillis] elapses).
|
||||
*/
|
||||
suspend fun awaitMainLooper(
|
||||
timeoutMillis: Long = 10_000,
|
||||
condition: () -> Boolean
|
||||
) {
|
||||
withTimeout(timeoutMillis.milliseconds) {
|
||||
while (!condition()) {
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
yield()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
package im.angry.openeuicc.testutil
|
||||
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import im.angry.openeuicc.OpenEuiccApplication
|
||||
import im.angry.openeuicc.core.EuiccChannelManager
|
||||
import im.angry.openeuicc.core.EuiccChannelManagerFactory
|
||||
import im.angry.openeuicc.di.AppContainer
|
||||
import im.angry.openeuicc.di.DefaultAppContainer
|
||||
import im.angry.openeuicc.util.PreferenceRepository
|
||||
|
||||
/**
|
||||
* Application used by Robolectric tests: swaps the app container's
|
||||
* EuiccChannelManagerFactory so that the *real* EuiccChannelManagerService
|
||||
* receives a mock EuiccChannelManager (and LPA) when it asks for one.
|
||||
*
|
||||
* The mock must be installed before the service is built:
|
||||
* `TestOpenEuiccApplication.mockEuiccChannelManager = ...`
|
||||
*/
|
||||
class TestOpenEuiccApplication : OpenEuiccApplication() {
|
||||
companion object {
|
||||
lateinit var mockEuiccChannelManager: EuiccChannelManager
|
||||
}
|
||||
|
||||
override val appContainer: AppContainer by lazy {
|
||||
TestAppContainer(this, mockEuiccChannelManager)
|
||||
}
|
||||
}
|
||||
|
||||
class TestAppContainer(
|
||||
context: Context,
|
||||
private val mockEuiccChannelManager: EuiccChannelManager
|
||||
) : DefaultAppContainer(context) {
|
||||
override val euiccChannelManagerFactory: EuiccChannelManagerFactory =
|
||||
object : EuiccChannelManagerFactory {
|
||||
override fun createEuiccChannelManager(serviceContext: Service): EuiccChannelManager =
|
||||
mockEuiccChannelManager
|
||||
}
|
||||
|
||||
// Real PreferenceRepository (DataStore-backed) is fine: it returns defaults.
|
||||
override val preferenceRepository: PreferenceRepository =
|
||||
PreferenceRepository(context)
|
||||
}
|
||||
|
|
@ -0,0 +1,220 @@
|
|||
package im.angry.openeuicc.ui.wizard
|
||||
|
||||
import android.content.Intent
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService
|
||||
import im.angry.openeuicc.testutil.MockEuiccChannel
|
||||
import im.angry.openeuicc.testutil.MockEuiccChannelManager
|
||||
import im.angry.openeuicc.testutil.MockLpa
|
||||
import im.angry.openeuicc.testutil.TestOpenEuiccApplication
|
||||
import im.angry.openeuicc.testutil.awaitMainLooper
|
||||
import android.os.Looper
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.yield
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import net.typeblog.lpac_jni.ProfileDownloadState
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
/**
|
||||
* Tests launchProfileDownload(), the freestanding implementation of the
|
||||
* UI → service contract for profile download, against the REAL
|
||||
* EuiccChannelManagerService (built with Robolectric). Only the manager /
|
||||
* channel / LPA below the service are mocked (see testutil.Mocks).
|
||||
*
|
||||
* DownloadWizardProgressFragment MUST call launchProfileDownload() and not
|
||||
* re-implement the launch + auto-confirmation inline; the tests here only
|
||||
* protect code that actually runs in production. If you change the behavior
|
||||
* verified in this file, update the fragment at the same time.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(application = TestOpenEuiccApplication::class)
|
||||
class DownloadTaskLauncherTest {
|
||||
|
||||
private val seId = EuiccChannel.SecureElementId.DEFAULT
|
||||
private val input = ProfileDownloadInput(
|
||||
address = "smdp.example.com",
|
||||
matchingId = "matching-id",
|
||||
imei = "imei",
|
||||
confirmationCode = "conf-code"
|
||||
)
|
||||
|
||||
private lateinit var service: EuiccChannelManagerService
|
||||
private lateinit var channel: MockEuiccChannel
|
||||
private lateinit var manager: MockEuiccChannelManager
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
channel = MockEuiccChannel(slotId = 1, portId = 2)
|
||||
manager = MockEuiccChannelManager(channel)
|
||||
TestOpenEuiccApplication.mockEuiccChannelManager = manager
|
||||
service = Robolectric.buildService(EuiccChannelManagerService::class.java).get()
|
||||
}
|
||||
|
||||
/**
|
||||
* The service self-starts via startForegroundService(); Robolectric does not
|
||||
* deliver that to onStartCommand() on its own, so simulate the system call.
|
||||
* Must be invoked after the launch coroutine has had a chance to subscribe to
|
||||
* foregroundStarted (otherwise the emission is dropped -- foregroundStarted
|
||||
* has no replay). In production the system delivers the start asynchronously,
|
||||
* so the subscriber is always ready by then.
|
||||
*
|
||||
* When launchProfileDownload is running inside an `async` coroutine, we must
|
||||
* first yield() so it can call launchProfileDownloadTask() and park at
|
||||
* backChannel.send(true); only then does the service's launch coroutine exist
|
||||
* and subscribe to foregroundStarted.
|
||||
*/
|
||||
private suspend fun startService() {
|
||||
yield()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
service.onStartCommand(Intent(), 0, 1)
|
||||
}
|
||||
|
||||
private suspend fun awaitTaskDone(
|
||||
handle: EuiccChannelManagerService.ForegroundTaskHandle
|
||||
): EuiccChannelManagerService.ForegroundTaskState.Done = coroutineScope {
|
||||
// Collect on the test thread (inherited from runBlocking): flow emissions always
|
||||
// run the collect body on this coroutine's dispatcher, so adds happen on the same
|
||||
// thread that awaitMainLooper reads from -- no concurrent access, plain list is safe.
|
||||
val states = mutableListOf<EuiccChannelManagerService.ForegroundTaskState>()
|
||||
val collector = async { handle.stateFlow.collect { states += it } }
|
||||
try {
|
||||
awaitMainLooper {
|
||||
states.any { it is EuiccChannelManagerService.ForegroundTaskState.Done }
|
||||
}
|
||||
} finally {
|
||||
collector.cancel()
|
||||
}
|
||||
states.last() as EuiccChannelManagerService.ForegroundTaskState.Done
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `launchProfileDownload launches through the real service and auto-confirms`() = runBlocking {
|
||||
val lpa = channel.lpa as MockLpa
|
||||
|
||||
// launchProfileDownload returns immediately: the back channel is buffered,
|
||||
// so the auto-confirmation does not block the caller (the download itself
|
||||
// only starts after the start command is delivered below).
|
||||
val handle = withTimeout(10_000.milliseconds) {
|
||||
val deferred = async { launchProfileDownload(service, manager, logicalSlotId = 0, seId, input) }
|
||||
// Deliver the start command so the service machinery can run.
|
||||
startService()
|
||||
awaitMainLooper { deferred.isCompleted }
|
||||
deferred.await()
|
||||
}
|
||||
|
||||
// Wait until the download has actually reached the LPA before asserting
|
||||
// what the service did with it.
|
||||
awaitMainLooper { lpa.downloadStarted.isCompleted }
|
||||
|
||||
// The service must have been asked to download with the physical slot/port
|
||||
// resolved through the manager (1, 2) and the exact input the UI passed.
|
||||
assertEquals(1 to 2, manager.physicalChannelRequests.first())
|
||||
assertEquals(input, lpa.downloadInput)
|
||||
|
||||
// The critical part that regressed once: the UI MUST send a confirmation on
|
||||
// the back channel; otherwise the download stalls and then cancels. Here the
|
||||
// LPA's callback must have seen `true`.
|
||||
assertEquals(true, lpa.awaitDownloadResult())
|
||||
|
||||
// The task must have completed with no error.
|
||||
val done = awaitTaskDone(handle)
|
||||
assertNull(done.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `autoConfirm=false leaves confirmation to the UI`() = runBlocking {
|
||||
val lpa = channel.lpa as MockLpa
|
||||
|
||||
val handle = launchProfileDownload(
|
||||
service, manager, logicalSlotId = 0, seId, input, autoConfirm = false
|
||||
)
|
||||
startService()
|
||||
|
||||
// The download must reach the LPA and stall at the confirmation step...
|
||||
awaitMainLooper { lpa.downloadStarted.isCompleted }
|
||||
assertFalse(
|
||||
"download must not complete before a manual confirmation",
|
||||
lpa.downloadReturned.isCompleted
|
||||
)
|
||||
|
||||
// ...until the UI confirms through the back channel itself.
|
||||
handle.backChannel.send(true)
|
||||
|
||||
assertEquals(true, lpa.awaitDownloadResult())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `launchProfileDownload returns before the confirmation step so the caller can observe progress`() =
|
||||
runBlocking {
|
||||
// Simulate a download that emits an intermediate state (Preparing)
|
||||
// before ConfirmingDownload and parks there until the test releases it.
|
||||
val lpa = MockLpa(
|
||||
preConfirmationStates = listOf(ProfileDownloadState.Preparing()),
|
||||
holdAt = ProfileDownloadState.Preparing(),
|
||||
)
|
||||
channel = MockEuiccChannel(slotId = 1, portId = 2, lpa = lpa)
|
||||
manager = MockEuiccChannelManager(channel)
|
||||
TestOpenEuiccApplication.mockEuiccChannelManager = manager
|
||||
service = Robolectric.buildService(EuiccChannelManagerService::class.java).get()
|
||||
|
||||
val deferred = async { launchProfileDownload(service, manager, logicalSlotId = 0, seId, input) }
|
||||
startService()
|
||||
|
||||
// The download is now parked at Preparing (before ConfirmingDownload).
|
||||
awaitMainLooper { lpa.isStateReached(ProfileDownloadState.Preparing()) }
|
||||
|
||||
// launchProfileDownload must NOT be blocked on the auto-confirmation
|
||||
// back channel: the caller has to be able to subscribe to progress
|
||||
// while the download is still in its early steps. Otherwise the UI
|
||||
// misses every intermediate state (and dies without showing anything
|
||||
// if the download fails before ConfirmingDownload).
|
||||
assertTrue(
|
||||
"launchProfileDownload must return while the download is still at Preparing",
|
||||
deferred.isCompleted
|
||||
)
|
||||
val handle = deferred.await()
|
||||
|
||||
// The caller must be able to observe the intermediate progress state
|
||||
// that was emitted before ConfirmingDownload. Collect on the test
|
||||
// thread (inherited from runBlocking) so the list is never mutated
|
||||
// concurrently, like in awaitTaskDone().
|
||||
val states = mutableListOf<EuiccChannelManagerService.ForegroundTaskState>()
|
||||
val collector = async {
|
||||
handle.stateFlow.collect { states += it }
|
||||
}
|
||||
try {
|
||||
withTimeout(10_000.milliseconds) {
|
||||
while (states.none {
|
||||
it is EuiccChannelManagerService.ForegroundTaskState.InProgress &&
|
||||
it.context is ProfileDownloadState.Preparing
|
||||
}) {
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
yield()
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
collector.cancel()
|
||||
}
|
||||
|
||||
// Let the download finish; the auto-confirmation already sent by
|
||||
// launchProfileDownload must continue it normally.
|
||||
lpa.releaseHold()
|
||||
val done = awaitTaskDone(handle)
|
||||
assertNull(done.error)
|
||||
assertEquals(true, lpa.awaitDownloadResult())
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,347 @@
|
|||
package im.angry.openeuicc.ui.wizard
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Intent
|
||||
import android.os.Looper
|
||||
import android.view.View
|
||||
import android.widget.Button
|
||||
import android.widget.ImageView
|
||||
import android.widget.ProgressBar
|
||||
import android.widget.TextView
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.google.android.material.textfield.TextInputLayout
|
||||
import im.angry.openeuicc.common.R
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService
|
||||
import im.angry.openeuicc.testutil.MockEuiccChannel
|
||||
import im.angry.openeuicc.testutil.MockEuiccChannelManager
|
||||
import im.angry.openeuicc.testutil.MockLpa
|
||||
import im.angry.openeuicc.testutil.TestOpenEuiccApplication
|
||||
import im.angry.openeuicc.testutil.awaitMainLooper
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import net.typeblog.lpac_jni.ProfileDownloadState
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* A Robolectric UI test that drives the REAL DownloadWizardActivity through the
|
||||
* whole wizard flow -- slot select -> method select -> details -> download
|
||||
* progress -- until the download completes.
|
||||
*
|
||||
* Only the dependencies *below* EuiccChannelManagerService are mocked (manager ->
|
||||
* channel -> LPA, see testutil.Mocks). The activity, every wizard fragment, the
|
||||
* in-process service binding and the entire foreground-task machinery are the
|
||||
* real production code, so this test protects the actual UI flow that a user
|
||||
* experiences, not just the launchProfileDownload() contract in isolation.
|
||||
*
|
||||
* The MockLpa simulates a download that reaches ProfileDownloadState.ConfirmingDownload
|
||||
* and blocks until the subscriber confirms through the task's back channel --
|
||||
* exactly what a real download does before finishing.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(application = TestOpenEuiccApplication::class)
|
||||
class DownloadWizardFlowTest {
|
||||
|
||||
private val input = ProfileDownloadInput(
|
||||
address = "smdp.example.com",
|
||||
matchingId = "matching-id",
|
||||
imei = "imei",
|
||||
confirmationCode = "conf-code"
|
||||
)
|
||||
|
||||
private lateinit var activity: DownloadWizardActivity
|
||||
private lateinit var service: EuiccChannelManagerService
|
||||
private lateinit var channel: MockEuiccChannel
|
||||
private lateinit var manager: MockEuiccChannelManager
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
channel = MockEuiccChannel(slotId = 1, portId = 2)
|
||||
manager = MockEuiccChannelManager(channel)
|
||||
TestOpenEuiccApplication.mockEuiccChannelManager = manager
|
||||
|
||||
// Robolectric does not auto-create services on bindService(); register the
|
||||
// REAL EuiccChannelManagerService (with the mock manager below it) as the
|
||||
// binding target so that BaseEuiccAccessActivity connects to it in-process.
|
||||
service = Robolectric.buildService(EuiccChannelManagerService::class.java).get()
|
||||
val bindIntent = Intent(
|
||||
RuntimeEnvironment.getApplication(),
|
||||
EuiccChannelManagerService::class.java
|
||||
)
|
||||
shadowOf(RuntimeEnvironment.getApplication())
|
||||
.setComponentNameAndServiceForBindServiceForIntent(
|
||||
bindIntent,
|
||||
ComponentName(
|
||||
RuntimeEnvironment.getApplication(),
|
||||
EuiccChannelManagerService::class.java
|
||||
),
|
||||
service.onBind(Intent())
|
||||
)
|
||||
|
||||
val intent = DownloadWizardActivity.newIntent(
|
||||
RuntimeEnvironment.getApplication(),
|
||||
logicalSlotId = 0
|
||||
)
|
||||
val controller = Robolectric.buildActivity(DownloadWizardActivity::class.java, intent)
|
||||
// The activity does not declare a theme itself; it inherits the host
|
||||
// app's application-level theme (Theme.OpenEUICC), which Robolectric
|
||||
// does not merge in for a library module. AppCompatActivity requires an
|
||||
// AppCompat theme, so apply it before onCreate() runs.
|
||||
controller.get().setTheme(R.style.Theme_OpenEUICC)
|
||||
activity = controller.setup().get()
|
||||
idle()
|
||||
|
||||
// Wait until the in-process service connection is up and onInit() has run.
|
||||
runBlocking {
|
||||
awaitMainLooper { activity.euiccChannelManagerLoaded.isCompleted }
|
||||
}
|
||||
idle()
|
||||
}
|
||||
|
||||
private fun idle() {
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
}
|
||||
|
||||
private fun currentFragment(): DownloadWizardActivity.DownloadWizardStepFragment? =
|
||||
activity.supportFragmentManager
|
||||
.findFragmentById(R.id.step_fragment_container)
|
||||
as? DownloadWizardActivity.DownloadWizardStepFragment
|
||||
|
||||
/**
|
||||
* RecyclerView children are only laid out when the Robolectric main looper
|
||||
* runs the view traversal; if that hasn't happened yet, force a layout so
|
||||
* that findViewHolderForAdapterPosition() works.
|
||||
*/
|
||||
private fun RecyclerView.ensureLaidOut() {
|
||||
idle()
|
||||
if (childCount == 0) {
|
||||
measure(
|
||||
View.MeasureSpec.makeMeasureSpec(1080, View.MeasureSpec.EXACTLY),
|
||||
View.MeasureSpec.makeMeasureSpec(1920, View.MeasureSpec.EXACTLY)
|
||||
)
|
||||
layout(0, 0, 1080, 1920)
|
||||
idle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun clickListItem(recyclerView: RecyclerView, position: Int) {
|
||||
recyclerView.ensureLaidOut()
|
||||
val holder = recyclerView.findViewHolderForAdapterPosition(position)
|
||||
assertNotNull("list item $position should be visible", holder)
|
||||
holder!!.itemView.performClick()
|
||||
idle()
|
||||
}
|
||||
|
||||
private fun clickNext() {
|
||||
activity.findViewById<Button>(R.id.download_wizard_next).performClick()
|
||||
idle()
|
||||
}
|
||||
|
||||
/**
|
||||
* Drive the wizard through slot select -> method select -> details form ->
|
||||
* download progress, and kick the service's foreground task machinery by
|
||||
* simulating the start command (Robolectric does not deliver
|
||||
* startForegroundService() on its own).
|
||||
*/
|
||||
private suspend fun startDownload() {
|
||||
// ---- Slot select: the mock manager exposes exactly one eUICC ----
|
||||
val slotList = activity.findViewById<RecyclerView>(R.id.download_slot_list)
|
||||
awaitMainLooper { (slotList.adapter?.itemCount ?: 0) > 0 }
|
||||
assertEquals(1, slotList.adapter?.itemCount)
|
||||
clickListItem(slotList, 0)
|
||||
|
||||
// ---- Next -> method select ----
|
||||
clickNext()
|
||||
assertTrue(currentFragment() is DownloadWizardMethodSelectFragment)
|
||||
|
||||
// ---- Pick the manual entry -> details form ----
|
||||
val methodList = activity.findViewById<RecyclerView>(R.id.download_method_list)
|
||||
awaitMainLooper { (methodList.adapter?.itemCount ?: 0) == 4 }
|
||||
clickListItem(methodList, 3) // download_wizard_method_manual
|
||||
assertTrue(currentFragment() is DownloadWizardDetailsFragment)
|
||||
|
||||
// ---- Fill the form exactly as the user would ----
|
||||
val fields = mapOf(
|
||||
R.id.profile_download_server to input.address,
|
||||
R.id.profile_download_code to input.matchingId!!,
|
||||
R.id.profile_download_confirmation_code to input.confirmationCode!!,
|
||||
R.id.profile_download_imei to input.imei!!
|
||||
)
|
||||
fields.forEach { (id, text) ->
|
||||
activity.findViewById<TextInputLayout>(id).editText!!.setText(text)
|
||||
}
|
||||
idle()
|
||||
|
||||
// ---- Next -> download progress; the download launches via the REAL service ----
|
||||
clickNext()
|
||||
assertTrue(currentFragment() is DownloadWizardProgressFragment)
|
||||
|
||||
// The service self-starts via startForegroundService(); Robolectric does
|
||||
// not deliver that to onStartCommand() on its own (see
|
||||
// DownloadTaskLauncherTest), so simulate the system call once the task
|
||||
// has had a chance to subscribe to foregroundStarted. The mock manager
|
||||
// having resolved the logical slot proves the launch has been reached.
|
||||
awaitMainLooper { manager.logicalChannelRequests.isNotEmpty() }
|
||||
idle()
|
||||
service.onStartCommand(Intent(), 0, 1)
|
||||
idle()
|
||||
}
|
||||
|
||||
private fun progressItemHolder(position: Int): RecyclerView.ViewHolder {
|
||||
val progressList = activity.findViewById<RecyclerView>(R.id.download_progress_list)
|
||||
progressList.ensureLaidOut()
|
||||
val holder = progressList.findViewHolderForAdapterPosition(position)
|
||||
assertNotNull("progress item $position should be visible", holder)
|
||||
return holder!!
|
||||
}
|
||||
|
||||
/** Asserts that the given progress step currently shows a checkmark and no error text. */
|
||||
private fun assertProgressItemDone(position: Int) {
|
||||
val holder = progressItemHolder(position)
|
||||
val icon = holder.itemView.findViewById<ImageView>(R.id.download_progress_icon)
|
||||
val errorTitle = holder.itemView.findViewById<TextView>(R.id.download_progress_item_error_title)
|
||||
assertEquals("step $position should show a checkmark", View.VISIBLE, icon.visibility)
|
||||
assertEquals("step $position should not show an error", View.GONE, errorTitle.visibility)
|
||||
}
|
||||
|
||||
/** Asserts that the given progress step currently shows the indeterminate spinner. */
|
||||
private fun assertProgressItemInProgress(position: Int) {
|
||||
val holder = progressItemHolder(position)
|
||||
val progressBar =
|
||||
holder.itemView.findViewById<ProgressBar>(R.id.download_progress_icon_progress)
|
||||
assertEquals("step $position should show the progress spinner", View.VISIBLE, progressBar.visibility)
|
||||
}
|
||||
|
||||
/** Asserts that the given progress step currently shows the error state. */
|
||||
private fun assertProgressItemError(position: Int) {
|
||||
val holder = progressItemHolder(position)
|
||||
val errorTitle = holder.itemView.findViewById<TextView>(R.id.download_progress_item_error_title)
|
||||
assertEquals("step $position should show the error message", View.VISIBLE, errorTitle.visibility)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wizard runs the full flow through the real service to a completed download`() = runBlocking {
|
||||
val lpa = channel.lpa as MockLpa
|
||||
|
||||
startDownload()
|
||||
|
||||
// ---- The download must complete and the UI must reflect it ----
|
||||
awaitMainLooper { lpa.downloadReturned.isCompleted }
|
||||
awaitMainLooper { currentFragment()?.hasNext == true }
|
||||
|
||||
// The LPA received the exact input the UI passed, and the metadata
|
||||
// confirmation was auto-approved through the back channel.
|
||||
assertEquals(input, lpa.downloadInput)
|
||||
assertEquals(true, lpa.awaitDownloadResult())
|
||||
|
||||
// The service resolved the physical slot/port through the manager and
|
||||
// launched the download with them.
|
||||
assertEquals(1 to 2, manager.physicalChannelRequests.first())
|
||||
|
||||
// UI: every step the download reached shows a checkmark; nothing is stuck
|
||||
// in progress; the wizard offers to continue (i.e. no error).
|
||||
for (i in 0..2) {
|
||||
assertProgressItemDone(i)
|
||||
}
|
||||
// hasNext is true and no error -> the Next button must be visible so the
|
||||
// user can leave the (successful) download screen.
|
||||
assertEquals(
|
||||
View.VISIBLE,
|
||||
activity.findViewById<Button>(R.id.download_wizard_next).visibility
|
||||
)
|
||||
|
||||
// Clicking Next after a successful download must finish the wizard
|
||||
// (createNextFragment() returns null when there is no error).
|
||||
clickNext()
|
||||
assertTrue("wizard should finish after a successful download", activity.isFinishing)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wizard streams intermediate progress while the download is still running`() = runBlocking {
|
||||
val lpa = channel.lpa as MockLpa
|
||||
// Simulate a real download that walks through Preparing, Connecting and
|
||||
// Authenticating before asking for metadata confirmation, and park it at
|
||||
// Authenticating so we can inspect the UI mid-download.
|
||||
lpa.preConfirmationStates = listOf(
|
||||
ProfileDownloadState.Preparing(),
|
||||
ProfileDownloadState.Connecting(),
|
||||
ProfileDownloadState.Authenticating(),
|
||||
)
|
||||
lpa.holdAt = ProfileDownloadState.Authenticating()
|
||||
|
||||
startDownload()
|
||||
|
||||
// Wait until the download has actually reached (and is parked at) the
|
||||
// authentication step.
|
||||
awaitMainLooper { lpa.isStateReached(ProfileDownloadState.Authenticating()) }
|
||||
|
||||
// The UI must have streamed the progress live: the earlier steps already
|
||||
// show checkmarks and the current step shows the spinner -- it must NOT
|
||||
// jump straight from "nothing" to "done" at the end.
|
||||
assertProgressItemDone(0)
|
||||
assertProgressItemDone(1)
|
||||
assertProgressItemInProgress(2)
|
||||
|
||||
// Let the download continue; it must complete normally afterwards.
|
||||
lpa.releaseHold()
|
||||
awaitMainLooper { lpa.downloadReturned.isCompleted }
|
||||
awaitMainLooper { currentFragment()?.hasNext == true }
|
||||
assertEquals(true, lpa.awaitDownloadResult())
|
||||
// The steps reached before the confirmation are all done; the download
|
||||
// finishes without leaving anything stuck in progress.
|
||||
for (i in 0..2) {
|
||||
assertProgressItemDone(i)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wizard shows the reached steps and an error when the download fails before confirmation`() = runBlocking {
|
||||
val lpa = channel.lpa as MockLpa
|
||||
// The SM-DP+ rejects the device during authentication (step 3), i.e.
|
||||
// before any metadata confirmation happens -- this is the failure mode
|
||||
// that used to leave the progress UI stuck with no checkmarks at all.
|
||||
lpa.preConfirmationStates = listOf(
|
||||
ProfileDownloadState.Preparing(),
|
||||
ProfileDownloadState.Connecting(),
|
||||
ProfileDownloadState.Authenticating(),
|
||||
)
|
||||
lpa.failAfter = ProfileDownloadState.Authenticating()
|
||||
lpa.failure = LocalProfileAssistant.ProfileDownloadException(
|
||||
lpaErrorReason = "ES10B_ERROR_REASON_UNSUPPORTED_CRT_VALUES",
|
||||
lastHttpResponse = null,
|
||||
lastHttpException = null,
|
||||
lastApduResponse = null,
|
||||
lastApduException = null,
|
||||
)
|
||||
|
||||
startDownload()
|
||||
|
||||
// The download must fail and the wizard must then offer the diagnostics step.
|
||||
awaitMainLooper { currentFragment()?.hasNext == true }
|
||||
|
||||
// The steps reached before the failure must be marked done...
|
||||
assertProgressItemDone(0)
|
||||
assertProgressItemDone(1)
|
||||
// ...and the failing step must show the error.
|
||||
assertProgressItemError(2)
|
||||
|
||||
// The error must have been recorded so the diagnostics step can show it:
|
||||
// Next must lead to the diagnostics fragment (only created when an error
|
||||
// is present).
|
||||
clickNext()
|
||||
assertTrue(
|
||||
"next must lead to the diagnostics step after a failed download",
|
||||
currentFragment() is DownloadWizardDiagnosticsFragment
|
||||
)
|
||||
}
|
||||
}
|
||||
4
app-common/src/test/resources/robolectric.properties
Normal file
4
app-common/src/test/resources/robolectric.properties
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
# Pin the SDK level used by Robolectric tests in this module.
|
||||
# The current behavior would otherwise default to minSdk (28), but an explicit
|
||||
# setting keeps CI deterministic across Robolectric upgrades.
|
||||
sdk=28
|
||||
|
|
@ -52,4 +52,5 @@ kotlin {
|
|||
|
||||
dependencies {
|
||||
implementation(project(":app-common"))
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ android {
|
|||
|
||||
defaultConfig {
|
||||
applicationId = "im.angry.openeuicc"
|
||||
minSdk = 30
|
||||
minSdk = 31
|
||||
targetSdk = 37
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
|
@ -35,6 +35,18 @@ android {
|
|||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
}
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests {
|
||||
// Robolectric needs real resources (task titles, dialog themes)
|
||||
isIncludeAndroidResources = true
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
// Reuse app-common's Robolectric mocks (EuiccChannel / EuiccChannelManager / test application)
|
||||
getByName("test").java.srcDir("../app-common/src/test/java/im/angry/openeuicc/testutil")
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
|
|
@ -48,9 +60,15 @@ dependencies {
|
|||
implementation(project(":libs:hidden-apis-shim"))
|
||||
implementation(project(":libs:lpac-jni"))
|
||||
implementation(project(":app-common"))
|
||||
// This is a massiave hack. We need testImplementation because the test classes
|
||||
// need to be loadable against only public android.jar. However, once Robolectic
|
||||
// starts running tests, the real classes from android-all.jar take precedence.
|
||||
// FIXME: Probably make it so that this is not utterly fragile...
|
||||
testImplementation(project(":libs:hidden-apis-stub"))
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.5")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
|
||||
testImplementation("org.robolectric:robolectric:4.17-beta-4")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
}
|
||||
|
||||
val modulePropsTemplate = mutableMapOf(
|
||||
|
|
|
|||
|
|
@ -56,6 +56,27 @@
|
|||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!--
|
||||
LUI resolution activity, started by com.android.phone's
|
||||
EuiccResolutionUiDispatcherActivity. Like all LUI components, it must require
|
||||
BIND_EUICC_SERVICE and declare a non-zero priority (EuiccConnector.findBestActivity).
|
||||
-->
|
||||
<activity
|
||||
android:name=".ui.EuiccResolutionActivity"
|
||||
android:excludeFromRecents="true"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.BIND_EUICC_SERVICE"
|
||||
android:theme="@style/Theme.App.DeepLinkTransparent">
|
||||
<intent-filter android:priority="100">
|
||||
<action android:name="android.service.euicc.action.RESOLVE_NO_PRIVILEGES" />
|
||||
<action android:name="android.service.euicc.action.RESOLVE_DEACTIVATE_SIM" />
|
||||
<action android:name="android.service.euicc.action.RESOLVE_RESOLVABLE_ERRORS" />
|
||||
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.service.euicc.category.EUICC_UI" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
|
||||
android:enabled="false"
|
||||
|
|
|
|||
|
|
@ -2,11 +2,15 @@ package im.angry.openeuicc.service
|
|||
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.service.euicc.DownloadSubscriptionResult
|
||||
import android.service.euicc.EuiccProfileInfo
|
||||
import android.service.euicc.EuiccService
|
||||
import android.service.euicc.GetDefaultDownloadableSubscriptionListResult
|
||||
import android.service.euicc.GetDownloadableSubscriptionMetadataResult
|
||||
import android.service.euicc.GetEuiccProfileInfoListResult
|
||||
import android.telephony.TelephonyManager
|
||||
import android.telephony.UiccAccessRule
|
||||
import android.telephony.UiccSlotMapping
|
||||
import android.telephony.euicc.DownloadableSubscription
|
||||
import android.telephony.euicc.EuiccInfo
|
||||
|
|
@ -14,18 +18,62 @@ import android.util.Log
|
|||
import im.angry.openeuicc.core.EuiccChannel
|
||||
import im.angry.openeuicc.core.EuiccChannelManager
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService.ForegroundTaskHandle
|
||||
import im.angry.openeuicc.service.EuiccChannelManagerService.ForegroundTaskState
|
||||
import im.angry.openeuicc.util.*
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import net.typeblog.lpac_jni.LocalProfileInfo
|
||||
import net.typeblog.lpac_jni.ProfileClass
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import net.typeblog.lpac_jni.ProfileDownloadState
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
|
||||
companion object {
|
||||
const val TAG = "OpenEuiccService"
|
||||
|
||||
/**
|
||||
* The profile download that OpenEuiccService left waiting for confirmation in
|
||||
* EuiccChannelManagerService, if any, together with the activation code it was started
|
||||
* for. See pendingDownloadTask.
|
||||
*/
|
||||
@Volatile
|
||||
private var pendingDownload: PendingDownload? = null
|
||||
|
||||
/**
|
||||
* This lock is used in withEuiccManager() to serialize access to EuiccManager in this class.
|
||||
* See that method for details.
|
||||
*/
|
||||
private val euiccLock = Mutex()
|
||||
|
||||
/**
|
||||
* Cancel the download left waiting for confirmation, if there is one.
|
||||
*
|
||||
* It is assumed that the pending download is the one just declined; the platform is
|
||||
* unlikely to have started another order this quickly.
|
||||
*/
|
||||
suspend fun cancelPendingDownload(euiccChannelManagerService: EuiccChannelManagerService) {
|
||||
euiccLock.withLock {
|
||||
pendingDownload?.let { pending ->
|
||||
euiccChannelManagerService.recoverForegroundTaskSubscriber(pending.taskId)
|
||||
?.backChannel?.trySend(false)
|
||||
}
|
||||
pendingDownload = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A download task left in EuiccChannelManagerService waiting for confirmation.
|
||||
// LPAString is remembered to prevent reuse across different download sessions however unlikely.
|
||||
// Confirmation code is not included here since it does not change the identity of the profile being downloaded,
|
||||
// and could be supplied later.
|
||||
private data class PendingDownload(val taskId: Long, val lpaString: LPAString)
|
||||
|
||||
private val seId = EuiccChannel.SecureElementId.DEFAULT
|
||||
|
||||
private val hasInternalEuicc by lazy {
|
||||
|
|
@ -40,7 +88,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
|
|||
} else {
|
||||
// Otherwise, we can report at least one removable eUICC to the system without confusing
|
||||
// it too much.
|
||||
telephonyManager.uiccCardsInfoCompat.firstOrNull { it.isEuicc }?.physicalSlotIndex == physicalSlotId
|
||||
telephonyManager.uiccCardsInfoCompat.firstOrNull { it.isEuicc }?.physicalSlotIndex != physicalSlotId
|
||||
}
|
||||
|
||||
private data class EuiccChannelManagerContext(
|
||||
|
|
@ -58,9 +106,18 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
|
|||
* This ensures that we only spawn and connect to APDU channels when we absolutely need to,
|
||||
* instead of keeping them open unnecessarily in the background at all times.
|
||||
*
|
||||
* This function also serializes all access to EuiccChannelManager from this class with a mutex,
|
||||
* and it also ensures that when it calls fn(), no other foreground tasks managed by EuiccChannelManagerService
|
||||
* are running. This is currently a massive hack and requires fragile interaction between the two systems,
|
||||
* and is EXTREMELY hacky. THIS SHALL BE REPLACED AS SOON AS POSSIBLE.
|
||||
*
|
||||
* This function cannot be inline because non-local returns may bypass to unbind
|
||||
*/
|
||||
private fun <T> withEuiccChannelManager(fn: suspend EuiccChannelManagerContext.() -> T): T {
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
private fun <T> withEuiccChannelManager(
|
||||
waitForDownload: Boolean = true,
|
||||
fn: suspend EuiccChannelManagerContext.() -> T
|
||||
): T {
|
||||
val (binder, unbind) = runBlocking {
|
||||
bindServiceSuspended(
|
||||
Intent(this@OpenEuiccService, EuiccChannelManagerService::class.java),
|
||||
|
|
@ -74,11 +131,50 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
|
|||
|
||||
val localBinder = binder as EuiccChannelManagerService.LocalBinder
|
||||
|
||||
val ret = runBlocking {
|
||||
EuiccChannelManagerContext(localBinder.service).fn()
|
||||
val ret = try {
|
||||
runBlocking {
|
||||
// Wrapped in Result so that a legitimate null returned by fn() (e.g. onGetEid on
|
||||
// an unmapped slot) is not confused with "fn() has not run yet".
|
||||
var result: kotlin.Result<T>? = null
|
||||
// THIS IS WHERE I GO TO HELL FOR KEEPING THIS HORRIBLE SECTION OF CODE.
|
||||
// The main complexity here is that we need to serialize on both the mutex _in this class_,
|
||||
// and also on the foreground task system managed by EuiccChannelManagerService.
|
||||
// If any other method is currently accessing EuiccChannelManager, OR if any foreground task
|
||||
// is running, even if they're not launched from this service, we must not allow the callback
|
||||
// to run.
|
||||
while (true) {
|
||||
val task = euiccLock.withLock {
|
||||
if (waitForDownload) {
|
||||
val pending = pendingDownload
|
||||
val task = pending?.taskId?.let {
|
||||
localBinder.service.recoverForegroundTaskSubscriber(it)?.takeIf { handle ->
|
||||
// This is okay for a similar reason as pendingDownloadTask().
|
||||
!handle.backChannel.isClosedForSend
|
||||
}
|
||||
}
|
||||
if (task == null) {
|
||||
// The task is gone or has already finished
|
||||
if (pending != null) pendingDownload = null
|
||||
result =
|
||||
runCatching { EuiccChannelManagerContext(localBinder.service).fn() }
|
||||
}
|
||||
task
|
||||
} else {
|
||||
result =
|
||||
runCatching { EuiccChannelManagerContext(localBinder.service).fn() }
|
||||
null
|
||||
}
|
||||
}
|
||||
if (task == null) break
|
||||
task.stateFlow.waitDone()
|
||||
}
|
||||
// Always assigned by the time the loop breaks
|
||||
checkNotNull(result).getOrThrow()
|
||||
}
|
||||
} finally {
|
||||
unbind()
|
||||
}
|
||||
|
||||
unbind()
|
||||
return ret
|
||||
}
|
||||
|
||||
|
|
@ -133,7 +229,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
|
|||
} catch (_: Exception) {
|
||||
// Ignore
|
||||
} finally {
|
||||
delay(backoff.toLong())
|
||||
delay(backoff.toLong().milliseconds)
|
||||
}
|
||||
} while (System.currentTimeMillis() - startTimeMillis < timeoutMillis)
|
||||
return null
|
||||
|
|
@ -151,14 +247,271 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
|
|||
// Not implemented
|
||||
}
|
||||
|
||||
private fun DownloadableSubscription.parseActivationCode(): LPAString? =
|
||||
encodedActivationCode?.let { runCatching { LPAString.parse(it) }.getOrNull() }
|
||||
|
||||
// Wait for a download task to reach ConfirmingDownload; null if it failed before
|
||||
private suspend fun ForegroundTaskHandle.awaitConfirmingDownload() =
|
||||
// FIXME: This only awaits for ConfirmingDownload, but not later states. What happens if we happen to
|
||||
// race against the task in a way that makes it go past that state when we get here?
|
||||
// It should probably not happen normally since Android should not launch another download task
|
||||
// before it learns about teh completion of a previous one, but we probably need to address this.
|
||||
stateFlow.first {
|
||||
it is ForegroundTaskState.Done ||
|
||||
(it as? ForegroundTaskState.InProgress)?.context is ProfileDownloadState.ConfirmingDownload
|
||||
}.let { (it as? ForegroundTaskState.InProgress)?.context as? ProfileDownloadState.ConfirmingDownload }
|
||||
|
||||
// Returns the download task left pending by the metadata fetch call waiting for confirmation to
|
||||
// finish, but only if it was started for the same activation code.
|
||||
// Call sites should probably not expect a pending download task to always exist.
|
||||
// If it does not, you should probably just launch a new one via launchAndRememberDownloadTask,
|
||||
// which also cancels any pending download task for other sessions.
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
private fun EuiccChannelManagerContext.pendingDownloadTask(lpaString: LPAString): ForegroundTaskHandle? {
|
||||
val pending = pendingDownload ?: return null
|
||||
if (pending.lpaString != lpaString) {
|
||||
// A task is pending, but for another activation code. Leave it remembered so that
|
||||
// launchAndRememberDownloadTask cancels it; just do not reuse it here.
|
||||
return null
|
||||
}
|
||||
return euiccChannelManagerService.recoverForegroundTaskSubscriber(pending.taskId)?.takeIf {
|
||||
// Technically this is racy because the backChannel could be closed as we are
|
||||
// checking this status, but that is unlikely, and even if it happened, we would
|
||||
// just return a task handle that will emit an error (or Done). The user may see
|
||||
// a transient error and be asked to try again.
|
||||
!it.backChannel.isClosedForSend
|
||||
} ?: run {
|
||||
// Lazily clear the remembered task now that we know it is gone (or no longer waiting).
|
||||
// As its name suggests this variable and this function only cares about tasks left over by the
|
||||
// metadata fetch function.
|
||||
pendingDownload = null
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch a profile download task based on an existing bound EuiccChannelManager,
|
||||
* and remember it as pending for future confirmation.
|
||||
*
|
||||
* This function is almost entirely for the purpose of onGetDownloadableSubscriptionMetadata.
|
||||
* To acquire profile metadata, we must start a downlaod session, but onGetDownloadableSubscriptionMetadata
|
||||
* also must return once metadata is fetched. So it leaves two options: you either cancel the session
|
||||
* at that point, which, on many SM-DP+ servers, will also invalidate the matching code; or, you
|
||||
* keep the session around somehow and reuse it when the user finally proceeds to download.
|
||||
*
|
||||
* We keep the download task running in background for up to 5 minutes. This should be more than enough
|
||||
* for "normal" download sessions.
|
||||
*
|
||||
* Of course, it is also possible to launch a download task directly as part of onDownloadSubscription.
|
||||
* That probably does not happen except for privileged caller apps (system privileged)/
|
||||
*
|
||||
* Returns null if the caller should return RESULT_MUST_DEACTIVATE_SIM.
|
||||
*/
|
||||
private suspend fun EuiccChannelManagerContext.launchAndRememberDownloadTask(
|
||||
slotId: Int,
|
||||
portIndex: Int,
|
||||
lpaString: LPAString,
|
||||
confirmationCode: String?,
|
||||
forceDeactivateSim: Boolean
|
||||
): ForegroundTaskHandle? {
|
||||
// Only one task can run at a time; don't wait until another waiting download times out.
|
||||
pendingDownload?.let { pending ->
|
||||
euiccChannelManagerService.recoverForegroundTaskSubscriber(pending.taskId)
|
||||
?.backChannel?.trySend(false)
|
||||
}
|
||||
pendingDownload = null
|
||||
|
||||
val port = euiccChannelManager.findFirstAvailablePort(slotId).takeIf { it >= 0 } ?: run {
|
||||
if (!forceDeactivateSim) return null
|
||||
val port = if (portIndex >= 0) portIndex else 0
|
||||
ensurePortIsMapped(slotId, port)
|
||||
retryWithTimeout(5000) {
|
||||
euiccChannelManager.withEuiccChannel(slotId, port, seId) { channel ->
|
||||
if (!channel.valid) {
|
||||
throw IllegalStateException("Slot $slotId port $port is unavailable; may need to try again")
|
||||
}
|
||||
port
|
||||
}
|
||||
} ?: throw IllegalStateException("Slot $slotId port $port did not become available")
|
||||
}
|
||||
val imei = euiccChannelManager.withEuiccChannel(slotId, port, seId) { channel ->
|
||||
runCatching { telephonyManager.getImei(channel.logicalSlotId) }.getOrNull()
|
||||
}
|
||||
|
||||
euiccChannelManagerService.waitForForegroundTask()
|
||||
val handle = euiccChannelManagerService.launchProfileDownloadTask(
|
||||
slotId,
|
||||
port,
|
||||
seId,
|
||||
ProfileDownloadInput(
|
||||
lpaString.address,
|
||||
lpaString.matchingId,
|
||||
imei,
|
||||
confirmationCode
|
||||
),
|
||||
// Leaves time for the user to consent or enter a confirmation code in between
|
||||
5 * 60 * 1000
|
||||
)
|
||||
pendingDownload = PendingDownload(handle.taskId, lpaString)
|
||||
return handle
|
||||
}
|
||||
|
||||
override fun onGetDownloadableSubscriptionMetadata(
|
||||
slotId: Int,
|
||||
subscription: DownloadableSubscription?,
|
||||
forceDeactivateSim: Boolean
|
||||
): GetDownloadableSubscriptionMetadataResult {
|
||||
// Stub: return as-is and do not fetch anything
|
||||
// This is incompatible with carrier eSIM apps; should we make it compatible?
|
||||
return GetDownloadableSubscriptionMetadataResult(RESULT_OK, subscription)
|
||||
): GetDownloadableSubscriptionMetadataResult =
|
||||
if (subscription == null) {
|
||||
GetDownloadableSubscriptionMetadataResult(RESULT_FIRST_USER, null)
|
||||
} else {
|
||||
// -1 = any port
|
||||
onGetDownloadableSubscriptionMetadata(slotId, -1, subscription, forceDeactivateSim)
|
||||
}
|
||||
|
||||
override fun onGetDownloadableSubscriptionMetadata(
|
||||
slotId: Int,
|
||||
portIndex: Int,
|
||||
subscription: DownloadableSubscription,
|
||||
forceDeactivateSim: Boolean
|
||||
): GetDownloadableSubscriptionMetadataResult = withEuiccChannelManager(waitForDownload = false) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"onGetDownloadableSubscriptionMetadata slotId=$slotId portIndex=$portIndex forceDeactivateSim=$forceDeactivateSim"
|
||||
)
|
||||
val lpaString = subscription.parseActivationCode()
|
||||
if (shouldIgnoreSlot(slotId) || lpaString == null) {
|
||||
return@withEuiccChannelManager GetDownloadableSubscriptionMetadataResult(
|
||||
RESULT_FIRST_USER,
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
val confirming = try {
|
||||
// Either reuse a pending download task we launched before or create a new one.
|
||||
// As described in launchAndRememberDownloadTask, we must start to download in order to fetch metadata,
|
||||
// and we can't safely cancel the task in the general case for arbitrary SM-DP+ servers, so we need
|
||||
// to memorize the task to continue later.
|
||||
// It's possible that the system may call this function again for the same profile, so
|
||||
// we do need to check pendingDownloadTask.
|
||||
(pendingDownloadTask(lpaString)
|
||||
?: launchAndRememberDownloadTask(
|
||||
slotId,
|
||||
portIndex,
|
||||
lpaString,
|
||||
subscription.confirmationCode?.ifEmpty { null },
|
||||
forceDeactivateSim
|
||||
)
|
||||
?: return@withEuiccChannelManager GetDownloadableSubscriptionMetadataResult(
|
||||
RESULT_MUST_DEACTIVATE_SIM,
|
||||
null
|
||||
)).awaitConfirmingDownload()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to fetch profile metadata", e)
|
||||
null
|
||||
} ?: return@withEuiccChannelManager GetDownloadableSubscriptionMetadataResult(
|
||||
RESULT_FIRST_USER,
|
||||
null
|
||||
)
|
||||
|
||||
val builder = DownloadableSubscription.Builder(subscription)
|
||||
confirming.metadata?.let { metadata ->
|
||||
if (metadata.providerName.isNotBlank()) {
|
||||
builder.setCarrierName(metadata.providerName)
|
||||
}
|
||||
if (metadata.accessRules.isNotEmpty()) {
|
||||
builder.setAccessRules(metadata.accessRules.map {
|
||||
UiccAccessRule(it.certificateHash.decodeHex(), it.packageName, 0)
|
||||
})
|
||||
}
|
||||
}
|
||||
GetDownloadableSubscriptionMetadataResult(RESULT_OK, builder.build())
|
||||
}
|
||||
|
||||
override fun onDownloadSubscription(
|
||||
slotIndex: Int,
|
||||
portIndex: Int,
|
||||
subscription: DownloadableSubscription,
|
||||
switchAfterDownload: Boolean,
|
||||
forceDeactivateSim: Boolean,
|
||||
resolvedBundle: Bundle
|
||||
): DownloadSubscriptionResult {
|
||||
val (downloadResult, iccid) = withEuiccChannelManager(waitForDownload = false) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"onDownloadSubscription slotIndex=$slotIndex portIndex=$portIndex switchAfterDownload=$switchAfterDownload forceDeactivateSim=$forceDeactivateSim " +
|
||||
"callingPackage=${resolvedBundle.getString("android.service.euicc.extra.PACKAGE_NAME")}"
|
||||
)
|
||||
|
||||
val lpaString = subscription.parseActivationCode()
|
||||
if (shouldIgnoreSlot(slotIndex) || lpaString == null) {
|
||||
return@withEuiccChannelManager Pair(
|
||||
DownloadSubscriptionResult(RESULT_FIRST_USER, 0, TelephonyManager.UNSUPPORTED_CARD_ID),
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
// FIXME: I'm not sure this is entirely correct since it is possible that we only knew about
|
||||
// the confirmation code when the server returned an error. We need to handle that case
|
||||
// as well.
|
||||
if (lpaString.confirmationCodeRequired && subscription.confirmationCode.isNullOrEmpty()) {
|
||||
return@withEuiccChannelManager Pair(
|
||||
DownloadSubscriptionResult(
|
||||
RESULT_RESOLVABLE_ERRORS,
|
||||
RESOLVABLE_ERROR_CONFIRMATION_CODE,
|
||||
TelephonyManager.UNSUPPORTED_CARD_ID
|
||||
), null
|
||||
)
|
||||
}
|
||||
|
||||
val cardId = telephonyManager.uiccCardsInfoCompat.find { it.physicalSlotIndex == slotIndex }
|
||||
?.cardId ?: TelephonyManager.UNSUPPORTED_CARD_ID
|
||||
|
||||
suspend fun confirm(handle: ForegroundTaskHandle) =
|
||||
handle.awaitConfirmingDownload()?.takeIf {
|
||||
it.confirmationCode = subscription.confirmationCode?.ifEmpty { null }
|
||||
// Fails if the download is not waiting anymore, e.g. timed out
|
||||
handle.backChannel.trySend(true).isSuccess
|
||||
}
|
||||
|
||||
// Confirm the download onGetDownloadableSubscriptionMetadata() left waiting, or a new
|
||||
// one (it's possible to skip the get metadata step depending on caller privilege)
|
||||
val waiting = pendingDownloadTask(lpaString)
|
||||
val (handle, confirming) = waiting?.let { h -> confirm(h)?.let { Pair(h, it) } } ?: try {
|
||||
launchAndRememberDownloadTask(
|
||||
slotIndex, portIndex, lpaString,
|
||||
subscription.confirmationCode?.ifEmpty { null }, forceDeactivateSim
|
||||
)
|
||||
?.let { Pair(it, confirm(it)) }
|
||||
?: return@withEuiccChannelManager Pair(
|
||||
DownloadSubscriptionResult(RESULT_MUST_DEACTIVATE_SIM, 0, cardId), null
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Could not start the profile download", e)
|
||||
return@withEuiccChannelManager Pair(DownloadSubscriptionResult(RESULT_FIRST_USER, 0, cardId), null)
|
||||
}
|
||||
|
||||
val error = handle.stateFlow.waitDone()
|
||||
pendingDownload = null
|
||||
if (error != null) {
|
||||
Log.e(TAG, "Profile download failed", error)
|
||||
Pair(DownloadSubscriptionResult(RESULT_FIRST_USER, 0, cardId), null)
|
||||
} else {
|
||||
Pair(DownloadSubscriptionResult(RESULT_OK, 0, cardId), confirming?.metadata?.iccid)
|
||||
}
|
||||
}
|
||||
|
||||
if (downloadResult.result != RESULT_OK || !switchAfterDownload) return downloadResult
|
||||
|
||||
// Calling onSwitchToSubscriptionWithPort must happen outside of withEuiccChannelManager because
|
||||
// of the lock inside of that function.
|
||||
if (iccid.isNullOrEmpty() ||
|
||||
onSwitchToSubscriptionWithPort(slotIndex, portIndex, iccid, true) != RESULT_OK
|
||||
) {
|
||||
Log.e(TAG, "Profile $iccid downloaded but not enabled; it has to be enabled manually")
|
||||
// The platform only refreshes its list after the switch
|
||||
appContainer.subscriptionManager.tryRefreshCachedEuiccInfo(downloadResult.cardId)
|
||||
}
|
||||
return downloadResult
|
||||
}
|
||||
|
||||
override fun onGetDefaultDownloadableSubscriptionList(
|
||||
|
|
@ -181,7 +534,6 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
|
|||
)
|
||||
}
|
||||
|
||||
// TODO: Temporarily enable the slot to access its profiles if it is currently unmapped
|
||||
val port = euiccChannelManager.findFirstAvailablePort(slotId)
|
||||
if (port == -1) {
|
||||
return@withEuiccChannelManager GetEuiccProfileInfoListResult(
|
||||
|
|
@ -376,10 +728,14 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
|
|||
30 * 1000
|
||||
).stateFlow.waitDone()
|
||||
|
||||
if (res != null) return@withEuiccChannelManager RESULT_FIRST_USER
|
||||
if (res != null) {
|
||||
Log.e(TAG, "Profile switch task failed (iccid=$foundIccid enable=$enable)", res)
|
||||
return@withEuiccChannelManager RESULT_FIRST_USER
|
||||
}
|
||||
|
||||
return@withEuiccChannelManager RESULT_OK
|
||||
} catch (_: Exception) {
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "onSwitchToSubscriptionWithPort failed", e)
|
||||
return@withEuiccChannelManager RESULT_FIRST_USER
|
||||
} finally {
|
||||
euiccChannelManager.invalidate()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,224 @@
|
|||
package im.angry.openeuicc.ui
|
||||
|
||||
import android.content.DialogInterface
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import android.service.euicc.EuiccService
|
||||
import android.telephony.SubscriptionManager
|
||||
import android.telephony.TelephonyManager
|
||||
import android.telephony.euicc.EuiccManager
|
||||
import android.util.Log
|
||||
import android.widget.EditText
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.core.widget.doAfterTextChanged
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.google.android.material.textfield.TextInputLayout
|
||||
import im.angry.openeuicc.R
|
||||
import im.angry.openeuicc.service.OpenEuiccService
|
||||
import im.angry.openeuicc.util.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* LUI resolution activity, started by com.android.phone's EuiccResolutionUiDispatcherActivity when
|
||||
* the platform needs the user's consent (or a confirmation code) for an EuiccManager operation
|
||||
* requested by an app. The answer goes back through EuiccManager.continueOperation(), with the
|
||||
* intent's extras untouched; declining (or leaving) the dialog fails the operation.
|
||||
*/
|
||||
class EuiccResolutionActivity : BaseEuiccAccessActivity() {
|
||||
companion object {
|
||||
private const val TAG = "EuiccResolutionActivity"
|
||||
}
|
||||
|
||||
private var resolved = false
|
||||
|
||||
private val resolutionCallingPackage: String? by lazy {
|
||||
intent.getStringExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE)
|
||||
}
|
||||
|
||||
private val callingAppLabel: CharSequence by lazy {
|
||||
// Without QUERY_ALL_PACKAGES, the calling app may not be visible to us
|
||||
resolutionCallingPackage?.let {
|
||||
runCatching {
|
||||
packageManager.getApplicationLabel(packageManager.getApplicationInfo(it, 0))
|
||||
}.getOrDefault(it)
|
||||
} ?: getString(R.string.euicc_resolution_unknown_app)
|
||||
}
|
||||
|
||||
// Downloads (and metadata lookups) come with INVALID_SUBSCRIPTION_ID
|
||||
private val isSwitch: Boolean by lazy {
|
||||
intent.getIntExtra(
|
||||
EuiccService.EXTRA_RESOLUTION_SUBSCRIPTION_ID,
|
||||
SubscriptionManager.INVALID_SUBSCRIPTION_ID
|
||||
) != SubscriptionManager.INVALID_SUBSCRIPTION_ID
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.setBackgroundDrawableResource(android.R.color.transparent)
|
||||
}
|
||||
|
||||
override fun onInit() {
|
||||
val builder = AlertDialog.Builder(this, im.angry.openeuicc.common.R.style.AlertDialogTheme)
|
||||
val dialog = when (intent.action) {
|
||||
EuiccService.ACTION_RESOLVE_NO_PRIVILEGES -> builder
|
||||
.setTitle(
|
||||
getString(
|
||||
if (isSwitch) R.string.euicc_resolution_no_privileges_switch_title
|
||||
else R.string.euicc_resolution_no_privileges_title,
|
||||
callingAppLabel
|
||||
)
|
||||
)
|
||||
.setMessage(
|
||||
getString(
|
||||
if (isSwitch) R.string.euicc_resolution_no_privileges_switch_message
|
||||
else R.string.euicc_resolution_no_privileges_message,
|
||||
callingAppLabel
|
||||
)
|
||||
)
|
||||
.setNegativeButton(R.string.euicc_resolution_deny) { _, _ -> resolve(false) }
|
||||
.setPositiveButton(R.string.euicc_resolution_allow) { _, _ -> resolve(true) }
|
||||
.apply {
|
||||
if (resolutionCallingPackage != null) {
|
||||
setNeutralButton(R.string.euicc_resolution_app_info, null)
|
||||
}
|
||||
}
|
||||
.create()
|
||||
.apply {
|
||||
// Set here so that the button doesn't dismiss the dialog
|
||||
setOnShowListener {
|
||||
getButton(AlertDialog.BUTTON_NEUTRAL)?.setOnClickListener {
|
||||
startActivity(
|
||||
Intent(
|
||||
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.fromParts("package", resolutionCallingPackage, null)
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EuiccService.ACTION_RESOLVE_DEACTIVATE_SIM -> builder
|
||||
.setTitle(R.string.euicc_resolution_deactivate_sim_title)
|
||||
.setMessage(getString(R.string.euicc_resolution_deactivate_sim_message, callingAppLabel))
|
||||
.setNegativeButton(R.string.euicc_resolution_cancel) { _, _ -> resolve(false) }
|
||||
.setPositiveButton(R.string.euicc_resolution_continue) { _, _ -> resolve(true) }
|
||||
.create()
|
||||
|
||||
EuiccService.ACTION_RESOLVE_RESOLVABLE_ERRORS -> {
|
||||
val errors = intent.getIntExtra(EuiccService.EXTRA_RESOLVABLE_ERRORS, 0)
|
||||
val needsCode = errors and EuiccService.RESOLVABLE_ERROR_CONFIRMATION_CODE != 0
|
||||
val needsPolicyRules = errors and EuiccService.RESOLVABLE_ERROR_POLICY_RULES != 0
|
||||
val codeView = if (needsCode) {
|
||||
layoutInflater.inflate(R.layout.dialog_euicc_resolution_code, null)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val codeInput = codeView?.requireViewById<EditText>(R.id.euicc_resolution_code)
|
||||
if (intent.getBooleanExtra(EuiccService.EXTRA_RESOLUTION_CONFIRMATION_CODE_RETRIED, false)) {
|
||||
codeView?.requireViewById<TextInputLayout>(R.id.euicc_resolution_code_layout)?.error =
|
||||
getString(R.string.euicc_resolution_confirmation_code_retry)
|
||||
}
|
||||
|
||||
builder
|
||||
.setTitle(R.string.euicc_resolution_resolvable_errors_title)
|
||||
.setMessage(
|
||||
listOfNotNull(
|
||||
if (needsCode) {
|
||||
getString(R.string.euicc_resolution_confirmation_code_message, callingAppLabel)
|
||||
} else null,
|
||||
if (needsPolicyRules) getString(R.string.euicc_resolution_policy_rules_message) else null,
|
||||
).joinToString("\n\n")
|
||||
)
|
||||
.setView(codeView)
|
||||
.setNegativeButton(R.string.euicc_resolution_cancel) { _, _ -> resolve(false) }
|
||||
.setPositiveButton(R.string.euicc_resolution_continue) { _, _ ->
|
||||
resolve(true, Bundle().apply {
|
||||
if (needsCode) {
|
||||
putString(
|
||||
EuiccService.EXTRA_RESOLUTION_CONFIRMATION_CODE,
|
||||
codeInput?.text?.toString()?.trim()
|
||||
)
|
||||
}
|
||||
if (needsPolicyRules) {
|
||||
putBoolean(EuiccService.EXTRA_RESOLUTION_ALLOW_POLICY_RULES, true)
|
||||
}
|
||||
})
|
||||
}
|
||||
.create()
|
||||
.apply {
|
||||
// The platform fails the operation with an empty confirmation code
|
||||
if (codeInput != null) {
|
||||
setOnShowListener {
|
||||
val positive = getButton(DialogInterface.BUTTON_POSITIVE)
|
||||
positive.isEnabled = !codeInput.text.isNullOrBlank()
|
||||
codeInput.doAfterTextChanged { positive.isEnabled = !it.isNullOrBlank() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
Log.w(TAG, "Unsupported resolution action ${intent.action}")
|
||||
finish()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Back declines, but a stray tap outside the dialog doesn't
|
||||
dialog.setCanceledOnTouchOutside(false)
|
||||
dialog.setOnCancelListener { resolve(false) }
|
||||
dialog.show()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
// Never leave the operation (and the calling app) hanging
|
||||
if (isFinishing && !resolved) {
|
||||
resolve(false)
|
||||
}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun resolve(consent: Boolean, extras: Bundle = Bundle()) {
|
||||
if (resolved) return
|
||||
resolved = true
|
||||
Log.i(TAG, "Resolution ${intent.action} for $resolutionCallingPackage: consent=$consent")
|
||||
|
||||
if (!consent && !isSwitch && euiccChannelManagerLoaded.isCompleted) {
|
||||
// The platform doesn't tell OpenEuiccService; cancel the download it may have left
|
||||
// waiting for confirmation.
|
||||
lifecycleScope.launch(Dispatchers.IO) {
|
||||
OpenEuiccService.cancelPendingDownload(euiccChannelManagerService)
|
||||
}
|
||||
}
|
||||
|
||||
val resolutionExtras = Bundle(extras).apply {
|
||||
putBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT, consent)
|
||||
// For RESOLVE_NO_PRIVILEGES, the platform may leave the choice of the port to us
|
||||
val defaultPortIndex = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
TelephonyManager.DEFAULT_PORT_INDEX
|
||||
} else {
|
||||
0
|
||||
}
|
||||
if (intent.action == EuiccService.ACTION_RESOLVE_NO_PRIVILEGES &&
|
||||
intent.getIntExtra(EuiccService.EXTRA_RESOLUTION_PORT_INDEX, defaultPortIndex) < 0
|
||||
) {
|
||||
putInt(EuiccService.EXTRA_RESOLUTION_PORT_INDEX, defaultPortIndex)
|
||||
}
|
||||
}
|
||||
try {
|
||||
val cardId = intent.getIntExtra(EuiccService.EXTRA_RESOLUTION_CARD_ID, TelephonyManager.UNSUPPORTED_CARD_ID)
|
||||
getSystemService(EuiccManager::class.java)!!
|
||||
.let { if (cardId >= 0) it.createForCardId(cardId) else it }
|
||||
.continueOperation(intent, resolutionExtras)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Unable to continue eUICC operation", e)
|
||||
}
|
||||
|
||||
setResult(if (consent) RESULT_OK else RESULT_CANCELED)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
25
app/src/main/res/layout/dialog_euicc_resolution_code.xml
Normal file
25
app/src/main/res/layout/dialog_euicc_resolution_code.xml
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="24dp"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingEnd="24dp">
|
||||
|
||||
<com.google.android.material.textfield.TextInputLayout
|
||||
android:id="@+id/euicc_resolution_code_layout"
|
||||
style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="@string/euicc_resolution_confirmation_code_hint">
|
||||
|
||||
<com.google.android.material.textfield.TextInputEditText
|
||||
android:id="@+id/euicc_resolution_code"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="textNoSuggestions|textVisiblePassword"
|
||||
android:maxLines="1" />
|
||||
</com.google.android.material.textfield.TextInputLayout>
|
||||
</LinearLayout>
|
||||
|
|
@ -23,6 +23,25 @@
|
|||
<string name="lui_skip">Skip</string>
|
||||
<string name="lui_download">Download eSIM</string>
|
||||
|
||||
<!-- eUICC resolution (user consent) dialogs, shown on behalf of apps using EuiccManager -->
|
||||
<string name="euicc_resolution_unknown_app">Unknown app</string>
|
||||
<string name="euicc_resolution_no_privileges_title">Allow \"%1$s\" to download an eSIM?</string>
|
||||
<string name="euicc_resolution_no_privileges_message">\"%1$s\" wants to download a mobile network profile (eSIM) to this device and turn it on. This may turn off the profile currently in use on the eSIM.\n\nOnly allow this if you trust this app.</string>
|
||||
<string name="euicc_resolution_no_privileges_switch_title">Allow \"%1$s\" to switch your eSIM?</string>
|
||||
<string name="euicc_resolution_no_privileges_switch_message">\"%1$s\" wants to turn on another mobile network profile on your eSIM. The profile currently in use on the eSIM will be turned off.</string>
|
||||
<string name="euicc_resolution_allow">Allow</string>
|
||||
<string name="euicc_resolution_deny">Don\'t allow</string>
|
||||
<string name="euicc_resolution_app_info">App info</string>
|
||||
<string name="euicc_resolution_deactivate_sim_title">Turn off current mobile network?</string>
|
||||
<string name="euicc_resolution_deactivate_sim_message">To continue, \"%1$s\" needs to turn off the mobile network profile currently in use on this SIM. You can turn it back on later.</string>
|
||||
<string name="euicc_resolution_continue">Continue</string>
|
||||
<string name="euicc_resolution_cancel">Cancel</string>
|
||||
<string name="euicc_resolution_resolvable_errors_title">Additional confirmation needed</string>
|
||||
<string name="euicc_resolution_confirmation_code_message">Enter the confirmation code provided by your carrier to download the eSIM requested by \"%1$s\".</string>
|
||||
<string name="euicc_resolution_confirmation_code_retry">The confirmation code was incorrect. Please try again.</string>
|
||||
<string name="euicc_resolution_confirmation_code_hint">Confirmation code</string>
|
||||
<string name="euicc_resolution_policy_rules_message">This eSIM profile contains carrier policy rules, which may for example prevent turning it off or deleting it. Continue only if you agree.</string>
|
||||
|
||||
<!-- Preference -->
|
||||
<string name="pref_advanced_telephony_manager_removable">Use TelephonyManager everywhere</string>
|
||||
<string name="pref_advanced_telephony_manager_removable_desc">By default, only OMAPI is attempted for removable eSIMs to match what is done in unprivileged mode (i.e. EasyEUICC). This may not work well on some devices. Select this option to force the use of TelephonyManager even for removable eSIMs.</string>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,619 @@
|
|||
package im.angry.openeuicc.service
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.DialogInterface
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.service.euicc.EuiccService
|
||||
import android.service.euicc.GetEuiccProfileInfoListResult
|
||||
import android.telephony.TelephonyManager
|
||||
import android.telephony.UiccAccessRule
|
||||
import android.telephony.euicc.DownloadableSubscription
|
||||
import android.telephony.euicc.EuiccManager
|
||||
import android.widget.EditText
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import im.angry.openeuicc.R
|
||||
import im.angry.openeuicc.core.EuiccChannel
|
||||
import im.angry.openeuicc.core.EuiccChannelManager
|
||||
import im.angry.openeuicc.testutil.MockEuiccChannel
|
||||
import im.angry.openeuicc.testutil.MockEuiccChannelManager
|
||||
import im.angry.openeuicc.testutil.TestOpenEuiccApplication
|
||||
import im.angry.openeuicc.testutil.awaitMainLooper
|
||||
import im.angry.openeuicc.ui.EuiccResolutionActivity
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Deferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import net.typeblog.lpac_jni.EuiccInfo2
|
||||
import net.typeblog.lpac_jni.HttpInterface
|
||||
import net.typeblog.lpac_jni.LocalProfileAssistant
|
||||
import net.typeblog.lpac_jni.LocalProfileInfo
|
||||
import net.typeblog.lpac_jni.LocalProfileNotification
|
||||
import net.typeblog.lpac_jni.ProfileClass
|
||||
import net.typeblog.lpac_jni.ProfileDownloadCallback
|
||||
import net.typeblog.lpac_jni.ProfileDownloadInput
|
||||
import net.typeblog.lpac_jni.ProfileDownloadState
|
||||
import net.typeblog.lpac_jni.RemoteProfileAccessRule
|
||||
import net.typeblog.lpac_jni.RemoteProfileInfo
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.Implementation
|
||||
import org.robolectric.annotation.Implements
|
||||
import org.robolectric.shadows.ShadowDialog
|
||||
import org.robolectric.shadows.ShadowEuiccManager
|
||||
import org.robolectric.shadows.UiccCardInfoBuilder
|
||||
import org.robolectric.shadows.UiccPortInfoBuilder
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
import java.time.Duration
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
/**
|
||||
* Carrier-app eSIM downloads through the platform (EuiccManager.downloadSubscription() →
|
||||
* EuiccController → OpenEuiccService), tested only through the public EuiccService entry points
|
||||
* and the contract of EuiccResolutionActivity (the user's answer → continueOperation()).
|
||||
*
|
||||
* Everything in OpenEUICC runs for real (OpenEuiccService, EuiccChannelManagerService and its
|
||||
* foreground tasks); only the LPA is faked. [CarrierLpa] replays what lpac reported against real
|
||||
* SM-DP+ servers on a Galaxy S21 (LineageOS 23.2 / Android 16, September 2026), with made-up
|
||||
* ICCIDs, activation codes and certificate hashes.
|
||||
*
|
||||
* The platform called the service in this order for an unprivileged carrier app:
|
||||
* downloadSubscription() → RESOLVE_NO_PRIVILEGES → continueOperation(consent)
|
||||
* → onGetDownloadableSubscriptionMetadata(forceDeactivateSim = true)
|
||||
* → "Calling package has carrier privilege to this profile" (access rules match)
|
||||
* → onDownloadSubscription(forceDeactivateSim = true)
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(
|
||||
application = TestOpenEuiccApplication::class,
|
||||
shadows = [ContinueOperationRecorder::class]
|
||||
)
|
||||
class OpenEuiccServiceDownloadTest {
|
||||
companion object {
|
||||
const val SLOT = 1 // physical slot of the S21's built-in eUICC
|
||||
const val PORT = 0
|
||||
const val CARRIER_APP = "com.example.carrierapp"
|
||||
const val EID = "89000000000000000000000000000000"
|
||||
|
||||
val activationCode: DownloadableSubscription =
|
||||
DownloadableSubscription.forActivationCode("LPA:1\$smdp.example.com\$TEST-MATCHING-ID")
|
||||
|
||||
// SGP.22 StoreMetadataRequest as received from the Simyo SM-DP+: provider "simyo",
|
||||
// one REF-AR-DO (certificate hash, here a fake SHA-256, plus package name)
|
||||
val operatorProfile = RemoteProfileInfo(
|
||||
iccid = "89000000000000000011",
|
||||
name = "Simyo Android eSIM",
|
||||
providerName = "simyo",
|
||||
profileClass = ProfileClass.Operational,
|
||||
accessRules = listOf(RemoteProfileAccessRule("AB".repeat(32), CARRIER_APP)),
|
||||
)
|
||||
|
||||
// Nomad (travel eSIM, Thales SM-DP+): provider and name "NOMAD", one access rule
|
||||
val travelProfile = RemoteProfileInfo(
|
||||
iccid = "89000000000000000022",
|
||||
name = "NOMAD",
|
||||
providerName = "NOMAD",
|
||||
profileClass = ProfileClass.Operational,
|
||||
accessRules = listOf(RemoteProfileAccessRule("CD".repeat(32), null)),
|
||||
)
|
||||
}
|
||||
|
||||
private val app = RuntimeEnvironment.getApplication()
|
||||
private lateinit var lpa: CarrierLpa
|
||||
private lateinit var channelManager: CarrierChannelManager
|
||||
private lateinit var channelManagerService: VirtualClockEuiccChannelManagerService
|
||||
private lateinit var service: OpenEuiccService
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
lpa = CarrierLpa()
|
||||
channelManager = CarrierChannelManager(lpa)
|
||||
TestOpenEuiccApplication.mockEuiccChannelManager = channelManager
|
||||
channelManagerService =
|
||||
Robolectric.buildService(VirtualClockEuiccChannelManagerService::class.java).create().get()
|
||||
shadowOf(app).setComponentNameAndServiceForBindService(
|
||||
ComponentName(app, EuiccChannelManagerService::class.java),
|
||||
channelManagerService.onBind(Intent())
|
||||
)
|
||||
shadowOf(app.getSystemService(TelephonyManager::class.java)).setUiccCardsInfo(
|
||||
listOf(
|
||||
UiccCardInfoBuilder.newBuilder()
|
||||
.setIsEuicc(true)
|
||||
.setIsRemovable(false)
|
||||
.setPhysicalSlotIndex(SLOT)
|
||||
.setPorts(listOf(UiccPortInfoBuilder.newBuilder().setPortIndex(PORT).build()))
|
||||
.build()
|
||||
)
|
||||
)
|
||||
service = Robolectric.buildService(OpenEuiccService::class.java).create().get()
|
||||
ContinueOperationRecorder.extras.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* The platform calls EuiccService methods on a binder thread and waits for the result. Do the
|
||||
* same, while this (main) thread runs the main looper and delivers EuiccChannelManagerService's
|
||||
* self-start (startForegroundService()) like the system would. A call that blocks fails the
|
||||
* test after 30 s (its thread is left behind).
|
||||
*/
|
||||
private fun <T> platformCall(call: OpenEuiccService.() -> T): T = runBlocking {
|
||||
val result = CoroutineScope(Dispatchers.IO).async { service.call() }
|
||||
awaitMainLooper(30_000) {
|
||||
shadowOf(app).nextStartedService?.let {
|
||||
// Let the task subscribe to the start command first (it's not replayed)
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
channelManagerService.onStartCommand(it, 0, 1)
|
||||
}
|
||||
result.isCompleted
|
||||
}
|
||||
result.await()
|
||||
}
|
||||
|
||||
/**
|
||||
* Start EuiccResolutionActivity as com.android.phone does, press [button] (after typing
|
||||
* [confirmationCode], if given) and return the extras it passed to continueOperation().
|
||||
*/
|
||||
private fun userAnswers(intent: Intent, button: Int, confirmationCode: String? = null): Bundle {
|
||||
Robolectric.buildActivity(EuiccResolutionActivity::class.java, intent).setup()
|
||||
val dialog = ShadowDialog.getLatestDialog() as AlertDialog
|
||||
confirmationCode?.let { dialog.findViewById<EditText>(R.id.euicc_resolution_code)!!.setText(it) }
|
||||
dialog.getButton(button).performClick()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
return ContinueOperationRecorder.extras.single()
|
||||
}
|
||||
|
||||
// Mijn Simyo app, "Allow", switchAfterDownload = true
|
||||
@Test
|
||||
fun `operator app - one ES9+ session from metadata to download, then enable with refresh`() {
|
||||
val consent = userAnswers(
|
||||
Intent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES)
|
||||
.putExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE, CARRIER_APP),
|
||||
DialogInterface.BUTTON_POSITIVE
|
||||
)
|
||||
assertTrue(consent.getBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT))
|
||||
|
||||
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
|
||||
assertEquals(EuiccService.RESULT_OK, metadata.result)
|
||||
// The platform matches the calling package against these rules
|
||||
val subscription = metadata.downloadableSubscription
|
||||
assertEquals("simyo", ReflectionHelpers.callInstanceMethod<String>(subscription, "getCarrierName"))
|
||||
val rule = ReflectionHelpers.callInstanceMethod<List<UiccAccessRule>>(subscription, "getAccessRules").single()
|
||||
assertEquals("AB".repeat(32), rule.certificateHexString)
|
||||
assertEquals(CARRIER_APP, rule.packageName)
|
||||
// The session waits at the metadata step
|
||||
assertEquals(1, lpa.sessions.get())
|
||||
assertEquals(emptyList<Boolean>(), lpa.metadataStepAnswers)
|
||||
|
||||
val download = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, activationCode, true, true, Bundle())
|
||||
}
|
||||
assertEquals(EuiccService.RESULT_OK, download.result)
|
||||
// The same session continued: many SM-DP+ servers refuse a second one for the same order
|
||||
assertEquals(1, lpa.sessions.get())
|
||||
assertEquals(listOf(true), lpa.metadataStepAnswers)
|
||||
assertEquals(listOf(operatorProfile.iccid to true), lpa.enableCalls)
|
||||
}
|
||||
|
||||
// The SIM refresh of the switch makes the platform ask for the profiles
|
||||
// (SubscriptionManagerService.updateEmbeddedSubscriptions) while the switch waits for the eUICC
|
||||
// to come back. Without the new profile, it stores the new subscription as a physical SIM.
|
||||
@Test
|
||||
fun `profile list requested during the switch after a download has the new profile`() {
|
||||
lateinit var query: Deferred<GetEuiccProfileInfoListResult>
|
||||
channelManager.onRefresh = {
|
||||
query = CoroutineScope(Dispatchers.IO).async { service.onGetEuiccProfileInfoList(SLOT) }
|
||||
}
|
||||
|
||||
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
|
||||
val download = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, activationCode, true, true, Bundle())
|
||||
}
|
||||
assertEquals(EuiccService.RESULT_OK, download.result)
|
||||
assertEquals(listOf(operatorProfile.iccid to true), lpa.enableCalls)
|
||||
|
||||
val profiles = runBlocking {
|
||||
awaitMainLooper(30_000) { query.isCompleted }
|
||||
query.await()
|
||||
}
|
||||
assertEquals(EuiccService.RESULT_OK, profiles.result)
|
||||
assertEquals(listOf(operatorProfile.iccid), profiles.profiles.map { it.iccid })
|
||||
}
|
||||
|
||||
// The order where the metadata is fetched before the user declines (Mijn Simyo asked for
|
||||
// consent first, see the next test); the waiting session must not be left behind
|
||||
@Test
|
||||
fun `don't allow after the metadata step cancels the waiting session`() = runBlocking {
|
||||
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, false) }
|
||||
assertEquals(EuiccService.RESULT_OK, metadata.result)
|
||||
|
||||
val consent = userAnswers(
|
||||
Intent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES)
|
||||
.putExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE, CARRIER_APP),
|
||||
DialogInterface.BUTTON_NEGATIVE
|
||||
)
|
||||
// The platform reports the error to the carrier app upon consent = false
|
||||
assertEquals(false, consent.getBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT, true))
|
||||
|
||||
awaitMainLooper { lpa.metadataStepAnswers.isNotEmpty() }
|
||||
assertEquals(listOf(false), lpa.metadataStepAnswers)
|
||||
assertEquals(emptyList<LocalProfileInfo>(), lpa.profiles)
|
||||
}
|
||||
|
||||
// Mijn Simyo app, "Don't allow" (consent is asked before the metadata step)
|
||||
@Test
|
||||
fun `don't allow before the metadata step starts no ES9+ session`() {
|
||||
val consent = userAnswers(
|
||||
Intent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES)
|
||||
.putExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE, CARRIER_APP),
|
||||
DialogInterface.BUTTON_NEGATIVE
|
||||
)
|
||||
assertEquals(false, consent.getBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT, true))
|
||||
assertEquals(0, lpa.sessions.get())
|
||||
}
|
||||
|
||||
// Nomad app, switchAfterDownload = false, enabled later in Settings
|
||||
@Test
|
||||
fun `travel eSIM app - download without switching`() {
|
||||
lpa.metadata = travelProfile
|
||||
|
||||
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, -1, activationCode, true) }
|
||||
assertEquals(EuiccService.RESULT_OK, metadata.result)
|
||||
assertEquals(
|
||||
"NOMAD",
|
||||
ReflectionHelpers.callInstanceMethod<String>(metadata.downloadableSubscription, "getCarrierName")
|
||||
)
|
||||
|
||||
val download = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, activationCode, false, true, Bundle())
|
||||
}
|
||||
assertEquals(EuiccService.RESULT_OK, download.result)
|
||||
assertEquals(1, lpa.sessions.get())
|
||||
assertEquals(listOf(travelProfile.iccid), lpa.profiles.map { it.iccid })
|
||||
assertEquals(emptyList<Pair<String, Boolean>>(), lpa.enableCalls)
|
||||
}
|
||||
|
||||
// Not observed with a real carrier (Simyo and Nomad need no confirmation code)
|
||||
@Test
|
||||
fun `confirmation code requested after the metadata step continues the same session`() {
|
||||
val subscription =
|
||||
DownloadableSubscription.forActivationCode("LPA:1\$smdp.example.com\$TEST-MATCHING-ID\$\$1")
|
||||
|
||||
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, subscription, true) }
|
||||
assertEquals(EuiccService.RESULT_OK, metadata.result)
|
||||
|
||||
val needsCode = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, subscription, false, true, Bundle())
|
||||
}
|
||||
assertEquals(EuiccService.RESULT_RESOLVABLE_ERRORS, needsCode.result)
|
||||
assertEquals(
|
||||
EuiccService.RESOLVABLE_ERROR_CONFIRMATION_CODE,
|
||||
needsCode.resolvableErrors and EuiccService.RESOLVABLE_ERROR_CONFIRMATION_CODE
|
||||
)
|
||||
|
||||
val answer = userAnswers(
|
||||
Intent(EuiccService.ACTION_RESOLVE_RESOLVABLE_ERRORS)
|
||||
.putExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE, CARRIER_APP)
|
||||
.putExtra(EuiccService.EXTRA_RESOLVABLE_ERRORS, EuiccService.RESOLVABLE_ERROR_CONFIRMATION_CODE),
|
||||
DialogInterface.BUTTON_POSITIVE,
|
||||
confirmationCode = "1234"
|
||||
)
|
||||
assertTrue(answer.getBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT))
|
||||
assertEquals("1234", answer.getString(EuiccService.EXTRA_RESOLUTION_CONFIRMATION_CODE))
|
||||
|
||||
// EuiccController then runs the operation again, with the code
|
||||
val withCode = DownloadableSubscription.Builder(subscription).setConfirmationCode("1234").build()
|
||||
assertEquals(
|
||||
EuiccService.RESULT_OK,
|
||||
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, withCode, true) }.result
|
||||
)
|
||||
val download = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, withCode, false, true, Bundle())
|
||||
}
|
||||
assertEquals(EuiccService.RESULT_OK, download.result)
|
||||
assertEquals(1, lpa.sessions.get())
|
||||
assertEquals("1234", lpa.prepareDownloadConfirmationCode)
|
||||
}
|
||||
|
||||
// Not observed like this with a real carrier: a modem that rejects EnableProfile with refresh
|
||||
// (e.g. catBusy), so it only works without refresh and the switch task reports
|
||||
// SwitchingProfilesRefreshException after the profile has already been installed
|
||||
@Test
|
||||
fun `failed enable after a finished download still reports success`() {
|
||||
lpa.refreshWorks = false
|
||||
|
||||
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
|
||||
val download = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, activationCode, true, true, Bundle())
|
||||
}
|
||||
// An error would make the carrier app request a new activation code for a profile
|
||||
// that is already installed
|
||||
assertEquals(EuiccService.RESULT_OK, download.result)
|
||||
assertEquals(listOf(operatorProfile.iccid), lpa.profiles.map { it.iccid })
|
||||
assertEquals(
|
||||
listOf(operatorProfile.iccid to true, operatorProfile.iccid to false),
|
||||
lpa.enableCalls
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session waiting at the metadata step survives a slow user`() {
|
||||
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
|
||||
|
||||
// E.g. a consent or confirmation code dialog in between
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMinutes(1))
|
||||
|
||||
val download = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, activationCode, false, true, Bundle())
|
||||
}
|
||||
assertEquals(EuiccService.RESULT_OK, download.result)
|
||||
assertEquals(1, lpa.sessions.get())
|
||||
assertEquals(listOf(true), lpa.metadataStepAnswers)
|
||||
}
|
||||
|
||||
// The timeout itself runs on the virtual clock (VirtualClockEuiccChannelManagerService); this
|
||||
// checks that the service asks for one and cancels the session when it fires
|
||||
@Test
|
||||
fun `session waiting at the metadata step is cancelled after the timeout`() = runBlocking {
|
||||
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
|
||||
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMinutes(6))
|
||||
awaitMainLooper { lpa.metadataStepAnswers.isNotEmpty() }
|
||||
assertEquals(listOf(false), lpa.metadataStepAnswers)
|
||||
|
||||
// A late download request starts a new session
|
||||
val download = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, activationCode, false, true, Bundle())
|
||||
}
|
||||
assertEquals(EuiccService.RESULT_OK, download.result)
|
||||
assertEquals(2, lpa.sessions.get())
|
||||
assertEquals(listOf(false, true), lpa.metadataStepAnswers)
|
||||
}
|
||||
|
||||
// The waiting session holds the eUICC (the LPA lock). The platform calls these synchronously,
|
||||
// e.g. on the telephony worker thread; they block until the session is over and only then
|
||||
// touch the eUICC. Nothing confirms the session here, so the confirmation timeout cancels it.
|
||||
@Test
|
||||
fun `EID and profile list requests block until the waiting session is over`() = runBlocking {
|
||||
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
|
||||
assertEquals(1, lpa.sessions.get())
|
||||
|
||||
// Both block until the waiting session is over; nothing confirms it, so the confirmation
|
||||
// timeout cancels it while they wait (idleFor() advances the virtual clock)
|
||||
val eid = CoroutineScope(Dispatchers.IO).async { service.onGetEid(SLOT) }
|
||||
val profiles = CoroutineScope(Dispatchers.IO).async { service.onGetEuiccProfileInfoList(SLOT) }
|
||||
awaitMainLooper(30_000) {
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMinutes(1))
|
||||
eid.isCompleted && profiles.isCompleted
|
||||
}
|
||||
|
||||
assertEquals(EID, eid.await())
|
||||
assertEquals(EuiccService.RESULT_OK, profiles.await().result)
|
||||
assertEquals(1, lpa.sessions.get())
|
||||
assertEquals(listOf(false), lpa.metadataStepAnswers)
|
||||
}
|
||||
|
||||
// An invalid matching ID, refused by the SM-DP+ in
|
||||
// ES9+.AuthenticateClient with subjectCode 8.2.6, reasonCode 3.8
|
||||
@Test
|
||||
fun `server rejection is reported and leaves no waiting session`() {
|
||||
lpa.rejection = LocalProfileAssistant.ProfileDownloadException(
|
||||
lpaErrorReason = "ES10B_ERROR_REASON_UNDEFINED",
|
||||
lastHttpResponse = HttpInterface.HttpResponse(
|
||||
200,
|
||||
"""{"header":{"functionExecutionStatus":{"status":"Failed","statusCodeData":{"subjectCode":"8.2.6","reasonCode":"3.8","subjectIdentifier":"Matching ID","message":"Refused"}}}}""".toByteArray()
|
||||
),
|
||||
lastHttpException = null,
|
||||
lastApduResponse = null,
|
||||
lastApduException = null,
|
||||
)
|
||||
|
||||
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
|
||||
assertNotEquals(EuiccService.RESULT_OK, metadata.result)
|
||||
assertNull(metadata.downloadableSubscription)
|
||||
|
||||
val download = platformCall {
|
||||
onDownloadSubscription(SLOT, PORT, activationCode, true, true, Bundle())
|
||||
}
|
||||
assertNotEquals(EuiccService.RESULT_OK, download.result)
|
||||
assertEquals(2, lpa.sessions.get())
|
||||
assertEquals(emptyList<Boolean>(), lpa.metadataStepAnswers)
|
||||
assertEquals(emptyList<Pair<String, Boolean>>(), lpa.enableCalls)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A LocalProfileAssistant replaying lpac against a real SM-DP+. Each downloadProfile() call is
|
||||
* one ES9+ session: ES9+.InitiateAuthentication and AuthenticateClient (Preparing, Connecting,
|
||||
* Authenticating), then the metadata step (ConfirmingDownload with the StoreMetadataRequest
|
||||
* content) and, only if confirmed there, PrepareDownload, GetBoundProfilePackage and
|
||||
* LoadBoundProfilePackage (Downloading, Finalizing). Like LocalProfileAssistantImpl, it throws a
|
||||
* ProfileDownloadException when the session is declined at the metadata step or fails.
|
||||
*/
|
||||
class CarrierLpa : LocalProfileAssistant {
|
||||
/** Profile metadata sent by the SM-DP+ */
|
||||
@Volatile
|
||||
var metadata = OpenEuiccServiceDownloadTest.operatorProfile
|
||||
|
||||
/** If set, the SM-DP+ refuses the order during authentication with this error */
|
||||
@Volatile
|
||||
var rejection: LocalProfileAssistant.ProfileDownloadException? = null
|
||||
|
||||
/** Whether EnableProfile with refresh works; if not, it only works without refresh */
|
||||
@Volatile
|
||||
var refreshWorks = true
|
||||
|
||||
/** Number of ES9+ sessions (downloadProfile() calls) */
|
||||
val sessions = AtomicInteger()
|
||||
|
||||
/** What the callback answered at the metadata step, per session (false = cancelled) */
|
||||
val metadataStepAnswers = CopyOnWriteArrayList<Boolean>()
|
||||
|
||||
/** The confirmation code the last ES10b.PrepareDownload was called with */
|
||||
@Volatile
|
||||
var prepareDownloadConfirmationCode: String? = null
|
||||
|
||||
/** (ICCID, refresh) of every EnableProfile */
|
||||
val enableCalls = CopyOnWriteArrayList<Pair<String, Boolean>>()
|
||||
|
||||
private val installed = CopyOnWriteArrayList<LocalProfileInfo>()
|
||||
|
||||
// Like LocalProfileAssistantImpl: a download holds the eUICC for all other operations
|
||||
val lock = ReentrantLock()
|
||||
|
||||
override fun downloadProfile(input: ProfileDownloadInput, callback: ProfileDownloadCallback) = lock.withLock {
|
||||
sessions.incrementAndGet()
|
||||
callback.onStatusUpdate(ProfileDownloadState.Preparing())
|
||||
callback.onStatusUpdate(ProfileDownloadState.Connecting())
|
||||
callback.onStatusUpdate(ProfileDownloadState.Authenticating())
|
||||
rejection?.let { throw it }
|
||||
|
||||
val confirming = ProfileDownloadState.ConfirmingDownload(metadata)
|
||||
val confirmed = callback.onStatusUpdate(confirming)
|
||||
metadataStepAnswers += confirmed
|
||||
if (!confirmed) {
|
||||
throw LocalProfileAssistant.ProfileDownloadException(
|
||||
"ES10B_ERROR_REASON_UNDEFINED", null, null, null, null
|
||||
)
|
||||
}
|
||||
|
||||
prepareDownloadConfirmationCode = confirming.confirmationCode ?: input.confirmationCode
|
||||
callback.onStatusUpdate(ProfileDownloadState.Downloading())
|
||||
callback.onStatusUpdate(ProfileDownloadState.Finalizing())
|
||||
installed += LocalProfileInfo(
|
||||
metadata.iccid,
|
||||
LocalProfileInfo.State.Disabled,
|
||||
metadata.name,
|
||||
"",
|
||||
metadata.providerName,
|
||||
"",
|
||||
metadata.profileClass
|
||||
)
|
||||
}
|
||||
|
||||
override fun enableProfile(iccid: String, refresh: Boolean): Boolean {
|
||||
enableCalls += iccid to refresh
|
||||
return refreshWorks || !refresh
|
||||
}
|
||||
|
||||
override val profiles: List<LocalProfileInfo>
|
||||
get() = lock.withLock { installed.toList() }
|
||||
override val valid = true
|
||||
override val notifications = emptyList<LocalProfileNotification>()
|
||||
override val eID: String
|
||||
get() = lock.withLock { OpenEuiccServiceDownloadTest.EID }
|
||||
override val euiccInfo2: EuiccInfo2? = null
|
||||
override fun setEs10xMss(mss: Byte) {}
|
||||
override fun disableProfile(iccid: String, refresh: Boolean): Boolean = true
|
||||
override fun deleteProfile(iccid: String): Boolean = true
|
||||
override fun deleteNotification(seqNumber: Long): Boolean = true
|
||||
override fun handleNotification(seqNumber: Long): Boolean = true
|
||||
override fun euiccMemoryReset() {}
|
||||
override fun setNickname(iccid: String, nickname: String) {}
|
||||
override fun close() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Like DefaultEuiccChannelManager: waitForReconnect() and invalidate() close the channel, even while
|
||||
* someone else uses it, and the next withEuiccChannel() opens a new one. Using a closed channel
|
||||
* throws here; lpac itself uses its freed context.
|
||||
*/
|
||||
class CarrierChannelManager(private val lpa: CarrierLpa) : EuiccChannelManager by MockEuiccChannelManager(
|
||||
MockEuiccChannel(OpenEuiccServiceDownloadTest.SLOT, OpenEuiccServiceDownloadTest.PORT, lpa)
|
||||
) {
|
||||
/** How the platform reacts to the SIM refresh of a profile switch */
|
||||
@Volatile
|
||||
var onRefresh: (() -> Unit)? = null
|
||||
|
||||
private var channel = ChannelLpa(lpa)
|
||||
|
||||
override suspend fun <R> withEuiccChannel(
|
||||
physicalSlotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
fn: suspend (EuiccChannel) -> R
|
||||
): R {
|
||||
val channelLpa = synchronized(this) {
|
||||
channel.takeIf { !it.closed } ?: ChannelLpa(lpa).also { channel = it }
|
||||
}
|
||||
return fn(MockEuiccChannel(physicalSlotId, portId, channelLpa))
|
||||
}
|
||||
|
||||
override suspend fun waitForReconnect(physicalSlotId: Int, portId: Int, timeoutMillis: Long) {
|
||||
onRefresh?.invoke()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun invalidate() = lpa.lock.withLock {
|
||||
// Like LocalProfileAssistantImpl.close(), with the eUICC held; with the platform around,
|
||||
// let whoever got the channel before wait for the eUICC meanwhile (up to 1 s)
|
||||
val deadline = System.currentTimeMillis() + if (onRefresh != null) 1000 else 0
|
||||
while (!lpa.lock.hasQueuedThreads() && System.currentTimeMillis() < deadline) {
|
||||
Thread.sleep(10)
|
||||
}
|
||||
synchronized(this) { channel.close() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The LPA of one channel */
|
||||
class ChannelLpa(private val lpa: CarrierLpa) : LocalProfileAssistant by lpa {
|
||||
@Volatile
|
||||
var closed = false
|
||||
|
||||
override val profiles: List<LocalProfileInfo>
|
||||
get() = lpa.lock.withLock {
|
||||
check(!closed) { "Channel closed" }
|
||||
lpa.profiles
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
closed = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* EuiccChannelManagerService with the download confirmation timeout on Robolectric's clock (the
|
||||
* main looper) instead of the wall clock, so that tests can let minutes pass instantly.
|
||||
*/
|
||||
class VirtualClockEuiccChannelManagerService : EuiccChannelManagerService() {
|
||||
override fun launchProfileDownloadTask(
|
||||
slotId: Int,
|
||||
portId: Int,
|
||||
seId: EuiccChannel.SecureElementId,
|
||||
input: ProfileDownloadInput,
|
||||
confirmationTimeoutMillis: Long,
|
||||
): ForegroundTaskHandle =
|
||||
super.launchProfileDownloadTask(slotId, portId, seId, input, Long.MAX_VALUE).also {
|
||||
Handler(Looper.getMainLooper()).postDelayed(
|
||||
{ it.backChannel.trySend(false) },
|
||||
confirmationTimeoutMillis
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Records EuiccManager.continueOperation() (a system API that talks to EuiccController) */
|
||||
@Implements(EuiccManager::class)
|
||||
class ContinueOperationRecorder : ShadowEuiccManager() {
|
||||
companion object {
|
||||
val extras = CopyOnWriteArrayList<Bundle>()
|
||||
}
|
||||
|
||||
@Implementation
|
||||
protected fun continueOperation(resolutionIntent: Intent, resolutionExtras: Bundle) {
|
||||
extras += resolutionExtras
|
||||
}
|
||||
}
|
||||
2
app/src/test/resources/robolectric.properties
Normal file
2
app/src/test/resources/robolectric.properties
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
# EuiccService APIs used by OpenEuiccService need a recent platform
|
||||
sdk=35
|
||||
|
|
@ -10,3 +10,15 @@ plugins {
|
|||
tasks.register<Delete>("clean") {
|
||||
delete = setOf(rootProject.layout.buildDirectory)
|
||||
}
|
||||
|
||||
// Print per-test results (which tests ran, passed, failed, were skipped)
|
||||
// instead of Gradle's default summary-only output.
|
||||
subprojects {
|
||||
tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {
|
||||
testLogging {
|
||||
events("passed", "skipped", "failed")
|
||||
// Uncomment to also capture each test's stdout/stderr:
|
||||
// showStandardStreams = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
22
docs/ARA-M.md
Normal file
22
docs/ARA-M.md
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# ARA-M Applet Configuration
|
||||
|
||||
Audience: SAS-UP FAE
|
||||
|
||||
This configuration affects only EasyEUICC and is unrelated to OpenEUICC.
|
||||
|
||||
The ARA-M applet configuration is **REQUIRED** for EasyEUICC to communicate with the card in the device.
|
||||
|
||||
The current EasyEUICC signing key is valid until 24 Dec 2043 and is represented by the following fingerprints:
|
||||
|
||||
- `2A2FA878BC7C3354C2CF82935A5945A3EDAE4AFA` (SHA-1, **PREFERRED**)
|
||||
- `57BECC26B373A6475D093D33B0EA1C5E2BF2738EC0233680094CCBBCB500A13E` (SHA-256)
|
||||
|
||||
## Signing key rotation policy
|
||||
|
||||
There is currently no formal rotation plan or contingency. The design prioritizes maximum compatibility while a rotation strategy is selected in 2038 and implemented no later than 24 Dec 2038.
|
||||
|
||||
This approach provides a five-year migration window before the current signing key expires on 24 Dec 2043.
|
||||
|
||||
## References
|
||||
|
||||
- [UICC carrier privileges](https://source.android.com/docs/core/connect/uicc#rules_on_uicc)
|
||||
22
docs/ATR.md
Normal file
22
docs/ATR.md
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# Answer To Reset
|
||||
|
||||
Audience: SAS-UP FAE
|
||||
|
||||
## `T = 15` and interface byte
|
||||
|
||||
After `T = 15`, the first `tBi` byte is not arbitrary; it indicates interface byte.
|
||||
For ETSI TS 102 221, the key values are:
|
||||
|
||||
- `0x82` (`0b1000_0010`): eUICC-related functions supported
|
||||
- `0x81` (`0b1000_0001`): LSIs (Logical Secure Element Interfaces) supported
|
||||
|
||||
These are defined in [ETSI TS 102 221, clause 6.3.3, Table 6.7](https://www.etsi.org/deliver/etsi_ts/102200_102299/102221/18.02.00_60/ts_102221v180200p.pdf#page=36).
|
||||
|
||||
## Why it matters
|
||||
|
||||
- `T = 15` + first `tBi = 0x82`: the card is advertising **eUICC-related functions supported**. \
|
||||
On Android, removable eUICC with this flag is often treated as non-removable. \
|
||||
Result: the modem/Telephony stack may refuse to re-enable it as a normal SIM
|
||||
- `T = 15` + first `tBi = 0x81`: the card is advertising **LSIs supported**. \
|
||||
This is not a strong compatibility signal for removable eUICC behavior. \
|
||||
Modem implementations vary; support is not consistently reliable.
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
Since: OpenEUICC v1.3.0 or EasyEUICC v1.3.0
|
||||
|
||||
## Web Intent
|
||||
## Web intent
|
||||
|
||||
HTML example:
|
||||
|
||||
|
|
@ -10,7 +10,7 @@ HTML example:
|
|||
<a href="lpa:1$rsp.example.com$matching-id">Open {Open/Easy}EUICC</a>
|
||||
```
|
||||
|
||||
## Android Intent
|
||||
## Android intent
|
||||
|
||||
Kotlin example:
|
||||
|
||||
|
|
@ -19,8 +19,7 @@ val lpaUri = Uri.parse("lpa:1\$rsp.example.com\$matching-id")
|
|||
startActivity(Intent(Intent.ACTION_VIEW, lpaUri))
|
||||
```
|
||||
|
||||
To check whether any installed app can handle this deep link, call [PackageManager#queryIntentActivities] before calling
|
||||
`startActivity`.
|
||||
Before calling `startActivity`, check whether any installed app can handle this deep link by calling [PackageManager#queryIntentActivities].
|
||||
|
||||
[PackageManager#queryIntentActivities]: https://developer.android.com/reference/android/content/pm/PackageManager#queryIntentActivities(android.content.Intent,%20int)
|
||||
|
||||
|
|
|
|||
8
docs/README.md
Normal file
8
docs/README.md
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
# Application Notes
|
||||
|
||||
- [Deep Link](DEEP-LINK.md)
|
||||
|
||||
## EasyEUICC
|
||||
|
||||
- [Answer To Reset](ATR.md)
|
||||
- [ARA-M Applet Configuration](ARA-M.md)
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package im.angry.openeuicc.util
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.telephony.UiccAccessRule
|
||||
import android.telephony.euicc.DownloadableSubscription
|
||||
import android.telephony.euicc.EuiccManager
|
||||
import java.lang.reflect.Method
|
||||
|
||||
// System APIs of android.telephony.euicc via reflection to enable building without AOSP source
|
||||
// tree (see TelephonyManagerHiddenApi.kt). When building against AOSP, the real member
|
||||
// functions take precedence and this file is not compiled at all.
|
||||
private val continueOperation: Method by lazy {
|
||||
EuiccManager::class.java.getMethod(
|
||||
"continueOperation",
|
||||
Intent::class.java, Bundle::class.java
|
||||
)
|
||||
}
|
||||
private val builderSetCarrierName: Method by lazy {
|
||||
DownloadableSubscription.Builder::class.java.getMethod(
|
||||
"setCarrierName",
|
||||
String::class.java
|
||||
)
|
||||
}
|
||||
private val builderSetAccessRules: Method by lazy {
|
||||
DownloadableSubscription.Builder::class.java.getMethod(
|
||||
"setAccessRules",
|
||||
List::class.java
|
||||
)
|
||||
}
|
||||
|
||||
fun EuiccManager.continueOperation(resolutionIntent: Intent, resolutionExtras: Bundle) {
|
||||
continueOperation.invoke(this, resolutionIntent, resolutionExtras)
|
||||
}
|
||||
|
||||
fun DownloadableSubscription.Builder.setCarrierName(value: String): DownloadableSubscription.Builder =
|
||||
builderSetCarrierName.invoke(this, value) as DownloadableSubscription.Builder
|
||||
|
||||
fun DownloadableSubscription.Builder.setAccessRules(value: List<UiccAccessRule>): DownloadableSubscription.Builder =
|
||||
builderSetAccessRules.invoke(this, value) as DownloadableSubscription.Builder
|
||||
|
|
@ -151,6 +151,12 @@ public abstract class EuiccService extends Service {
|
|||
*/
|
||||
public static final String EXTRA_RESOLUTION_CARD_ID =
|
||||
"android.service.euicc.extra.RESOLUTION_CARD_ID";
|
||||
/**
|
||||
* Intent extra set for resolution requests containing an int indicating the subscription id
|
||||
* to be enabled.
|
||||
*/
|
||||
public static final String EXTRA_RESOLUTION_SUBSCRIPTION_ID =
|
||||
"android.service.euicc.extra.RESOLUTION_SUBSCRIPTION_ID";
|
||||
/**
|
||||
* Intent extra set for resolution requests containing an int indicating the current port index.
|
||||
*/
|
||||
|
|
@ -288,6 +294,14 @@ public abstract class EuiccService extends Service {
|
|||
public abstract GetDownloadableSubscriptionMetadataResult onGetDownloadableSubscriptionMetadata(
|
||||
int slotId, DownloadableSubscription subscription, boolean forceDeactivateSim);
|
||||
|
||||
public GetDownloadableSubscriptionMetadataResult onGetDownloadableSubscriptionMetadata(
|
||||
int slotId, int portIndex, DownloadableSubscription subscription,
|
||||
boolean forceDeactivateSim) {
|
||||
// stub implementation, LPA needs to implement this
|
||||
throw new UnsupportedOperationException(
|
||||
"LPA must override onGetDownloadableSubscriptionMetadata");
|
||||
}
|
||||
|
||||
/**
|
||||
* Return metadata for subscriptions which are available for download for this device.
|
||||
*
|
||||
|
|
@ -328,6 +342,13 @@ public abstract class EuiccService extends Service {
|
|||
return null;
|
||||
}
|
||||
|
||||
public DownloadSubscriptionResult onDownloadSubscription(int slotIndex, int portIndex,
|
||||
DownloadableSubscription subscription, boolean switchAfterDownload,
|
||||
boolean forceDeactivateSim, Bundle resolvedBundle) {
|
||||
// stub implementation, LPA needs to implement this
|
||||
throw new UnsupportedOperationException("LPA must override onDownloadSubscription");
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the given subscription.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -4,7 +4,10 @@ sealed class ProfileDownloadState {
|
|||
class Preparing : ProfileDownloadState()
|
||||
class Connecting : ProfileDownloadState()
|
||||
class Authenticating : ProfileDownloadState()
|
||||
class ConfirmingDownload(val metadata: RemoteProfileInfo?) : ProfileDownloadState()
|
||||
class ConfirmingDownload(val metadata: RemoteProfileInfo?) : ProfileDownloadState() {
|
||||
// FIXME: Pass this back to JNI better. Something that's not a random property.
|
||||
var confirmationCode: String? = null
|
||||
}
|
||||
class Downloading : ProfileDownloadState()
|
||||
class Finalizing : ProfileDownloadState()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,4 +6,22 @@ data class RemoteProfileInfo(
|
|||
val name: String,
|
||||
val providerName: String,
|
||||
val profileClass: ProfileClass,
|
||||
// Carrier privilege access rules (REF-AR-DO) from the profile metadata
|
||||
val accessRules: List<RemoteProfileAccessRule>,
|
||||
) {
|
||||
// Used by JNI (see lpac-download.c)
|
||||
@Suppress("unused")
|
||||
constructor(
|
||||
iccid: String,
|
||||
name: String,
|
||||
providerName: String,
|
||||
profileClass: ProfileClass,
|
||||
accessRules: Array<RemoteProfileAccessRule>,
|
||||
) : this(iccid, name, providerName, profileClass, accessRules.toList())
|
||||
}
|
||||
|
||||
// packageName is null if the rule applies to any app signed with the certificate
|
||||
data class RemoteProfileAccessRule(
|
||||
val certificateHash: String,
|
||||
val packageName: String?,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
Subproject commit c859b25da02955fef659d658b8f324b5cde87be3
|
||||
Subproject commit 6d9f2443ab071f86e5d9b43025a40929ec41c46c
|
||||
|
|
@ -1 +1 @@
|
|||
Subproject commit d214738fa0bdb23faf5833d3d798963079a00468
|
||||
Subproject commit 50cdf15ab40942b00f8819a1c2ca19997f1a6d34
|
||||
|
|
@ -15,8 +15,11 @@ jobject download_state_finalizing;
|
|||
jmethodID on_state_update;
|
||||
jclass confirming_download_class;
|
||||
jmethodID confirming_download_constructor;
|
||||
jmethodID confirming_download_get_confirmation_code;
|
||||
jclass remote_profile_info_class;
|
||||
jmethodID remote_profile_info_constructor;
|
||||
jclass remote_profile_access_rule_class;
|
||||
jmethodID remote_profile_access_rule_constructor;
|
||||
jobject profile_class_testing;
|
||||
jobject profile_class_provisioning;
|
||||
jobject profile_class_operational;
|
||||
|
|
@ -86,6 +89,10 @@ void lpac_download_init() {
|
|||
confirming_download_class,
|
||||
"<init>",
|
||||
"(Lnet/typeblog/lpac_jni/RemoteProfileInfo;)V");
|
||||
confirming_download_get_confirmation_code = (*env)->GetMethodID(env,
|
||||
confirming_download_class,
|
||||
"getConfirmationCode",
|
||||
"()Ljava/lang/String;");
|
||||
|
||||
jclass profile_class_class = (*env)->FindClass(env, "net/typeblog/lpac_jni/ProfileClass");
|
||||
jfieldID profile_class_testing_field = (*env)->GetStaticFieldID(env, profile_class_class,
|
||||
|
|
@ -111,7 +118,15 @@ void lpac_download_init() {
|
|||
"net/typeblog/lpac_jni/RemoteProfileInfo");
|
||||
remote_profile_info_class = (*env)->NewGlobalRef(env, _remote_profile_info_class);
|
||||
remote_profile_info_constructor = (*env)->GetMethodID(env, remote_profile_info_class, "<init>",
|
||||
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/typeblog/lpac_jni/ProfileClass;)V");
|
||||
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/typeblog/lpac_jni/ProfileClass;[Lnet/typeblog/lpac_jni/RemoteProfileAccessRule;)V");
|
||||
|
||||
jclass _remote_profile_access_rule_class = (*env)->FindClass(env,
|
||||
"net/typeblog/lpac_jni/RemoteProfileAccessRule");
|
||||
remote_profile_access_rule_class = (*env)->NewGlobalRef(env, _remote_profile_access_rule_class);
|
||||
remote_profile_access_rule_constructor = (*env)->GetMethodID(env,
|
||||
remote_profile_access_rule_class,
|
||||
"<init>",
|
||||
"(Ljava/lang/String;Ljava/lang/String;)V");
|
||||
}
|
||||
|
||||
static jobject profile_class_from_es10c_profile_class(enum es10c_profile_class profile_class) {
|
||||
|
|
@ -133,7 +148,27 @@ static jobject create_remote_profile_info(JNIEnv *env,
|
|||
jstring metadata_iccid = NULL;
|
||||
jstring metadata_profile_name = NULL;
|
||||
jstring metadata_provider_name = NULL;
|
||||
jobjectArray metadata_access_rules = NULL;
|
||||
jobject remote_profile_info = NULL;
|
||||
struct es8p_metadata_access_rule *rule;
|
||||
jsize i = 0;
|
||||
|
||||
for (rule = profile_metadata->accessRules; rule != NULL; rule = rule->next)
|
||||
i++;
|
||||
metadata_access_rules = (*env)->NewObjectArray(env, i, remote_profile_access_rule_class, NULL);
|
||||
for (i = 0, rule = profile_metadata->accessRules; rule != NULL; i++, rule = rule->next) {
|
||||
jstring cert_hash = toJString(env, rule->certificateHash);
|
||||
// toJString() would turn a missing package name into ""
|
||||
jstring package_name = rule->packageName != NULL ? toJString(env, rule->packageName) : NULL;
|
||||
jobject access_rule = (*env)->NewObject(env, remote_profile_access_rule_class,
|
||||
remote_profile_access_rule_constructor,
|
||||
cert_hash, package_name);
|
||||
(*env)->SetObjectArrayElement(env, metadata_access_rules, i, access_rule);
|
||||
(*env)->DeleteLocalRef(env, access_rule);
|
||||
(*env)->DeleteLocalRef(env, cert_hash);
|
||||
if (package_name != NULL)
|
||||
(*env)->DeleteLocalRef(env, package_name);
|
||||
}
|
||||
|
||||
metadata_iccid = toJString(env, profile_metadata->iccid);
|
||||
metadata_profile_name = toJString(env, profile_metadata->profileName);
|
||||
|
|
@ -145,8 +180,10 @@ static jobject create_remote_profile_info(JNIEnv *env,
|
|||
metadata_iccid,
|
||||
metadata_profile_name,
|
||||
metadata_provider_name,
|
||||
profile_class);
|
||||
profile_class,
|
||||
metadata_access_rules);
|
||||
|
||||
(*env)->DeleteLocalRef(env, metadata_access_rules);
|
||||
if (metadata_iccid != NULL)
|
||||
(*env)->DeleteLocalRef(env, metadata_iccid);
|
||||
if (metadata_profile_name != NULL)
|
||||
|
|
@ -166,11 +203,13 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
|
|||
struct es8p_metadata *profile_metadata = NULL;
|
||||
struct es10b_load_bound_profile_package_result es10b_load_bound_profile_package_result;
|
||||
const char *_confirmation_code = NULL;
|
||||
const char *_late_confirmation_code = NULL;
|
||||
const char *_matching_id = NULL;
|
||||
const char *_smdp = NULL;
|
||||
const char *_imei = NULL;
|
||||
jobject remote_profile_info = NULL;
|
||||
jobject confirming_download_state = NULL;
|
||||
jstring late_confirmation_code = NULL;
|
||||
jboolean confirmed = JNI_TRUE;
|
||||
int ret;
|
||||
|
||||
|
|
@ -256,6 +295,15 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
|
|||
|
||||
confirmed = (*env)->CallBooleanMethod(env, callback, on_state_update, confirming_download_state);
|
||||
|
||||
if (confirmed) {
|
||||
// The callback may have set the confirmation code only now (EuiccService case)
|
||||
// FIXME: This should probably be passed in through something that's not just a property.
|
||||
late_confirmation_code = (*env)->CallObjectMethod(env, confirming_download_state,
|
||||
confirming_download_get_confirmation_code);
|
||||
if (late_confirmation_code != NULL)
|
||||
_late_confirmation_code = (*env)->GetStringUTFChars(env, late_confirmation_code, NULL);
|
||||
}
|
||||
|
||||
if (remote_profile_info != NULL) {
|
||||
(*env)->DeleteLocalRef(env, remote_profile_info);
|
||||
remote_profile_info = NULL;
|
||||
|
|
@ -276,7 +324,8 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
|
|||
goto out;
|
||||
}
|
||||
|
||||
ret = es10b_prepare_download(ctx, _confirmation_code);
|
||||
ret = es10b_prepare_download(ctx, _late_confirmation_code != NULL ? _late_confirmation_code
|
||||
: _confirmation_code);
|
||||
syslog(LOG_INFO, "es10b_prepare_download %d", ret);
|
||||
if (ret < 0) {
|
||||
ret = -ES10B_ERROR_REASON_UNDEFINED;
|
||||
|
|
@ -307,6 +356,10 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
|
|||
// This is so that Java side can access the last HTTP and/or APDU errors when we return.
|
||||
if (_confirmation_code != NULL)
|
||||
(*env)->ReleaseStringUTFChars(env, confirmation_code, _confirmation_code);
|
||||
if (_late_confirmation_code != NULL)
|
||||
(*env)->ReleaseStringUTFChars(env, late_confirmation_code, _late_confirmation_code);
|
||||
if (late_confirmation_code != NULL)
|
||||
(*env)->DeleteLocalRef(env, late_confirmation_code);
|
||||
if (_matching_id != NULL)
|
||||
(*env)->ReleaseStringUTFChars(env, matching_id, _matching_id);
|
||||
(*env)->ReleaseStringUTFChars(env, smdp, _smdp);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue