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 @@ -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
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
28 changes: 28 additions & 0 deletions multipaz-utopia/scripts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# AP2 interoperability check

`DelegateAp2InteropTest` answers AP2 delegation requests through a real OpenID4VP
presentment and writes each response to `build/ap2-interop/<scenario>.json`.
`verify_ap2_interop.py` runs every one through the verifier in AP2's own Python SDK
(`ap2.sdk.sdjwt.chain.verify_chain`), so "AP2's SDK verifies our responses" can be
re-run by anyone.

It checks, per scenario, that the SDK accepts the whole chain (issuer signature,
`typ`, `sd_hash`, key binding, `cnf` rules), that the KB-JWT carries the expected
`nonce` and `aud` (the SDK enforces them only on a terminal hop), and that the
mandates the SDK resolves, with selectively disclosed terms filled in, are the ones
requested. It exits non-zero on any failure.

```bash
# 1. Write the responses.
./gradlew :multipaz-utopia:jvmTest --tests '*DelegateAp2InteropTest' -Pdisable.web.targets=true

# 2. Check them against AP2 v0.2.0 (commit b4587ac1d055888a73b4b21750973cffba961793),
# the release the schemas in src/jvmTest/resources/ap2-schemas come from.
git clone --depth 1 --branch v0.2.0 https://github.com/google-agentic-commerce/AP2.git /tmp/AP2
python3 -m venv /tmp/ap2-venv
/tmp/ap2-venv/bin/pip install cryptography==46.0.5 jwcrypto==1.5.6 pydantic==2.12.5 sd-jwt==0.10.4
PYTHONPATH=/tmp/AP2/code/sdk/python /tmp/ap2-venv/bin/python \
multipaz-utopia/scripts/verify_ap2_interop.py multipaz-utopia/build/ap2-interop
```

The versions are those AP2 pins in its `pyproject.toml`.
121 changes: 121 additions & 0 deletions multipaz-utopia/scripts/verify_ap2_interop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Verifies the responses written by DelegateAp2InteropTest with AP2's own Python SDK.

`DelegateAp2InteropTest` answers AP2 delegation requests through a real OpenID4VP
presentment and writes each response to `multipaz-utopia/build/ap2-interop/<scenario>.json`.
This script feeds every one to the SDK's `verify_chain`, the verifier a merchant or an agent
runs, and checks that the mandates it resolves are the ones that were requested.

Usage (see the README next to this script):

PYTHONPATH=<AP2>/code/sdk/python python3 verify_ap2_interop.py [build/ap2-interop]

Needs `cryptography`, `jwcrypto`, `pydantic` and `sd-jwt` (AP2's SDK dependencies). Exits
non-zero if any scenario fails, so it can gate a CI job.
"""

import base64
import hashlib
import json
import pathlib
import sys

from jwcrypto.jwk import JWK

from ap2.sdk.sdjwt import chain
from ap2.sdk.sdjwt.common import parse_token

COMPACT_JWT_PARTS = 3


def canonical_segment(segment: str, index: int, total: int) -> str:
"""Restores the trailing `~` that splitting on `~~` strips (as ap2.sdk.mandate does)."""
if index == total - 1 or segment.endswith('~'):
return segment
if len(segment.rsplit('~', 1)[-1].split('.')) == COMPACT_JWT_PARTS:
return segment
return segment + '~'


def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b'=').decode()


def resolve(value, disclosures: dict[str, list]):
"""Replaces RFC 9901 digests with what their disclosures reveal, as a verifier does."""
if isinstance(value, list):
out = []
for item in value:
if isinstance(item, dict) and list(item) == ['...']:
out.append(resolve(disclosures[item['...']][1], disclosures))
else:
out.append(resolve(item, disclosures))
return out
if isinstance(value, dict):
out = {k: resolve(v, disclosures) for k, v in value.items() if k != '_sd'}
for digest in value.get('_sd', []):
_salt, name, revealed = disclosures[digest]
out[name] = resolve(revealed, disclosures)
return out
return value


def verify(scenario: dict) -> list[str]:
"""Returns what is wrong with one response; empty when AP2's SDK accepts it."""
segments = scenario['vp_token'].split('~~')
tokens = [
parse_token(canonical_segment(s, i, len(segments)))
for i, s in enumerate(segments)
]
issuer_key = JWK(**scenario['issuer_jwk'])
payloads = chain.verify_chain(
tokens,
lambda _token: issuer_key,
expected_aud=scenario['expected_aud'],
expected_nonce=scenario['expected_nonce'],
)
problems = []
# The SDK enforces the nonce and audience only on a terminal hop (`kb+sd-jwt`); an
# intermediate one (`kb-sd-jwt+kb`) is not checked, so the verifier must do it.
kb_jwt = next(p for p in segments[-1].split('~') if len(p.split('.')) == COMPACT_JWT_PARTS)
kb_body = kb_jwt.split('.')[1]
kb_payload = json.loads(base64.urlsafe_b64decode(kb_body + '=' * (-len(kb_body) % 4)))
for claim, expected in (('nonce', scenario['expected_nonce']), ('aud', scenario['expected_aud'])):
if kb_payload.get(claim) != expected:
problems.append(f"KB-JWT '{claim}' is {kb_payload.get(claim)!r}, expected {expected!r}")
disclosures = {}
for disclosure in scenario.get('delegate_disclosures', []):
padded = disclosure + '=' * (-len(disclosure) % 4)
decoded = json.loads(base64.urlsafe_b64decode(padded))
disclosures[b64url(hashlib.sha256(disclosure.encode()).digest())] = decoded
requested = [resolve(mandate, disclosures) for mandate in scenario['mandates']]
# The terminal hop's resolved items are the delegated mandates, in request order.
resolved = payloads[-len(requested):]
if resolved != requested:
problems.append(f'resolved mandates differ from the requested ones: {resolved}')
return problems


def main() -> int:
directory = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else 'build/ap2-interop')
files = sorted(directory.glob('*.json'))
if not files:
print(f'no responses in {directory}: run DelegateAp2InteropTest first', file=sys.stderr)
return 2
failed = 0
for path in files:
scenario = json.loads(path.read_text())
try:
problems = verify(scenario)
except Exception as err: # noqa: BLE001 (any rejection is a failure to report)
problems = [f'{type(err).__name__}: {err}']
print(f'{"FAIL" if problems else "pass"} {scenario["scenario"]}')
for problem in problems:
print(f' {problem}')
failed += bool(problems)
print(f'\n{len(files) - failed}/{len(files)} scenarios verified by AP2\'s SDK')
return 1 if failed else 0


if __name__ == '__main__':
sys.exit(main())
Loading
Loading