Skip to content
Open
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
195 changes: 169 additions & 26 deletions CredentialProvider/wasm/matcher-rs/src/openid4vp.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,69 @@
use crate::base64url::decode_base64url;
use crate::credman::CredmanApi;
use crate::json_value::JsonValue;
pub use crate::openid4vp_models::*;
use crate::reporter::report_match_result;
use nanoserde::DeJson;
use std::borrow::Cow;

fn extract_request_str<'a>(
pr: &'a ProtocolRequest,
) -> Result<&'a str, Box<dyn std::error::Error>> {
if let Some(data) = &pr.data {
match data {
ProtocolRequestData::String(s) => Ok(s.as_str()),
ProtocolRequestData::Object(obj) => {
if obj.request.is_empty() {
return Err("Missing 'request' field in data object".into());
}
Ok(obj.request.as_str())
}
}
} else if !pr.request.is_empty() {
Ok(pr.request.as_str())
} else {
Err("Missing request data".into())
}
}

fn extract_multisigned_payload(
pr: &ProtocolRequest,
) -> Result<String, Box<dyn std::error::Error>> {
let json_str = extract_request_str(pr)?;
let parsed: JsonValue = DeJson::deserialize_json(json_str)?;

let JsonValue::Object(mut map) = parsed else {
return Err("Multisigned request must be a JSON object".into());
};

let payload = if let Some(req_val) = map.shift_remove("request") {
let JsonValue::Object(mut req_map) = req_val else {
return Err("Missing 'payload' in 'request' object".into());
};
let Some(JsonValue::String(p)) = req_map.shift_remove("payload") else {
return Err("Missing 'payload' in 'request' object".into());
};
p
} else {
let Some(JsonValue::String(p)) = map.shift_remove("payload") else {
return Err("Missing 'payload' field in multisigned request".into());
};
p
};

if payload.is_empty() {
return Err("Empty payload in multisigned request".into());
}

Ok(payload)
}

fn parse_protocol_request_data<'a>(
pr: &'a ProtocolRequest,
) -> Result<Cow<'a, OpenId4VpData>, Box<dyn std::error::Error>> {
if pr.protocol == "openid4vp-v1-signed" {
log::debug!("Handling signed OpenID4VP request");
let jws: &'a str = if let Some(data) = &pr.data {
match data {
ProtocolRequestData::String(s) => s,
ProtocolRequestData::Object(obj) => {
if obj.request.is_empty() {
return Err("Missing 'request' field in signed data object".into());
}
&obj.request
}
}
} else if !pr.request.is_empty() {
&pr.request
} else {
return Err("Missing signed request data".into());
};
let jws = extract_request_str(pr)?;

let parts: Vec<&str> = jws.split('.').collect();
if parts.len() < 2 {
Expand All @@ -36,7 +75,14 @@ fn parse_protocol_request_data<'a>(
return Ok(Cow::Owned(DeJson::deserialize_json(std::str::from_utf8(
&decoded,
)?)?));
}
} else if pr.protocol == "openid4vp-v1-multisigned" {
log::debug!("Handling multisigned OpenID4VP request");
let payload_str = extract_multisigned_payload(pr)?;
let decoded = decode_base64url(&payload_str)?;
return Ok(Cow::Owned(DeJson::deserialize_json(std::str::from_utf8(
&decoded,
)?)?));
}

log::debug!("Handling unsigned OpenID4VP request");
if let Some(data) = &pr.data {
Expand Down Expand Up @@ -103,18 +149,34 @@ pub fn openid4vp_main(credman: &mut impl CredmanApi) -> Result<(), Box<dyn std::
};
log::info!("Found {} protocol requests", protocol_requests.len());

for (i, pr) in protocol_requests.iter().enumerate() {
log::debug!("Processing request {}: protocol={}", i, pr.protocol);
if pr.protocol != "openid4vp-v1-unsigned" && pr.protocol != "openid4vp-v1-signed" {
log::warn!("Unsupported protocol: {}", pr.protocol);
continue;
}
for target_protocol in &registry.supported_protocols {
log::debug!("Matching requests for protocol={}", target_protocol);
for (i, pr) in protocol_requests.iter().enumerate() {
if pr.protocol != *target_protocol {
continue;
}
log::debug!("Processing request {}: protocol={}", i, pr.protocol);
if pr.protocol != "openid4vp-v1-unsigned"
&& pr.protocol != "openid4vp-v1-signed"
&& pr.protocol != "openid4vp-v1-multisigned"
{
log::warn!("Unsupported protocol: {}", pr.protocol);
continue;
}

let data_json = parse_protocol_request_data(pr)?;
let query = data_json.dcql_query.as_ref().ok_or("Missing dcql_query")?;
let match_result = crate::dcql::dcql_query(query, &registry);
let data_json = parse_protocol_request_data(pr)?;
let query = data_json.dcql_query.as_ref().ok_or("Missing dcql_query")?;
let match_result = crate::dcql::dcql_query(query, &registry);

report_match_result(credman, &match_result, i, &data_json, &matcher_data_buffer)?;
let has_matches = !match_result.matched_credential_sets.is_empty()
|| match_result.inline_issuance.is_some();
if has_matches {
// If there are multiple requests of the same preferred protocol,
// we only process the first request that yields a match.
report_match_result(credman, &match_result, i, &data_json, &matcher_data_buffer)?;
return Ok(());
}
}
}

log::info!("OpenID4VP matching process completed");
Expand Down Expand Up @@ -160,6 +222,28 @@ mod tests {
assert!(err.to_string().contains("Missing unsigned request data"));
}

#[test]
fn test_parse_protocol_request_data_multisigned_valid() {
let json = r#"{
"protocol": "openid4vp-v1-multisigned",
"data": "{\"request\": {\"payload\": \"eyJkY3FsX3F1ZXJ5Ijp7ImNyZWRlbnRpYWxzIjpbXX19\"}}"
}"#;
let pr: ProtocolRequest = DeJson::deserialize_json(json).unwrap();
let data = parse_protocol_request_data(&pr).unwrap();
assert!(data.dcql_query.is_some());
}

#[test]
fn test_parse_protocol_request_data_multisigned_invalid_payload() {
let json = r#"{
"protocol": "openid4vp-v1-multisigned",
"data": "{\"request\": {}}"
}"#;
let pr: ProtocolRequest = DeJson::deserialize_json(json).unwrap();
let err = parse_protocol_request_data(&pr).unwrap_err();
assert!(err.to_string().contains("Missing 'payload'"));
}

use crate::test_utils::*;

macro_rules! define_test {
Expand Down Expand Up @@ -208,6 +292,7 @@ mod tests {
);
define_test!(tc30_parse_v1_unsigned, "TC30_ParseV1Unsigned");
define_test!(tc31_parse_v1_signed, "TC31_ParseV1Signed");
define_test!(tc42_parse_v1_multisigned, "TC42_ParseV1Multisigned");
define_test!(tc32_extract_payment_sca1, "TC32_ExtractPaymentSca1");
define_test!(tc33_extract_payment_details, "TC33_ExtractPaymentDetails");
define_test!(tc34_extract_payment_generic, "TC34_ExtractPaymentGeneric");
Expand All @@ -231,4 +316,62 @@ mod tests {
}
run_openid4vp_test("TC37_WasmMetadataText", Some(&registry_json));
}

/// Replaces the `"supported_protocols": [...]` array inside a JSON registry string
/// with the provided slice of protocol strings.
fn replace_supported_protocols(registry_json: &str, protocols: &[&str]) -> String {
let start_key = "\"supported_protocols\": [";
if let (Some(start_idx), Some(end_rel)) = (
registry_json.find(start_key),
registry_json.find(start_key).and_then(|idx| registry_json[idx..].find("],")),
) {
let end_idx = start_idx + end_rel + 2;
let formatted_protocols = protocols
.iter()
.map(|p| format!(" \"{}\"", p))
.collect::<Vec<_>>()
.join(",\n");
let new_section = format!("\"supported_protocols\": [\n{}\n ],", formatted_protocols);
let mut result = String::with_capacity(registry_json.len() + new_section.len());
result.push_str(&registry_json[..start_idx]);
result.push_str(&new_section);
result.push_str(&registry_json[end_idx..]);
result
} else {
registry_json.to_string()
}
}

#[test]
fn tc40_match_most_preferred_supported_protocol_available() {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let testdata_dir = std::path::PathBuf::from(manifest_dir).join("testdata");
let registry_json = std::fs::read_to_string(testdata_dir.join("registry.json")).unwrap();

// Inject custom supported_protocols preference order: signed then unsigned
let modified_registry = replace_supported_protocols(
&registry_json,
&["openid4vp-v1-signed", "openid4vp-v1-unsigned"],
);

run_openid4vp_test(
"TC40_MatchMostPreferredSupportedProtocolAvailable",
Some(&modified_registry),
);
}

#[test]
fn tc41_no_match_if_no_requests_for_supported_protocols() {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let testdata_dir = std::path::PathBuf::from(manifest_dir).join("testdata");
let registry_json = std::fs::read_to_string(testdata_dir.join("registry.json")).unwrap();

// Inject custom supported_protocols containing only "openid4vp-v1-signed"
let modified_registry = replace_supported_protocols(&registry_json, &["openid4vp-v1-signed"]);

run_openid4vp_test(
"TC41_NoMatchIfNoRequestsForSupportedProtocols",
Some(&modified_registry),
);
}
}
2 changes: 2 additions & 0 deletions CredentialProvider/wasm/matcher-rs/src/openid4vp_models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ pub struct DcqlCredentialSet {
#[nserde(default)]
pub struct Registry {
pub credentials: RegistryCredentials,
#[nserde(default)]
pub supported_protocols: Vec<String>,
}

#[derive(DeJson, Debug, Clone, Default)]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
{
"entrySets": {
"req:1;null": {
"entries": {
"0": {
"mdoc_cred_1": {
"additional_info": "",
"credId": "mdoc_cred_1",
"disclaimer": "",
"fields": [
[
"Family Name",
"Doe"
],
[
"Given Name",
"John"
],
[
"Age",
""
],
[
"Over 21",
"Yes"
]
],
"merchant_name": "",
"metadata_display_text": "",
"subtitle": "",
"title": "John's Driving License",
"transaction_amount": "",
"type": "Verification",
"warning": ""
},
"mdoc_cred_underage": {
"additional_info": "",
"credId": "mdoc_cred_underage",
"disclaimer": "",
"fields": [
[
"Age",
""
],
[
"Over 21",
"Yes"
]
],
"merchant_name": "",
"metadata_display_text": "",
"subtitle": "",
"title": "Underage License",
"transaction_amount": "",
"type": "Verification",
"warning": ""
},
"mdoc_cred_3": {
"additional_info": "",
"credId": "mdoc_cred_3",
"disclaimer": "",
"fields": [
[
"Family Name",
""
],
[
"Given Name",
""
],
[
"Age",
""
],
[
"Over 21",
""
]
],
"merchant_name": "",
"metadata_display_text": "",
"subtitle": "",
"title": "Alice's Driving License",
"transaction_amount": "",
"type": "Verification",
"warning": ""
},
"mdoc_cred_4": {
"additional_info": "",
"credId": "mdoc_cred_4",
"disclaimer": "",
"fields": [
[
"Family Name",
""
],
[
"Given Name",
""
],
[
"Age",
""
],
[
"Over 21",
""
]
],
"merchant_name": "",
"metadata_display_text": "",
"subtitle": "",
"title": "Jane's Driving License",
"transaction_amount": "",
"type": "Verification",
"warning": ""
}
}
},
"setId": "req:1;null",
"setLength": 1
}
},
"standaloneEntries": [
{
"additional_info": "",
"credId": "issuance_mdl_1",
"disclaimer": "",
"fields": [],
"merchant_name": "",
"metadata_display_text": "",
"subtitle": "From your local DMV",
"title": "Get a New mDL",
"transaction_amount": "",
"type": "InlineIssuance",
"warning": ""
}
]
}
Loading