Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1473,6 +1473,7 @@ internal class ConsentGoldenEcosystem private constructor(
internal object GoldenTransitFareTransaction : TransactionType<GoldenTransitFareTransaction.Payload>(
displayName = "Transit fare",
identifier = "org.multipaz.golden.transit_fare",
requiresRenderer = true,
) {
data class Fare(
val id: String,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package org.multipaz.compose.presentment

import android.app.Application
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.core.app.ApplicationProvider
import kotlinx.coroutines.runBlocking
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.multipaz.context.initializeApplication
import org.multipaz.presentment.PresentmentData
import org.multipaz.prompt.AndroidPromptModel
import org.multipaz.prompt.TransactionDataRenderer
import org.multipaz.prompt.TransactionDataRendererNotAvailableException
import org.multipaz.prompt.TransactionDataRendererRepository
import org.multipaz.prompt.requestConsent
import org.multipaz.request.Requester
import org.multipaz.request.TrustedRequesterIdentity
import org.multipaz.utopia.knowntypes.DigitalPaymentCredential
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.security.Security
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

/**
* Checks that [Consent] never draws, and so never lets the person approve, transaction data of a
* type that [org.multipaz.documenttype.TransactionType.requiresRenderer] with the built-in
* rendering.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w412dp-h915dp-xxhdpi")
class ConsentRequiresRendererTest {

@get:Rule
val composeTestRule = createComposeRule()

@Before
fun setUp() {
Security.addProvider(BouncyCastleProvider())
val app = ApplicationProvider.getApplicationContext<Application>()
initializeApplication(app)
ConsentGoldenEcosystem.registerFakeAndroidApps(app)
}

private class Setup(
val requester: Requester,
val trusted: TrustedRequesterIdentity?,
val presentmentData: PresentmentData,
val goldenRepository: TransactionDataRendererRepository,
)

private fun setup() = runBlocking {
val eco = ConsentGoldenEcosystem.create()
val (requester, trusted) = eco.trustedProximityRequester(ConsentGoldenEcosystem.RP_METRO_TRANSIT)
val canned = DigitalPaymentCredential.getDocumentType().cannedRequests.first {
it.id == "payment_transaction_only_conf"
}
val presentmentData = eco.executeCannedDcql(
cannedRequest = canned,
transactionDataMap = mapOf(
"cred1" to listOf(
goldenTransactionData(GoldenTransitFareTransaction, GoldenTransitFareTransaction.sampleData)
)
),
)
Setup(requester, trusted, presentmentData, eco.transactionDataRendererRepository)
}

private fun showConsent(setup: Setup, repository: TransactionDataRendererRepository?): Pair<Int, Int> {
var confirmed = 0
var cancelled = 0
composeTestRule.setContent {
Consent(
requester = setup.requester,
trustedRequesterIdentity = setup.trusted,
presentmentData = setup.presentmentData,
preselectedDocuments = emptyList(),
imageLoader = null,
transactionDataRendererRepository = repository,
onDocumentsInFocus = {},
onConfirm = { confirmed++ },
onCancel = { cancelled++ },
)
}
composeTestRule.waitForIdle()
return Pair(confirmed, cancelled)
}

@Test
fun noRepositoryRefusesInsteadOfDrawingBuiltInRendering() {
assertEquals(Pair(0, 1), showConsent(setup(), repository = null))
}

@Test
fun rendererForAnotherToolkitRefuses() {
val setup = setup()
val repository = TransactionDataRendererRepository().apply {
addRenderer(GoldenTransitFareTransaction.identifier, object : TransactionDataRenderer() {})
}
assertEquals(Pair(0, 1), showConsent(setup, repository))
}

@Test
fun composeRendererLetsConsentBeDrawn() {
val setup = setup()
assertEquals(Pair(0, 0), showConsent(setup, setup.goldenRepository))
}

@Test
fun allTransactionDataListsTheItemsOfEveryMatch() {
// The sample holds two payment credentials, so the item is listed once per solution.
val identifiers = setup().presentmentData.allTransactionData.map { it.type.identifier }
assertEquals(2, identifiers.size)
assertEquals(setOf(GoldenTransitFareTransaction.identifier), identifiers.toSet())
}

@Test
fun requestConsentRefusesBeforeShowingAnything() = runBlocking {
val setup = setup()
val promptModel = AndroidPromptModel.Builder().addCommonDialogs().build()
// Nothing is bound to the prompt model, so showing the prompt would have thrown
// PromptUiNotAvailableException instead.
val e = assertFailsWith<TransactionDataRendererNotAvailableException> {
promptModel.requestConsent(
requester = setup.requester,
trustedRequesterIdentity = setup.trusted,
presentmentData = setup.presentmentData,
preselectedDocuments = emptyList(),
onDocumentsInFocus = {},
transactionDataRendererRepository = null,
)
}
assertEquals(GoldenTransitFareTransaction.identifier, e.typeIdentifier)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ import org.multipaz.presentment.RequesterHistoryEntry
import org.multipaz.presentment.TransactionData
import org.multipaz.presentment.TransactionDataContext
import org.multipaz.prompt.TransactionDataRendererRepository
import org.multipaz.prompt.missingTransactionDataRenderer
import org.multipaz.request.OpenID4VPRequesterIdentity
import org.multipaz.request.Requester
import org.multipaz.request.TrustedRequesterIdentity
Expand Down Expand Up @@ -355,7 +356,10 @@ private const val TAG = "Consent"
* @param onDocumentsInFocus called with the documents currently selected for the user, including when
* first shown. If the user selects a different set of documents in the prompt, this will be called again.
* @param onConfirm called when the user presses the "Continue" button, returns the user's selection.
* @param onCancel called when the sheet is dismissed.
* @param onCancel called when the sheet is dismissed. It is also called, with nothing drawn, when
* [presentmentData] holds transaction data of a type that
* [org.multipaz.documenttype.TransactionType.requiresRenderer] and [transactionDataRendererRepository]
* has no [TransactionDataRendererCompose] for it: such data is never approved with the built-in rendering.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
Expand All @@ -374,6 +378,20 @@ fun Consent(
onConfirm: (selection: PresentmentSelection) -> Unit,
onCancel: () -> Unit = {},
) {
val missingRenderer = remember(presentmentData, transactionDataRendererRepository) {
missingTransactionDataRenderer(
transactionData = presentmentData.allTransactionData,
repository = transactionDataRendererRepository,
isUsable = { it is TransactionDataRendererCompose },
)
}
if (missingRenderer != null) {
LaunchedEffect(missingRenderer) {
Logger.w(TAG, "No usable renderer for transaction type '$missingRenderer', not showing consent")
onCancel()
}
return
}
val navController = rememberNavController()
val appInfo = remember {
requester.appId?.let {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,20 @@ package org.multipaz.compose.prompt
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.unit.Dp
import coil3.ImageLoader
import kotlinx.coroutines.launch
import org.multipaz.compose.presentment.ConsentModalBottomSheet
import org.multipaz.compose.presentment.TransactionDataRendererCompose
import org.multipaz.presentment.PresentmentSelection
import org.multipaz.prompt.ConsentPromptDialogModel
import org.multipaz.prompt.PromptDialogModel
import org.multipaz.prompt.PromptDismissedException
import org.multipaz.prompt.TransactionDataRendererNotAvailableException
import org.multipaz.prompt.missingTransactionDataRenderer

@OptIn(ExperimentalMaterial3Api::class)
@Composable
Expand All @@ -29,6 +33,20 @@ fun ConsentPromptDialog(
val dialogStateValue = dialogState.value
if (dialogStateValue is PromptDialogModel.DialogShownState) {
val dialogParameters = dialogStateValue.parameters
// A renderer made for another toolkit is no renderer here: a type whose data the person must
// see is refused rather than drawn with the built-in rendering. `requestConsent` has already
// refused the cases where there is no renderer at all.
val missingRenderer = missingTransactionDataRenderer(
transactionData = dialogParameters.presentmentData.allTransactionData,
repository = dialogParameters.transactionDataRendererRepository,
isUsable = { it is TransactionDataRendererCompose },
)
if (missingRenderer != null) {
LaunchedEffect(dialogStateValue) {
dialogStateValue.resultChannel.close(TransactionDataRendererNotAvailableException(missingRenderer))
}
return
}
ConsentModalBottomSheet(
sheetState = sheetState,
requester = dialogParameters.requester,
Expand Down
24 changes: 23 additions & 1 deletion multipaz-swiftui/src/iosMain/swift/Consent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1358,7 +1358,10 @@ public final class ConsentTestController {
/// - testController: an optional ``ConsentTestController`` used by snapshot tests.
/// - onDocumentsInFocus: callback invoked with the list of documents currently in focus as the user changes selections.
/// - onConfirm: callback when the user presses the Continue button with the credentials that were selected.
/// - onCancel: callback when the user presses the Cancel button.
/// - onCancel: callback when the user presses the Cancel button. It is also called, with nothing drawn,
/// when `presentmentData` holds transaction data of a type that `TransactionType.requiresRenderer` and
/// `transactionDataRendererRepository` has no ``TransactionDataRendererSwiftUi`` for it: such data is
/// never approved with the built-in rendering.
public struct Consent: View {
let maxHeight: CGFloat
let presentmentData: PresentmentData
Expand Down Expand Up @@ -1490,6 +1493,25 @@ public struct Consent: View {
}

public var body: some View {
if let missingRenderer = TransactionDataRendererRequirementKt.missingTransactionDataRenderer(
transactionData: presentmentData.allTransactionData,
repository: transactionDataRendererRepository,
isUsable: { KotlinBoolean(bool: $0 is TransactionDataRendererSwiftUi) }
) {
Color.clear.onAppear {
Logger.shared.w(
tag: "Consent",
msg: "No usable renderer for transaction type '\(missingRenderer)', not showing consent"
)
onCancel()
}
} else {
content
}
}

@ViewBuilder
private var content: some View {
let requesterDisplayData = buildRequesterDisplayData(
requester: requester,
trustedRequesterIdentity: trustedRequesterIdentity
Expand Down
15 changes: 14 additions & 1 deletion multipaz-swiftui/src/iosMain/swift/ConsentPromptDialog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,20 @@ struct ConsentPromptDialog: View {
if state is PromptDialogModelNoDialogState<ConsentPromptDialogModel.ConsentPromptRequest, PresentmentSelection> {
data = nil
} else if state is PromptDialogModelDialogShownState<ConsentPromptDialogModel.ConsentPromptRequest, PresentmentSelection> {
data = ConsentPromptDialogData(state: state as! PromptDialogModelDialogShownState<ConsentPromptDialogModel.ConsentPromptRequest, PresentmentSelection>)
let shown = state as! PromptDialogModelDialogShownState<ConsentPromptDialogModel.ConsentPromptRequest, PresentmentSelection>
// A renderer made for another toolkit is no renderer here: a type whose data the
// person must see is refused rather than drawn with the built-in rendering.
let params = shown.parameters!
let missingRenderer = TransactionDataRendererRequirementKt.missingTransactionDataRenderer(
transactionData: params.presentmentData.allTransactionData,
repository: params.transactionDataRendererRepository,
isUsable: { KotlinBoolean(bool: $0 is TransactionDataRendererSwiftUi) }
)
if let missingRenderer {
shown.resultChannel.close(cause: TransactionDataRendererNotAvailableException(typeIdentifier: missingRenderer))
} else {
data = ConsentPromptDialogData(state: shown)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,20 @@ const val ISO_18013_TRANSACTION_DATA_NAMESPACE = "org.iso.transactiondata"
* all [TransactionType] objects must have distinct values.
* @param openId4VpMdocResponseNamespace namespace to use in `deviceSigned` namespace map in
* OpenID4VP response; defaults to [identifier].
* @param requiresRenderer whether the consent prompt must be able to draw this transaction data with
* a [org.multipaz.prompt.TransactionDataRenderer] made for its UI toolkit, and refuses to show the
* prompt when it can't. The built-in rendering shows only a heading and what the type's own
* specification may require the person to read before approving is left out, so a type whose data
* the person must see to give informed consent sets this. Defaults to `false`: the built-in
* rendering is enough.
*/
abstract class TransactionType<PayloadT: Any>(
val displayName: String,
val identifier: String,
val kbJwtResponseClaimName: String = identifier,
val iso18013RequestInfoIdentifier: String = identifier,
val openId4VpMdocResponseNamespace: String = identifier,
val requiresRenderer: Boolean = false,
) {
/**
* Returns the DeviceSigned namespace to use for the given presentment protocol.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ data class PresentmentData(
val useCases: List<PresentmentUseCase>,
) {

/**
* Every transaction data item of every match in every solution of every use-case, in order. A
* consent prompt uses it to find out which renderers it needs before it is shown.
*/
val allTransactionData: List<TransactionData<*>>
get() = useCases.flatMap { useCase ->
useCase.solutions.flatMap { solution -> solution.matches.flatMap { it.transactionData } }
}

private fun compatibleMultiIndices(
useCase: PresentmentUseCase,
candidateIndices: List<Int>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,18 @@ suspend fun PromptModel.requestPassphrase(
* @throws PromptDismissedException if the user dismissed the prompt.
* @throws PromptModelNotAvailableException if `coroutineContext` does not have [PromptModel].
* @throws PromptUiNotAvailableException if the UI layer hasn't bound any UI for [PromptModel].
* @throws TransactionDataRendererNotAvailableException if [presentmentData] holds transaction data of
* a type that [org.multipaz.documenttype.TransactionType.requiresRenderer] and
* [transactionDataRendererRepository] has no renderer for it, or none was passed. The prompt is not
* shown. A renderer made for another UI toolkit than the one bound is refused the same way by that UI.
*/
@Throws(
CancellationException::class,
IllegalStateException::class,
PromptDismissedException::class,
PromptModelNotAvailableException::class,
PromptUiNotAvailableException::class
PromptUiNotAvailableException::class,
TransactionDataRendererNotAvailableException::class
)
suspend fun PromptModel.requestConsent(
requester: Requester,
Expand All @@ -119,6 +124,10 @@ suspend fun PromptModel.requestConsent(
classifySimpleConsentFn: ClassifySimpleConsentFn = ::defaultClassifySimpleConsent,
platformConsentOptions: PlatformConsentOptions? = null,
): PresentmentSelection {
// Before anything is shown: a type whose data the person must see is never approved blind.
// Which toolkit a renderer is made for is not known here: the UI layer checks that again.
missingTransactionDataRenderer(presentmentData.allTransactionData, transactionDataRendererRepository) { true }
?.let { throw TransactionDataRendererNotAvailableException(it) }
return getDialogModel(ConsentPromptDialogModel.DialogType).displayPrompt(
parameters = ConsentPromptDialogModel.ConsentPromptRequest(
requester = requester,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ suspend fun promptModelSilentConsent(
* conveying which credentials the user selected, if multiple options are available.
* @throws PromptModelNotAvailableException if `coroutineContext` does not have [PromptModel].
* @throws PromptUiNotAvailableException if the UI layer hasn't bound any UI for [PromptModel].
* @throws TransactionDataRendererNotAvailableException if the transaction data holds a type that
* [org.multipaz.documenttype.TransactionType.requiresRenderer] and has no renderer here.
*/
suspend fun promptModelRequestConsent(
requester: Requester,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.multipaz.prompt

/**
* Thrown when a consent prompt is asked to show transaction data of a type that
* [org.multipaz.documenttype.TransactionType.requiresRenderer], and there is no
* [TransactionDataRenderer] for it that the prompt can use: none is registered under the type's
* identifier, the [TransactionDataRendererRepository] was never passed to the prompt, or the one
* registered is made for another UI toolkit.
*
* The prompt is refused rather than shown with the built-in rendering, so a person never approves
* transaction data they were not shown.
*
* @property typeIdentifier the identifier of the transaction type that has no renderer.
*/
class TransactionDataRendererNotAvailableException(val typeIdentifier: String) : Exception(
"Transaction type '$typeIdentifier' can only be approved when its data is shown, but the consent " +
"prompt has no renderer for it: register a TransactionDataRenderer made for this UI toolkit " +
"under '$typeIdentifier' and pass the repository to the prompt"
)
Loading
Loading