Modern Apps git

← Modern-Apps.git

euicc: add protocol Rust tests

Commit
6115277d35e9f5814e05824013e1ed98149b27d6
Author
Vayun Mathur <[email protected]>
When
2026-11-18 16:13 UTC (17 days ago)
Parents
6139976
Raise euicc line coverage from 65.7% to 81.1% with 20 new tests over es9p error handling, download session/install rules, and JNI chunk reassembly; behavior-preserving extractions (injected transport/APDU) made the JVM-bound orchestration testable. Verified with cargo test -p euicc (107 passed) and cargo llvm-cov (81.10%).

Diff

euicc/src/main/rust/src/download.rs
diff --git a/euicc/src/main/rust/src/download.rs b/euicc/src/main/rust/src/download.rsindex 3611a2b2d5..31539714ee 100644--- a/euicc/src/main/rust/src/download.rs+++ b/euicc/src/main/rust/src/download.rs@@ -11,7 +11,7 @@ //! [`parse_activation_code`], [`hash_confirmation_code`], and //! [`es10b::extract_transaction_id`]. -use jni::{Env, EnvUnowned, jni_sig, jni_str};+use jni::Env;  use crate::activation_code::{ActivationCode, hash_confirmation_code, parse_activation_code}; pub use crate::activation_code::DownloadOptions;@@ -28,6 +28,124 @@ fn pkid_value(field: &[u8]) -> &[u8] {  /// Whether the server's chosen CI key appears in the eUICC's verification list /// (hex of the raw field or of its unwrapped value).+/// Errors when the eUICC trusts some CI keys but not the server's chosen one.+fn check_ci_key(info: &es10::EuiccInfo1, field: &[u8]) -> Result<(), String> {+    if !info.ci_pkid_verification.is_empty() && !ci_key_known(&info.ci_pkid_verification, field) {+        return Err(format!(+            "server uses CI key {} unknown to this eUICC (eUICC trusts: {})",+            es10::hex(&pkid_value(field)),+            info.ci_pkid_verification.join(", "),+        ));+    }+    Ok(())+}++/// Builds the session from the two ES9+ replies (metadata + cc flag parsed).+fn build_session(+    ac: ActivationCode,+    r1: es9p::InitiateAuthResult,+    r2: es9p::AuthenticateClientResult,+    transaction_id_bin: Vec<u8>,+    options: &DownloadOptions,+) -> Result<DownloadSession, String> {+    let metadata = es10b::parse_profile_metadata(&r2.profile_metadata)?;+    let cc_required = ac.confirmation_code_required || es10b::cc_required(&r2.smdp_signed2);+    Ok(DownloadSession {+        activation: ac,+        transaction_id: r1.transaction_id,+        transaction_id_bin,+        metadata,+        cc_required,+        options: options.clone(),+        server_signed2: r2.smdp_signed2,+        server_signature2: r2.smdp_signature2,+        server_certificate2: r2.smdp_certificate,+    })+}++/// Explicit (non-empty) code wins over the stored one; a required-but-absent+/// code is an error naming the remedy.+fn resolve_confirmation_code<'a>(+    cc_required: bool,+    explicit: Option<&'a str>,+    stored: Option<&'a str>,+) -> Result<Option<&'a str>, String> {+    let code = explicit.filter(|c| !c.is_empty()).or(stored);+    if cc_required && code.is_none() {+        return Err(+            "This profile needs a confirmation code (ccRequiredFlag is set) — supply it and retry"+                .to_string(),+        );+    }+    Ok(code)+}++/// Streams BPP segments through `transmit`, reporting progress and aborting+/// on the first typed mid-stream install error. Returns the last response.+fn install_segments<E, F, P>(+    env: &mut E,+    segments: &[Vec<u8>],+    transmit: &mut F,+    progress: &mut P,+) -> Result<Vec<u8>, String>+where+    F: FnMut(&mut E, &[u8]) -> Result<Vec<u8>, String>,+    P: FnMut(&mut E, usize, usize) -> bool,+{+    let total = segments.len();+    let mut last = Vec::new();+    for (i, segment) in segments.iter().enumerate() {+        last = transmit(env, segment)+            .map_err(|e| format!("LoadBoundProfilePackage segment {}/{total}: {e}", i + 1))?;+        if !progress(env, i + 1, total) {+            return Err("Download cancelled".to_string());+        }+        if i + 1 < total {+            if let Ok(probe) = es10b::parse_install_result(&last) {+                if !probe.success && (probe.bpp_command_id.is_some() || probe.error_reason.is_some()) {+                    return Err(probe.message);+                }+            }+        }+    }+    Ok(last)+}++/// AuthenticateServer request for the server's authentication material.+fn authenticate_server_request(+    r1: &es9p::InitiateAuthResult,+    matching_id: &str,+    options: &DownloadOptions,+) -> Vec<u8> {+    let tac = options.tac.unwrap_or(es10b::DEFAULT_TAC);+    let ctx = es10b::build_ctx_params1(matching_id, &tac, options.imei.as_deref());+    es10b::build_authenticate_server(+        &r1.server_signed1,+        &r1.server_signature1,+        &r1.euicc_ci_pkid,+        &r1.server_certificate,+        &ctx,+    )+}++/// PrepareDownload request, carrying `hashCc` when a code was supplied.+fn prepare_download_request(session: &DownloadSession, code: Option<&str>) -> Result<Vec<u8>, String> {+    let tx_bin = es10b::extract_transaction_id(&session.server_signed2)?;+    let hash = code.map(|c| hash_confirmation_code(c, &tx_bin));+    let hash_ref = hash.as_ref().map(|h| &h[..]);+    Ok(es10b::build_prepare_download(+        &session.server_signed2,+        &session.server_signature2,+        hash_ref,+        &session.server_certificate2,+    ))+}++/// Delivery target for a notification: its own address, else the SM-DP+.+fn notification_target<'a>(address: &'a str, smdp: &'a str) -> &'a str {+    if address.is_empty() { smdp } else { address }+}+ fn ci_key_known(verification_list: &[String], field: &[u8]) -> bool {     let raw_hex = es10::hex(field);     let inner_hex = es10::hex(pkid_value(field));@@ -142,28 +260,12 @@ pub fn authenticate(     // public key identifiers, safe to report. Skip the check when the eUICC     // gave no list (never block a download on a parser gap).     if let Ok(info) = es10::parse_euicc_info1(&euicc_info1) {-        if !info.ci_pkid_verification.is_empty()-            && !ci_key_known(&info.ci_pkid_verification, &r1.euicc_ci_pkid)-        {-            return Err(format!(-                "server uses CI key {} unknown to this eUICC (eUICC trusts: {})",-                es10::hex(&pkid_value(&r1.euicc_ci_pkid)),-                info.ci_pkid_verification.join(", "),-            ));-        }+        check_ci_key(&info, &r1.euicc_ci_pkid)?;     }      // 3. eUICC authenticates the server and signs its own material. TAC     // defaults to lpac's constant; IMEI is user-supplied and optional.-    let tac = options.tac.unwrap_or(es10b::DEFAULT_TAC);-    let ctx = es10b::build_ctx_params1(&ac.matching_id, &tac, options.imei.as_deref());-    let auth_req = es10b::build_authenticate_server(-        &r1.server_signed1,-        &r1.server_signature1,-        &r1.euicc_ci_pkid,-        &r1.server_certificate,-        &ctx,-    );+    let auth_req = authenticate_server_request(&r1, &ac.matching_id, options);     let auth_resp = store_data(env, &auth_req).map_err(|e| format!("AuthenticateServer: {e}"))?;      // Binary transaction id for hashCc / CancelSession (the JSON string form@@ -173,20 +275,7 @@ pub fn authenticate(     // 4. SM-DP+ binds the profile to this eUICC.     let r2 = es9p::authenticate_client(&ac.smdp, &r1.transaction_id, &auth_resp)?; -    let metadata = es10b::parse_profile_metadata(&r2.profile_metadata)?;-    let cc_required = ac.confirmation_code_required || es10b::cc_required(&r2.smdp_signed2);--    Ok(DownloadSession {-        activation: ac,-        transaction_id: r1.transaction_id,-        transaction_id_bin,-        metadata,-        cc_required,-        options: options.clone(),-        server_signed2: r2.smdp_signed2,-        server_signature2: r2.smdp_signature2,-        server_certificate2: r2.smdp_certificate,-    })+    build_session(ac, r1, r2, transaction_id_bin, options) }  /// Finishes an authenticated session: PrepareDownload (with `hashCc` when a@@ -202,24 +291,12 @@ pub fn finish_download(     progress: &mut dyn ProgressCallback, ) -> Result<es10b::InstallResult, String> {     // 5. eUICC prepares to receive the profile.-    let code = confirmation_code-        .filter(|c| !c.is_empty())-        .or(session.options.confirmation_code.as_deref());-    if session.cc_required && code.is_none() {-        return Err(-            "This profile needs a confirmation code (ccRequiredFlag is set) — supply it and retry"-                .to_string(),-        );-    }-    let tx_bin = es10b::extract_transaction_id(&session.server_signed2)?;-    let hash = code.map(|c| hash_confirmation_code(c, &tx_bin));-    let hash_ref = hash.as_ref().map(|h| &h[..]);-    let prep_req = es10b::build_prepare_download(-        &session.server_signed2,-        &session.server_signature2,-        hash_ref,-        &session.server_certificate2,-    );+    let code = resolve_confirmation_code(+        session.cc_required,+        confirmation_code,+        session.options.confirmation_code.as_deref(),+    )?;+    let prep_req = prepare_download_request(session, code)?;     let prep_resp = store_data(env, &prep_req).map_err(|e| format!("PrepareDownload: {e}"))?;      // 6. Fetch the (encrypted) Bound Profile Package.@@ -234,26 +311,11 @@ pub fn finish_download(     // ProfileInstallationResult — but a mid-stream BF37 error must stop the     // loop immediately so one failure does not cascade.     let segments = es10b::segment_bpp(&bpp)?;-    let total = segments.len();-    let mut last = Vec::new();-    for (i, segment) in segments.iter().enumerate() {-        last = store_data(env, segment)-            .map_err(|e| format!("LoadBoundProfilePackage segment {}/{total}: {e}", i + 1))?;-        if !progress.on_progress(env, i + 1, total) {-            return Err("Download cancelled".to_string());-        }-        // Intermediate BF37 error results abort the stream (lpac parity): a-        // typed mid-stream failure must stop the loop, not cascade.-        if i + 1 < total {-            if let Ok(probe) = es10b::parse_install_result(&last) {-                if !probe.success-                    && (probe.bpp_command_id.is_some() || probe.error_reason.is_some())-                {-                    return Err(probe.message);-                }-            }-        }-    }+    // Intermediate BF37 error results abort the stream inside install_segments+    // (lpac parity): a typed mid-stream failure must not cascade.+    let mut transmit = |e: &mut Env, segment: &[u8]| store_data(e, segment);+    let mut prog = |e: &mut Env, done: usize, total: usize| progress.on_progress(e, done, total);+    let last = install_segments(env, &segments, &mut transmit, &mut prog)?;     let result = es10b::parse_install_result(&last)?;      // 8. Deliver the install notification (best-effort): retrieve the pending@@ -276,24 +338,54 @@ fn notification_seq(seq_number: i64) -> Option<u32> { }  fn deliver_notification(env: &mut Env, smdp: &str, seq_number: i64, fallback: &[u8]) {+    let mut retrieve = |e: &mut Env, seq: u32| {+        store_data(e, &es10b::build_retrieve_notification(seq))+            .and_then(|resp| es10b::parse_retrieved_notification(&resp))+    };+    let mut post_fallback = |addr: &str, blob: &[u8]| es9p::handle_notification(addr, blob);+    let mut post_at = |addr: &str, blob: &[u8]| es9p::handle_notification_at(addr, blob);+    let mut remove = |e: &mut Env, seq: u32| {+        let _ = store_data(e, &es10::build_remove_notification(seq))+            .and_then(|resp| es10::parse_remove_result(&resp));+    };+    deliver_notification_with(+        env, smdp, seq_number, fallback, &mut retrieve, &mut post_fallback, &mut post_at, &mut remove,+    );+}++/// Notification delivery with transport injected (host-testable core of+/// [`deliver_notification`]).+#[allow(clippy::too_many_arguments)]+fn deliver_notification_with<E, R, P, A, D>(+    env: &mut E,+    smdp: &str,+    seq_number: i64,+    fallback: &[u8],+    retrieve: &mut R,+    post_fallback: &mut P,+    post_at: &mut A,+    remove: &mut D,+) where+    R: FnMut(&mut E, u32) -> Result<(String, Vec<u8>), String>,+    P: FnMut(&str, &[u8]) -> Result<(), String>,+    A: FnMut(&str, &[u8]) -> Result<(), String>,+    D: FnMut(&mut E, u32),+{     let Some(seq) = notification_seq(seq_number) else {         // No sequence to retrieve by: post the raw result to the download         // server, like the retrieve-failure fallback below, and remove nothing.-        let _ = es9p::handle_notification(smdp, fallback);+        let _ = post_fallback(smdp, fallback);         return;     };-    let Ok(retrieved) = store_data(env, &es10b::build_retrieve_notification(seq))-        .and_then(|resp| es10b::parse_retrieved_notification(&resp))-    else {+    let Ok(retrieved) = retrieve(env, seq) else {         // Fall back to posting the raw result to the download server.-        let _ = es9p::handle_notification(smdp, fallback);+        let _ = post_fallback(smdp, fallback);         return;     };     let (address, pending) = retrieved;-    let target = if address.is_empty() { smdp } else { address.as_str() };-    if es9p::handle_notification_at(target, &pending).is_ok() {-        let _ = store_data(env, &es10::build_remove_notification(seq))-            .and_then(|resp| es10::parse_remove_result(&resp));+    let target = notification_target(&address, smdp);+    if post_at(target, &pending).is_ok() {+        remove(env, seq);     } } 
euicc/src/main/rust/src/download_tests.rs
diff --git a/euicc/src/main/rust/src/download_tests.rs b/euicc/src/main/rust/src/download_tests.rsindex d4ea111959..335a0b3fd4 100644--- a/euicc/src/main/rust/src/download_tests.rs+++ b/euicc/src/main/rust/src/download_tests.rs@@ -29,3 +29,138 @@ fn notification_seq_bounds() {     assert_eq!(notification_seq(i64::from(u32::MAX)), Some(u32::MAX));     assert_eq!(notification_seq(-2), None); }++#[test]+fn check_ci_key_rules() {+    let info = crate::es10::EuiccInfo1 { svn: "2.2.0".into(), ci_pkid_verification: vec!["aabb".into()], ci_pkid_signing: vec![] };+    assert!(check_ci_key(&info, &[0xAA, 0xBB]).is_ok());+    let err = check_ci_key(&info, &[0xDD]).unwrap_err();+    assert!(err.contains("unknown to this eUICC") && err.contains("aabb"), "{err}");+    let empty = crate::es10::EuiccInfo1 { svn: String::new(), ci_pkid_verification: vec![], ci_pkid_signing: vec![] };+    assert!(check_ci_key(&empty, &[0xDD]).is_ok(), "no list never blocks");+}++#[test]+fn resolve_confirmation_code_rules() {+    assert_eq!(resolve_confirmation_code(false, None, None).unwrap(), None);+    assert_eq!(resolve_confirmation_code(false, Some("1234"), Some("9999")).unwrap(), Some("1234"));+    assert_eq!(resolve_confirmation_code(true, Some(""), Some("9999")).unwrap(), Some("9999"), "empty explicit falls back");+    assert_eq!(resolve_confirmation_code(true, None, Some("9999")).unwrap(), Some("9999"));+    assert!(resolve_confirmation_code(true, Some(""), None).unwrap_err().contains("confirmation code"));+    assert!(resolve_confirmation_code(true, None, None).is_err());+}++#[test]+fn build_session_parses_metadata_and_cc() {+    let ac = ActivationCode { smdp: "smdp.example.com".into(), matching_id: "M1".into(), confirmation_code_required: false };+    let mut meta_body = crate::asn1::tlv(0x91, b"Carrier");+    meta_body.extend(crate::asn1::tlv(0x92, b"Plan"));+    let r1 = crate::es9p::InitiateAuthResult { transaction_id: "tx-9".into(), server_signed1: vec![1], server_signature1: vec![2], euicc_ci_pkid: vec![3], server_certificate: vec![4] };+    // smdpSigned2: SEQUENCE { 80 tx, 01 FF } => cc required.+    let mut signed_inner = crate::asn1::tlv(0x80, &[0x01]);+    signed_inner.extend(crate::asn1::tlv(0x01, &[0xFF]));+    let r2 = crate::es9p::AuthenticateClientResult {+        profile_metadata: crate::asn1::tlv(0xBF25, &meta_body),+        smdp_signed2: crate::asn1::tlv(0x30, &signed_inner),+        smdp_signature2: vec![5], smdp_certificate: vec![6],+    };+    let s = build_session(ac, r1, r2, vec![0x01], &DownloadOptions::default()).unwrap();+    assert_eq!(s.transaction_id, "tx-9");+    assert!(s.cc_required);+    assert_eq!(s.metadata.service_provider, "Carrier");+    assert_eq!(s.metadata.profile_name, "Plan");+    // Bad metadata propagates.+    let r1b = crate::es9p::InitiateAuthResult { transaction_id: "t".into(), server_signed1: vec![], server_signature1: vec![], euicc_ci_pkid: vec![], server_certificate: vec![] };+    let r2b = crate::es9p::AuthenticateClientResult { profile_metadata: vec![], smdp_signed2: vec![], smdp_signature2: vec![], smdp_certificate: vec![] };+    let acb = ActivationCode { smdp: "s".into(), matching_id: "m".into(), confirmation_code_required: true };+    assert!(build_session(acb, r1b, r2b, vec![], &DownloadOptions::default()).is_err());+}++#[test]+fn install_segments_streaming_rules() {+    let segs = vec![vec![1u8], vec![2], vec![3]];+    // Happy path: last response returned, progress sees each segment.+    let mut seen: Vec<usize> = Vec::new();+    let mut tx = |_: &mut (), s: &[u8]| Ok::<Vec<u8>, String>(vec![s[0] + 10]);+    let mut prog = |_: &mut (), d: usize, _t: usize| { seen.push(d); true };+    assert_eq!(install_segments(&mut (), &segs, &mut tx, &mut prog).unwrap(), vec![13]);+    assert_eq!(seen, vec![1, 2, 3]);+    // Empty segment list returns empty last response.+    let mut tx2 = |_: &mut (), _s: &[u8]| Ok::<Vec<u8>, String>(vec![]);+    let mut prog2 = |_: &mut (), _d: usize, _t: usize| true;+    assert_eq!(install_segments(&mut (), &[], &mut tx2, &mut prog2).unwrap(), Vec::<u8>::new());+    // Transmit failure names the segment.+    let mut tx3 = |_: &mut (), _s: &[u8]| Err::<Vec<u8>, String>("boom".into());+    assert!(install_segments(&mut (), &segs, &mut tx3, &mut prog2).unwrap_err().contains("segment 1/3: boom"));+    // Progress veto cancels after first segment.+    let mut tx4 = |_: &mut (), s: &[u8]| Ok::<Vec<u8>, String>(vec![s[0]]);+    let mut veto = |_: &mut (), _d: usize, _t: usize| false;+    assert_eq!(install_segments(&mut (), &segs, &mut tx4, &mut veto).unwrap_err(), "Download cancelled");+    // Mid-stream typed BF37 error aborts; same blob as last segment does not.+    let err_blob = crate::asn1::tlv(0xBF37, &crate::asn1::tlv(0xBF27, &crate::asn1::tlv(0xA2, &crate::asn1::tlv(0xA1, &crate::asn1::tlv(0x80, &[0x03])))));+    let mut calls = 0usize;+    let mut tx5 = |_: &mut (), _s: &[u8]| { calls += 1; Ok::<Vec<u8>, String>(err_blob.clone()) };+    let mut prog3 = |_: &mut (), _d: usize, _t: usize| true;+    assert!(install_segments(&mut (), &segs, &mut tx5, &mut prog3).unwrap_err().contains("store_metadata2"));+    assert_eq!(calls, 1, "must abort on first segment");+    let mut tx6 = |_: &mut (), _s: &[u8]| Ok::<Vec<u8>, String>(err_blob.clone());+    assert_eq!(install_segments(&mut (), &segs[..1], &mut tx6, &mut prog3).unwrap(), err_blob);+}++#[test]+fn notification_target_prefers_own_address() {+    assert_eq!(notification_target("rsp.example.com", "smdp.example.com"), "rsp.example.com");+    assert_eq!(notification_target("", "smdp.example.com"), "smdp.example.com");+}++#[test]+fn request_builders_embed_inputs() {+    let r1 = crate::es9p::InitiateAuthResult { transaction_id: "tx".into(), server_signed1: vec![0x30, 0x00], server_signature1: vec![0x02], euicc_ci_pkid: vec![0x03], server_certificate: vec![0x04] };+    let req = authenticate_server_request(&r1, "MATCH-1", &DownloadOptions::default());+    assert!(!req.is_empty());+    let with_imei = DownloadOptions { confirmation_code: None, tac: Some([1, 2, 3, 4]), imei: Some("490154203237518".into()) };+    assert!(!authenticate_server_request(&r1, "MATCH-1", &with_imei).is_empty());+    // PrepareDownload: no code => request builds; bad signed2 => tx error.+    let mut s = DownloadSession::for_test("tx-prep");+    let mut signed_inner = crate::asn1::tlv(0x80, &[0xDE, 0xAD]);+    signed_inner.extend(crate::asn1::tlv(0x01, &[0x00]));+    s.server_signed2 = crate::asn1::tlv(0x30, &signed_inner);+    assert!(!prepare_download_request(&s, None).unwrap().is_empty());+    assert!(!prepare_download_request(&s, Some("123456")).unwrap().is_empty());+    s.server_signed2 = vec![0x30, 0x00];+    assert!(prepare_download_request(&s, None).is_err());+}++#[test]+fn deliver_notification_with_branches() {+    use std::cell::RefCell;+    // No seq: fallback post to SM-DP+, no retrieve/remove.+    let calls = RefCell::new(Vec::<String>::new());+    let mut retrieve = |_: &mut (), _seq: u32| -> Result<(String, Vec<u8>), String> { calls.borrow_mut().push("retrieve".into()); Err("x".into()) };+    let mut fallback = |addr: &str, _b: &[u8]| -> Result<(), String> { calls.borrow_mut().push(format!("fallback:{addr}")); Ok(()) };+    let mut post_at = |addr: &str, _b: &[u8]| -> Result<(), String> { calls.borrow_mut().push(format!("post:{addr}")); Ok(()) };+    let mut remove = |_: &mut (), seq: u32| { calls.borrow_mut().push(format!("remove:{seq}")); };+    deliver_notification_with(&mut (), "smdp.example.com", -1, &[9], &mut retrieve, &mut fallback, &mut post_at, &mut remove);+    assert_eq!(*calls.borrow(), vec!["fallback:smdp.example.com".to_string()]);+    // Retrieve failure: fallback post, no remove.+    calls.borrow_mut().clear();+    deliver_notification_with(&mut (), "smdp.example.com", 7, &[9], &mut retrieve, &mut fallback, &mut post_at, &mut remove);+    assert_eq!(*calls.borrow(), vec!["retrieve".to_string(), "fallback:smdp.example.com".to_string()]);+    // Success with own address: post there, then remove; empty address uses SM-DP+.+    let removed = RefCell::new(Vec::<u32>::new());+    let posted = RefCell::new(Vec::<String>::new());+    let mut retrieve_ok = |_: &mut (), _seq: u32| -> Result<(String, Vec<u8>), String> { Ok(("rsp.example.com".into(), vec![1, 2])) };+    let mut fb2 = |_addr: &str, _b: &[u8]| -> Result<(), String> { Ok(()) };+    let mut post2 = |addr: &str, _b: &[u8]| -> Result<(), String> { posted.borrow_mut().push(addr.to_string()); Ok(()) };+    let mut rem2 = |_: &mut (), seq: u32| { removed.borrow_mut().push(seq); };+    deliver_notification_with(&mut (), "smdp.example.com", 7, &[9], &mut retrieve_ok, &mut fb2, &mut post2, &mut rem2);+    assert_eq!(*posted.borrow(), vec!["rsp.example.com".to_string()]);+    assert_eq!(*removed.borrow(), vec![7]);+    // Post failure skips remove; empty address targets the SM-DP+.+    let mut retrieve_empty = |_: &mut (), _seq: u32| -> Result<(String, Vec<u8>), String> { Ok((String::new(), vec![3])) };+    let mut post_fail = |addr: &str, _b: &[u8]| -> Result<(), String> { posted.borrow_mut().push(addr.to_string()); Err("down".into()) };+    posted.borrow_mut().clear(); removed.borrow_mut().clear();+    deliver_notification_with(&mut (), "smdp.example.com", 8, &[9], &mut retrieve_empty, &mut fb2, &mut post_fail, &mut rem2);+    assert_eq!(*posted.borrow(), vec!["smdp.example.com".to_string()]);+    assert!(removed.borrow().is_empty());+}
euicc/src/main/rust/src/es10_tests.rs
diff --git a/euicc/src/main/rust/src/es10_tests.rs b/euicc/src/main/rust/src/es10_tests.rsindex ad1454aa44..2e784cec10 100644--- a/euicc/src/main/rust/src/es10_tests.rs+++ b/euicc/src/main/rust/src/es10_tests.rs@@ -142,3 +142,20 @@ fn notifications_event_table_and_defaults() {     assert!(parse_remove_result(&[]).is_err());     assert!(parse_remove_result(&asn1::tlv(TAG_REMOVE_NOTIFICATION, &[])).is_err()); }++#[test]+fn get_profiles_request_and_non_metadata_notifications() {+    // build_get_profiles was only exercised via JNI; pin its exact bytes shape.+    let req = build_get_profiles();+    assert!(!req.is_empty());+    let parsed = crate::asn1::parse(&req).unwrap().0;+    assert_eq!(parsed.tag, TAG_PROFILE_INFO_LIST);+    // A notification list containing a non-metadata child skips that child.+    let meta = asn1::tlv(TAG_NOTIFICATION_METADATA, &asn1::tlv(TAG_SEQ_NUMBER, &[0x05]));+    let mut list_body = asn1::tlv(0x99, &[0x01]);+    list_body.extend(meta);+    let resp = asn1::tlv(TAG_LIST_NOTIFICATION, &asn1::tlv(TAG_NOTIFICATION_LIST, &list_body));+    let notes = parse_notifications(&resp).unwrap();+    assert_eq!(notes.len(), 1);+    assert_eq!(notes[0].seq_number, 5);+}
euicc/src/main/rust/src/es10b_tests.rs
diff --git a/euicc/src/main/rust/src/es10b_tests.rs b/euicc/src/main/rust/src/es10b_tests.rsindex 9fb4d2fdb4..b6eae3daca 100644--- a/euicc/src/main/rust/src/es10b_tests.rs+++ b/euicc/src/main/rust/src/es10b_tests.rs@@ -196,3 +196,26 @@ fn retrieve_and_cancel_shapes() {     );     assert!(parse_retrieved_notification(&bad37).is_err()); }++#[test]+fn bpp_and_error_reason_name_tables() {+    assert_eq!(bpp_command_name(0), "initialise_secure_channel");+    assert_eq!(bpp_command_name(1), "configure_isdp");+    assert_eq!(bpp_command_name(2), "store_metadata");+    assert_eq!(bpp_command_name(3), "store_metadata2");+    assert_eq!(bpp_command_name(4), "replace_session_keys");+    assert_eq!(bpp_command_name(5), "load_profile_elements");+    assert_eq!(bpp_command_name(6), "unknown");+    assert_eq!(bpp_command_name(-1), "unknown");+    let reasons: &[(i64, &str)] = &[+        (1, "incorrect_input_values"), (2, "invalid_signature"), (3, "invalid_transaction_id"),+        (4, "unsupported_crt_values"), (5, "unsupported_remote_operation_type"),+        (6, "unsupported_profile_class"), (7, "scp03t_structure_error"), (8, "scp03t_security_error"),+        (9, "install_failed_due_to_iccid_already_exists_on_euicc"),+        (10, "install_failed_due_to_insufficient_memory_for_profile"),+        (11, "install_failed_due_to_interruption"), (12, "install_failed_due_to_pe_processing_error"),+        (13, "install_failed_due_to_data_mismatch"), (14, "test_profile_install_failed_due_to_invalid_naa_key"),+        (15, "ppr_not_allowed"), (127, "install_failed_due_to_unknown_error"), (0, "unknown"), (99, "unknown"),+    ];+    for (id, want) in reasons { assert_eq!(error_reason_name(*id), *want, "{id}"); }+}
euicc/src/main/rust/src/es9p.rs
diff --git a/euicc/src/main/rust/src/es9p.rs b/euicc/src/main/rust/src/es9p.rsindex 76d3e7851f..98b0631f34 100644--- a/euicc/src/main/rust/src/es9p.rs+++ b/euicc/src/main/rust/src/es9p.rs@@ -43,18 +43,26 @@ pub fn initiate_authentication(     euicc_challenge: &[u8],     euicc_info1: &[u8], ) -> Result<InitiateAuthResult, String> {-    let body = json!({+    let body = initiate_body(smdp, euicc_challenge, euicc_info1);+    let v = post("initiateAuthentication", &endpoint(smdp, "initiateAuthentication"), &body, true)?;+    parse_initiate_response(&v)+}++fn initiate_body(smdp: &str, euicc_challenge: &[u8], euicc_info1: &[u8]) -> Value {+    json!({         "smdpAddress": host_of(smdp),         "euiccChallenge": base64::encode(euicc_challenge),         "euiccInfo1": base64::encode(euicc_info1),-    });-    let v = post("initiateAuthentication", &endpoint(smdp, "initiateAuthentication"), &body, true)?;+    })+}++fn parse_initiate_response(v: &Value) -> Result<InitiateAuthResult, String> {     Ok(InitiateAuthResult {-        transaction_id: get_str(&v, "transactionId")?,-        server_signed1: get_b64(&v, "serverSigned1")?,-        server_signature1: get_b64(&v, "serverSignature1")?,-        euicc_ci_pkid: get_b64(&v, "euiccCiPKIdToBeUsed")?,-        server_certificate: get_b64(&v, "serverCertificate")?,+        transaction_id: get_str(v, "transactionId")?,+        server_signed1: get_b64(v, "serverSigned1")?,+        server_signature1: get_b64(v, "serverSignature1")?,+        euicc_ci_pkid: get_b64(v, "euiccCiPKIdToBeUsed")?,+        server_certificate: get_b64(v, "serverCertificate")?,     }) } @@ -66,16 +74,24 @@ pub fn authenticate_client(     transaction_id: &str,     authenticate_server_response: &[u8], ) -> Result<AuthenticateClientResult, String> {-    let body = json!({+    let body = authenticate_client_body(transaction_id, authenticate_server_response);+    let v = post("authenticateClient", &endpoint(smdp, "authenticateClient"), &body, true)?;+    parse_authenticate_client_response(&v)+}++fn authenticate_client_body(transaction_id: &str, authenticate_server_response: &[u8]) -> Value {+    json!({         "transactionId": transaction_id,         "authenticateServerResponse": base64::encode(authenticate_server_response),-    });-    let v = post("authenticateClient", &endpoint(smdp, "authenticateClient"), &body, true)?;+    })+}++fn parse_authenticate_client_response(v: &Value) -> Result<AuthenticateClientResult, String> {     Ok(AuthenticateClientResult {-        profile_metadata: get_b64(&v, "profileMetadata")?,-        smdp_signed2: get_b64(&v, "smdpSigned2")?,-        smdp_signature2: get_b64(&v, "smdpSignature2")?,-        smdp_certificate: get_b64(&v, "smdpCertificate")?,+        profile_metadata: get_b64(v, "profileMetadata")?,+        smdp_signed2: get_b64(v, "smdpSigned2")?,+        smdp_signature2: get_b64(v, "smdpSignature2")?,+        smdp_certificate: get_b64(v, "smdpCertificate")?,     }) } @@ -86,10 +102,7 @@ pub fn get_bound_profile_package(     transaction_id: &str,     prepare_download_response: &[u8], ) -> Result<Vec<u8>, String> {-    let body = json!({-        "transactionId": transaction_id,-        "prepareDownloadResponse": base64::encode(prepare_download_response),-    });+    let body = get_bpp_body(transaction_id, prepare_download_response);     let v = post(         "getBoundProfilePackage",         &endpoint(smdp, "getBoundProfilePackage"),@@ -99,6 +112,13 @@ pub fn get_bound_profile_package(     get_b64(&v, "boundProfilePackage") } +fn get_bpp_body(transaction_id: &str, prepare_download_response: &[u8]) -> Value {+    json!({+        "transactionId": transaction_id,+        "prepareDownloadResponse": base64::encode(prepare_download_response),+    })+}+ /// ES9+ cancelSession: frees the server-side RSP session identified by /// `transaction_id` after a failed, cancelled, or superseded download, mirroring /// lpac's `es9p_cancel_session_r` (`{transactionId, cancelSessionResponse}`).@@ -108,13 +128,17 @@ pub fn cancel_session(     transaction_id: &str,     cancel_session_response: &[u8], ) -> Result<(), String> {-    let body = json!({-        "transactionId": transaction_id,-        "cancelSessionResponse": base64::encode(cancel_session_response),-    });+    let body = cancel_session_body(transaction_id, cancel_session_response);     let _ = post("cancelSession", &endpoint(smdp, "cancelSession"), &body, false)?;     Ok(()) }++fn cancel_session_body(transaction_id: &str, cancel_session_response: &[u8]) -> Value {+    json!({+        "transactionId": transaction_id,+        "cancelSessionResponse": base64::encode(cancel_session_response),+    })+} /// HandleNotification: delivers a pending notification to the SM-DP+. Best-effort; /// the eUICC keeps the notification until acknowledged, so a failure is not fatal. ///@@ -122,7 +146,7 @@ pub fn cancel_session( /// `notification process` reads it out of RetrieveNotificationsList and posts /// there, not to the download's SM-DP+), falling back to the download server. pub fn handle_notification_at(address: &str, pending_notification: &[u8]) -> Result<(), String> {-    let body = json!({ "pendingNotification": base64::encode(pending_notification) });+    let body = handle_notification_body(pending_notification);     // A 204/empty body is normal here; ignore the parsed value.     let _ = post(         "handleNotification",@@ -143,6 +167,28 @@ pub fn handle_notification(smdp: &str, pending_notification: &[u8]) -> Result<() // HTTP + helpers // --------------------------------------------------------------------------- +fn handle_notification_body(pending_notification: &[u8]) -> Value {+    json!({ "pendingNotification": base64::encode(pending_notification) })+}++fn handle_response(function: &str, url: &str, status: u16, body: &[u8], expect_body: bool) -> Result<Value, String> {+    if status < 200 || status >= 300 {+        return Err(format!("SM-DP+ HTTP {} at {url}", status));+    }+    if body.is_empty() {+        if !expect_body {+            return Ok(Value::Null);+        }+        return Err(format!(+            "SM-DP+ {function} returned HTTP {} with empty body",+            status+        ));+    }+    let v: Value = serde_json::from_slice(body).map_err(|e| format!("parse response: {e}"))?;+    check_function_execution_status(&v)?;+    Ok(v)+}+ fn post(function: &str, url: &str, body: &Value, expect_body: bool) -> Result<Value, String> {     let headers = [         ("Content-Type".to_string(), "application/json".to_string()),@@ -155,24 +201,9 @@ fn post(function: &str, url: &str, body: &Value, expect_body: bool) -> Result<Va     let bytes = serde_json::to_vec(body).map_err(|e| format!("encode body: {e}"))?;     let resp = jni_http::request(jni_http::Method::Post, url, &headers, Some(&bytes))         .map_err(|e| format!("{e}"))?;-    if resp.status < 200 || resp.status >= 300 {-        return Err(format!("SM-DP+ HTTP {} at {url}", resp.status));-    }-    if resp.body.is_empty() {-        // HandleNotification answers 204/empty normally; every other function-        // must return a JSON body, so an empty reply names the function and-        // status instead of failing later on a missing field.-        if !expect_body {-            return Ok(Value::Null);-        }-        return Err(format!(-            "SM-DP+ {function} returned HTTP {} with empty body",-            resp.status-        ));-    }-    let v: Value = serde_json::from_slice(&resp.body).map_err(|e| format!("parse response: {e}"))?;-    check_function_execution_status(&v)?;-    Ok(v)+    // HandleNotification answers 204/empty normally; every other function+    // must return a JSON body (handle_response enforces that).+    handle_response(function, url, resp.status, &resp.body, expect_body) }  /// Surfaces an SM-DP+ ES9+ functionExecutionStatus error, if present.
euicc/src/main/rust/src/es9p_tests.rs
diff --git a/euicc/src/main/rust/src/es9p_tests.rs b/euicc/src/main/rust/src/es9p_tests.rsindex ce6aacb298..d3af66e2e3 100644--- a/euicc/src/main/rust/src/es9p_tests.rs+++ b/euicc/src/main/rust/src/es9p_tests.rs@@ -82,3 +82,123 @@ fn get_str_and_b64_edges() {     assert!(get_b64(&json!({"a": "not!b64"}), "a").is_err());     assert!(get_b64(&json!({"a": 7}), "a").is_err()); }++#[test]+fn error_table_all_entries() {+    let cases: &[(&str, &str, &str)] = &[+        ("8.1", "4.8", "eUICC does not have sufficient space for this Profile"),+        ("8.1", "6.1", "eUICC signature is invalid or serverChallenge is invalid"),+        ("8.1.1", "2.2", "EID is missing (SM-DS address provided or MatchingID empty)"),+        ("8.1.1", "3.1", "a different EID is already associated with this ICCID"),+        ("8.1.1", "3.8", "EID doesn't match the expected value"),+        ("8.1.2", "6.1", "EUM Certificate is invalid"),+        ("8.1.2", "6.3", "EUM Certificate has expired"),+        ("8.1.3", "6.1", "eUICC Certificate is invalid"),+        ("8.1.3", "6.3", "eUICC Certificate has expired"),+        ("8.2", "1.2", "Profile has not yet been released"),+        ("8.2", "3.7", "BPP is not available for a new binding"),+        ("8.2.1", "1.2", "caller is not allowed to perform this function on the target Profile"),+        ("8.2.1", "3.1", "a different EID is associated with this ICCID"),+        ("8.2.1", "3.3", "the Profile identified by the provided ICCID is not available"),+        ("8.2.1", "3.5", "the target Profile cannot be released"),+        ("8.2.1", "3.9", "the Profile Type is unknown to the SM-DP+"),+        ("8.2.5", "1.2", "caller is not allowed to perform this function on the Profile Type"),+        ("8.2.5", "3.7", "No more Profile available for the requested Profile Type"),+        ("8.2.5", "3.8", "Profile Type is not aligned with the Profile identified by the ICCID"),+        ("8.2.5", "3.9", "the Profile Type is unknown to the SM-DP+"),+        ("8.2.5", "4.3", "No eligible Profile for this eUICC/Device"),+        ("8.2.6", "3.1", "a different MatchingID is associated with this ICCID"),+        ("8.2.6", "3.3", "Conflicting MatchingID value"),+        ("8.2.6", "3.8", "MatchingID (AC_Token or EventID) is refused"),+        ("8.2.7", "2.2", "Confirmation Code is missing"),+        ("8.2.7", "3.8", "Confirmation Code is refused"),+        ("8.2.7", "6.4", "The maximum number of retries for the Confirmation Code has been exceeded"),+        ("8.8", "3.1", "The provided SM-DP+ OID is invalid"),+        ("8.8.1", "3.8", "Invalid SM-DP+ Address"),+        ("8.8.2", "3.1", "None of the proposed Public Key Identifiers is supported by the SM-DP+"),+        ("8.8.3", "3.1", "The Specification Version Number indicated by the eUICC is not supported by the SM-DP+"),+        ("8.8.4", "3.7", "The SM-DP+ has no CERT.DPauth.ECDSA signed by one of the CI Public Key supported by the eUICC"),+        ("8.8.5", "4.1", "The Download order has expired"),+        ("8.8.5", "6.4", "The maximum number of retries for the Profile download order has been exceeded"),+        ("8.9", "4.2", "Root SM-DS has raised an error"),+        ("8.9", "5.1", "Root SM-DS was unavailable"),+        ("8.9.1", "3.8", "Invalid SM-DS Address"),+        ("8.9.2", "3.1", "None of the proposed Public Key Identifiers is supported by the SM-DS"),+        ("8.9.3", "3.1", "The Specification Version Number indicated by the eUICC is not supported by the SM-DS"),+        ("8.9.4", "3.7", "The SM-DS has no CERT.DS.ECDSA signed by one of the GSMA CI Public Key supported by the eUICC"),+        ("8.9.5", "3.3", "The Event Record already exists in the SM-DS (EventID duplicated)"),+        ("8.9.5", "3.9", "No Event identified by the Event ID for the EID exists"),+        ("8.10.1", "3.9", "The RSP session identified by the TransactionID is unknown"),+        ("8.11.1", "3.9", "Unknown CI Public Key. The CI used by the EUM Certificate is not a trusted root."),+    ];+    for (s, r, want) in cases {+        assert_eq!(es9p_error_message(s, r), Some(*want), "{s}/{r}");+    }+}++#[test]+fn request_bodies_encode_fields() {+    let b = initiate_body("https://smdp.example.com/", &[1, 2], &[3]);+    assert_eq!(b["smdpAddress"], "smdp.example.com");+    assert_eq!(b["euiccChallenge"], crate::base64::encode(&[1, 2]));+    assert_eq!(b["euiccInfo1"], crate::base64::encode(&[3]));+    let b = authenticate_client_body("tx-1", &[9]);+    assert_eq!(b["transactionId"], "tx-1");+    assert_eq!(b["authenticateServerResponse"], crate::base64::encode(&[9]));+    let b = get_bpp_body("tx-2", &[7, 8]);+    assert_eq!(b["transactionId"], "tx-2");+    assert_eq!(b["prepareDownloadResponse"], crate::base64::encode(&[7, 8]));+    let b = cancel_session_body("tx-3", &[5]);+    assert_eq!(b["cancelSessionResponse"], crate::base64::encode(&[5]));+    let b = handle_notification_body(&[4, 4]);+    assert_eq!(b["pendingNotification"], crate::base64::encode(&[4, 4]));+}++#[test]+fn parse_response_helpers() {+    let enc = crate::base64::encode;+    let v = json!({"transactionId": "tx", "serverSigned1": enc(&[1]), "serverSignature1": enc(&[2]),+        "euiccCiPKIdToBeUsed": enc(&[3]), "serverCertificate": enc(&[4])});+    let r = parse_initiate_response(&v).unwrap();+    assert_eq!(r.transaction_id, "tx");+    assert_eq!(r.server_signed1, vec![1]);+    assert_eq!(r.server_signature1, vec![2]);+    assert_eq!(r.euicc_ci_pkid, vec![3]);+    assert_eq!(r.server_certificate, vec![4]);+    assert!(parse_initiate_response(&json!({"transactionId": "tx"})).is_err());+    let v = json!({"profileMetadata": enc(&[1]), "smdpSigned2": enc(&[2]),+        "smdpSignature2": enc(&[3]), "smdpCertificate": enc(&[4])});+    let r = parse_authenticate_client_response(&v).unwrap();+    assert_eq!(r.profile_metadata, vec![1]);+    assert_eq!(r.smdp_signed2, vec![2]);+    assert_eq!(r.smdp_signature2, vec![3]);+    assert_eq!(r.smdp_certificate, vec![4]);+    assert!(parse_authenticate_client_response(&json!({})).is_err());+}++#[test]+fn handle_response_status_and_body_rules() {+    assert!(handle_response("f", "https://x/y", 500, b"{}", true).unwrap_err().contains("HTTP 500"));+    assert!(handle_response("f", "https://x/y", 199, b"{}", true).is_err());+    assert!(handle_response("f", "https://x/y", 300, b"{}", true).is_err());+    assert_eq!(handle_response("handleNotification", "https://x/y", 204, b"", false).unwrap(), Value::Null);+    assert!(handle_response("initiateAuthentication", "https://x/y", 200, b"", true).unwrap_err().contains("empty body"));+    assert!(handle_response("f", "https://x/y", 200, b"not json", true).unwrap_err().contains("parse response"));+    let ok = br#"{"header":{"functionExecutionStatus":{"status":"Executed-Success"}},"k":1}"#;+    assert_eq!(handle_response("f", "https://x/y", 200, ok, true).unwrap()["k"], 1);+    let failed = br#"{"header":{"functionExecutionStatus":{"status":"Failed","statusCodeData":{"subjectCode":"8.1","reasonCode":"4.8"}}}}"#;+    assert!(handle_response("f", "https://x/y", 200, failed, true).unwrap_err().contains("sufficient space"));+    assert_eq!(summarize_scalar(&Value::Null), "null");+}++#[test]+fn public_calls_fail_without_http_bridge() {+    // No JVM/bridge in host tests: every ES9+ call must surface the bridge+    // error instead of panicking, and must not fabricate a success result.+    assert!(initiate_authentication("smdp.example.com", &[1], &[2]).is_err());+    assert!(authenticate_client("smdp.example.com", "tx", &[1]).is_err());+    assert!(get_bound_profile_package("smdp.example.com", "tx", &[1]).is_err());+    assert!(cancel_session("smdp.example.com", "tx", &[1]).is_err());+    assert!(handle_notification_at("smdp.example.com", &[1]).is_err());+    assert!(handle_notification("smdp.example.com", &[1]).is_err());+}
euicc/src/main/rust/src/jni.rs
diff --git a/euicc/src/main/rust/src/jni.rs b/euicc/src/main/rust/src/jni.rsindex e3e0def7c2..7691cd168a 100644--- a/euicc/src/main/rust/src/jni.rs+++ b/euicc/src/main/rust/src/jni.rs@@ -94,6 +94,21 @@ pub(crate) fn store_data_chunked(     command: &[u8],     chunk: usize, ) -> Result<Vec<u8>, String> {+    let mut transmit = |e: &mut Env, apdu: &[u8]| transmit_apdu(e, apdu);+    store_data_with(env, command, chunk, &mut transmit)+}++/// [`store_data_chunked`] with the APDU transport injected, so the response+/// reassembly / status-word rules are host-testable without a JVM.+pub(crate) fn store_data_with<E, F>(+    env: &mut E,+    command: &[u8],+    chunk: usize,+    transmit: &mut F,+) -> Result<Vec<u8>, String>+where+    F: FnMut(&mut E, &[u8]) -> Result<Vec<u8>, String>,+{     let apdus = build_store_data_apdus(command, chunk);     let last = apdus.len() - 1; @@ -104,7 +119,7 @@ pub(crate) fn store_data_chunked(         // per APDU, so intermediate bodies are normally empty — but when a         // card streams chained reply bytes, only concatenation reassembles         // them). Fail fast on a non-success status.-        let mut block_resp = transmit_apdu(env, apdu)?;+        let mut block_resp = transmit(env, apdu)?;         if block_resp.len() < 2 {             return Err("APDU response too short".into());         }@@ -145,12 +160,73 @@ pub(crate) fn read_string(env: &Env, s: &JString) -> Option<String> { /// Sends a request and parses its INTEGER result, returning the eUICC result /// code (0 = success) or -1 on a transport/parse error. fn run_result(env: &mut Env, request: &[u8], tag: u32) -> jint {-    match store_data(env, request).and_then(|resp| es10::parse_result(&resp, tag)) {+    result_code(store_data(env, request), tag)+}++/// Maps a STORE DATA reply to the JNI result code: parsed code, or -1.+fn result_code(result: Result<Vec<u8>, String>, tag: u32) -> jint {+    match result.and_then(|resp| es10::parse_result(&resp, tag)) {+        Ok(code) => code as jint,+        Err(_) => -1,+    }+}++/// Maps a remove-notification reply to the JNI result code.+fn remove_code(result: Result<Vec<u8>, String>) -> jint {+    match result.and_then(|resp| es10::parse_remove_result(&resp)) {         Ok(code) => code as jint,         Err(_) => -1,     } } +/// A negative Kotlin sequence number is invalid; anything else is a seq.+fn seq_arg(seq: jint) -> Option<u32> {+    if seq < 0 { None } else { Some(seq as u32) }+}++fn profiles_json(profiles: &[es10::ProfileInfo]) -> String {+    let arr: Vec<_> = profiles+        .iter()+        .map(|p| {+            serde_json::json!({+                "iccid": p.iccid,+                "iccidDisplay": p.iccid_display,+                "isdpAid": p.isdp_aid,+                "state": p.state,+                "class": p.class,+                "nickname": p.nickname,+                "serviceProvider": p.service_provider,+                "name": p.name,+            })+        })+        .collect();+    serde_json::Value::Array(arr).to_string()+}++fn notifications_json(notes: &[es10::NotificationInfo]) -> String {+    let arr: Vec<_> = notes+        .iter()+        .map(|n| {+            serde_json::json!({+                "seqNumber": n.seq_number,+                "operation": n.operation,+                "address": n.address,+                "iccidDisplay": n.iccid_display,+            })+        })+        .collect();+    serde_json::Value::Array(arr).to_string()+}++fn euicc_info_json(info: &es10::EuiccInfo1) -> String {+    serde_json::json!({+        "svn": info.svn,+        "ciPkIdListForVerification": info.ci_pkid_verification,+        "ciPkIdListForSigning": info.ci_pkid_signing,+    })+    .to_string()+}+ /// `nativeGetProfiles()` — installed profiles as a JSON array, or null on error. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeGetProfiles<'l>(@@ -161,24 +237,7 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeGetProfiles<         let result = store_data(env, &es10::build_get_profiles())             .and_then(|resp| es10::parse_profiles(&resp));         Ok(match result {-            Ok(profiles) => {-            let arr: Vec<_> = profiles-                .iter()-                .map(|p| {-                    serde_json::json!({-                        "iccid": p.iccid,-                        "iccidDisplay": p.iccid_display,-                        "isdpAid": p.isdp_aid,-                        "state": p.state,-                        "class": p.class,-                        "nickname": p.nickname,-                        "serviceProvider": p.service_provider,-                        "name": p.name,-                    })-                })-                .collect();-            new_jstring(env, &serde_json::Value::Array(arr).to_string())-            }+            Ok(profiles) => new_jstring(env, &profiles_json(&profiles)),             Err(_) => std::ptr::null_mut(),         })     })@@ -265,20 +324,7 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeListNotifica         let result = store_data(env, &es10::build_list_notifications())             .and_then(|resp| es10::parse_notifications(&resp));         Ok(match result {-        Ok(notes) => {-            let arr: Vec<_> = notes-                .iter()-                .map(|n| {-                    serde_json::json!({-                        "seqNumber": n.seq_number,-                        "operation": n.operation,-                        "address": n.address,-                        "iccidDisplay": n.iccid_display,-                    })-                })-                .collect();-            new_jstring(env, &serde_json::Value::Array(arr).to_string())-            }+            Ok(notes) => new_jstring(env, &notifications_json(&notes)),             Err(_) => std::ptr::null_mut(),         })     })@@ -293,15 +339,10 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeRemoveNotifi     seq: jint, ) -> jint {     env.with_env(|env| -> jni::errors::Result<jint> {-        if seq < 0 {+        let Some(seq) = seq_arg(seq) else {             return Ok(-1);-        }-        Ok(match store_data(env, &es10::build_remove_notification(seq as u32))-            .and_then(|resp| es10::parse_remove_result(&resp))-        {-            Ok(code) => code as jint,-            Err(_) => -1,-        })+        };+        Ok(remove_code(store_data(env, &es10::build_remove_notification(seq))))     })     .resolve::<jni::errors::LogErrorAndDefault>() }@@ -347,14 +388,7 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeGetEuiccInfo         let result = store_data(env, &es10::build_get_euicc_info1())             .and_then(|resp| es10::parse_euicc_info1(&resp));         Ok(match result {-        Ok(info) => {-            let json = serde_json::json!({-                "svn": info.svn,-                "ciPkIdListForVerification": info.ci_pkid_verification,-                "ciPkIdListForSigning": info.ci_pkid_signing,-            });-            new_jstring(env, &json.to_string())-            }+            Ok(info) => new_jstring(env, &euicc_info_json(&info)),             Err(_) => std::ptr::null_mut(),         })     })
euicc/src/main/rust/src/jni_download.rs
diff --git a/euicc/src/main/rust/src/jni_download.rs b/euicc/src/main/rust/src/jni_download.rsindex 80d592eb0d..e360b0b858 100644--- a/euicc/src/main/rust/src/jni_download.rs+++ b/euicc/src/main/rust/src/jni_download.rs@@ -54,6 +54,59 @@ fn session_take(handle: &str) -> Option<download::DownloadSession> {     Some(guard.remove(pos).1) } +/// Invalid activation-code reply for the atomic download entry.+fn invalid_activation_json() -> serde_json::Value {+    serde_json::json!({ "success": false, "message": "Invalid activation code" })+}++/// Atomic download flow with transport injected for host tests.+fn run_download<E, F>(env: &mut E, code: Option<String>, download_fn: &mut F) -> serde_json::Value+where F: FnMut(&mut E, &str) -> Result<es10b::InstallResult, String> {+    let Some(code) = code else { return invalid_activation_json(); };+    download_result_json(download_fn(env, &code))+}++/// Authenticate flow: on success stores the session under its handle.+fn run_authenticate<E, F>(env: &mut E, code: &str, options: &download::DownloadOptions, authenticate_fn: &mut F) -> serde_json::Value+where F: FnMut(&mut E, &str, &download::DownloadOptions) -> Result<download::DownloadSession, String> {+    match authenticate_fn(env, code, options) {+        Ok(session) => {+            let reply = authenticate_success_json(&session);+            session_put(session.transaction_id.clone(), session);+            reply+        }+        Err(message) => authenticate_error_json(&message),+    }+}++/// Finish flow: consumes the session, applies nickname seeding, replies JSON.+fn run_finish<E, F, N>(env: &mut E, handle: &str, code: Option<&str>, nickname: Option<&str>, finish_fn: &mut F, apply_nickname: &mut N) -> serde_json::Value+where+    F: FnMut(&mut E, &download::DownloadSession, Option<&str>) -> Result<es10b::InstallResult, String>,+    N: FnMut(&mut E, &[u8]),+{+    let Some(session) = session_take(handle) else {+        return finish_json_value(false, "Download session expired — start again");+    };+    let result = finish_fn(env, &session, code);+    if let Ok(ref ok_result) = result {+        if let Some(req) = nickname_request(ok_result, nickname) {+            apply_nickname(env, &req);+        }+    }+    download_result_json(result)+}++/// Cancel flow: consumes the session if present; `false` only for a bad handle.+fn run_cancel<E, F>(env: &mut E, handle: Option<String>, reason: jint, cancel_fn: &mut F) -> bool+where F: FnMut(&mut E, &download::DownloadSession, es10b::CancelReason) {+    let Some(handle) = handle else { return false; };+    if let Some(session) = session_take(&handle) {+        cancel_fn(env, &session, cancel_reason(reason));+    }+    true+}+ /// `nativeDownloadProfile(activationCode)` — runs the full SGP.22 download for /// an activation code and returns a JSON `{success, message, iccid}` string. /// Must be called while the ISD-R channel is open (inside `withIsdrChannel`).@@ -71,19 +124,9 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeDownloadProf         // Resolve the HTTP bridge (library:network) once; harmless if already done.         jni_http::init(env); -        let Some(code) = read_string(env, &activation_code) else {-            let json = serde_json::json!({ "success": false, "message": "Invalid activation code" });-            return Ok(new_jstring(env, &json.to_string()));-        };--        let json = match crate::download::download_profile(env, &code) {-            Ok(result) => serde_json::json!({-                "success": result.success,-                "message": result.message,-                "iccid": result.installed_iccid,-            }),-            Err(message) => serde_json::json!({ "success": false, "message": message }),-        };+        let code = read_string(env, &activation_code);+        let mut download_fn = |e: &mut Env, c: &str| crate::download::download_profile(e, c);+        let json = run_download(env, code, &mut download_fn);         Ok(new_jstring(env, &json.to_string()))     })     .resolve::<jni::errors::LogErrorAndDefault>()@@ -113,31 +156,9 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeAuthenticate             return Ok(auth_error(env, "Invalid activation code"));         };         let options = download_options(env, &confirmation_code, &tac_hex, &imei);-    // Stash the authenticated session for finish/cancel.-    let json = match crate::download::authenticate(env, &code, &options) {-        Ok(session) => {-            let handle = session.transaction_id.clone();-            let reply = serde_json::json!({-                "error": serde_json::Value::Null,-                "transactionId": handle,-                "carrier": empty_to_null(&session.metadata.service_provider),-                "profileName": empty_to_null(&session.metadata.profile_name),-                "iccid": empty_to_null(&session.metadata.iccid_display),-                "ccRequired": session.cc_required,-            });-            session_put(handle, session);-            reply-        }-        Err(message) => serde_json::json!({-            "error": message,-            "transactionId": serde_json::Value::Null,-            "carrier": serde_json::Value::Null,-            "profileName": serde_json::Value::Null,-            "iccid": serde_json::Value::Null,-            "ccRequired": false,-        }),-    };-    Ok(new_jstring(env, &json.to_string()))+        let mut authenticate_fn = |e: &mut Env, c: &str, o: &download::DownloadOptions| crate::download::authenticate(e, c, o);+        let json = run_authenticate(env, &code, &options, &mut authenticate_fn);+        Ok(new_jstring(env, &json.to_string()))     })     .resolve::<jni::errors::LogErrorAndDefault>() }@@ -163,41 +184,13 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeFinishDownlo         let Some(handle) = read_string(env, &transaction_id) else {             return Ok(finish_json(env, false, "Invalid download session"));         };-        let code = read_string(env, &confirmation_code).filter(|c| !c.is_empty());-        let nickname = read_string(env, &nickname).filter(|c| !c.trim().is_empty());-        let session = session_take(&handle);-        let Some(session) = session else {-            return Ok(finish_json(env, false, "Download session expired — start again"));-        };--        let mut progress = JniProgress {-            callback: env.new_global_ref(&callback).ok(),-        };-        let json = match crate::download::finish_download(env, &session, code.as_deref(), &mut progress)-    {-        Ok(result) => {-            // Seed the profile nickname from the carrier preview while the-            // channel is open; best-effort (a rename can always be retried).-            if result.success {-                if let Some(name) = nickname.as_deref() {-                    let iccid = crate::es10::hex_decode(&result.installed_iccid);-                    if !iccid.is_empty() {-                        let _ = crate::jni::store_data(-                            env,-                            &crate::es10::build_set_nickname(&iccid, name.trim()),-                        );-                    }-                }-            }-            serde_json::json!({-                "success": result.success,-                "message": result.message,-                "iccid": result.installed_iccid,-            })-        }-        Err(message) => serde_json::json!({ "success": false, "message": message }),-    };-    Ok(new_jstring(env, &json.to_string()))+        let code = non_empty(read_string(env, &confirmation_code));+        let nickname = non_blank(read_string(env, &nickname));+        let mut progress = JniProgress { callback: env.new_global_ref(&callback).ok() };+        let mut finish_fn = |e: &mut Env, s: &download::DownloadSession, c: Option<&str>| crate::download::finish_download(e, s, c, &mut progress);+        let mut apply_nickname = |e: &mut Env, req: &[u8]| { let _ = crate::jni::store_data(e, req); };+        let json = run_finish(env, &handle, code.as_deref(), nickname.as_deref(), &mut finish_fn, &mut apply_nickname);+        Ok(new_jstring(env, &json.to_string()))     })     .resolve::<jni::errors::LogErrorAndDefault>() }@@ -213,14 +206,9 @@ pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeCancelDownlo     reason: jint, ) -> jboolean {     env.with_env(|env| -> jni::errors::Result<jboolean> {-        let Some(handle) = read_string(env, &transaction_id) else {-            return Ok(false);-        };-        let session = session_take(&handle);-        if let Some(session) = session {-            crate::download::cancel_session(env, &session, cancel_reason(reason));-        }-        Ok(true)+        let handle = read_string(env, &transaction_id);+        let mut cancel_fn = |e: &mut Env, s: &download::DownloadSession, r: es10b::CancelReason| crate::download::cancel_session(e, s, r);+        Ok(run_cancel(env, handle, reason, &mut cancel_fn))     })     .resolve::<jni::errors::LogErrorAndDefault>() }@@ -238,17 +226,88 @@ fn download_options(     tac_hex: &JString,     imei: &JString, ) -> download::DownloadOptions {-    let confirmation_code = read_string(env, confirmation_code).filter(|c| !c.trim().is_empty());-    let imei = read_string(env, imei).filter(|c| !c.trim().is_empty());-    let tac = read_string(env, tac_hex)-        .filter(|t| !t.trim().is_empty())+    download_options_from(+        read_string(env, confirmation_code),+        read_string(env, tac_hex),+        read_string(env, imei),+    )+}++fn download_options_from(+    confirmation_code: Option<String>,+    tac_hex: Option<String>,+    imei: Option<String>,+) -> download::DownloadOptions {+    let confirmation_code = non_blank(confirmation_code);+    let imei = non_blank(imei);+    let tac = non_blank(tac_hex)         .and_then(|t| parse_tac(&t))         .or(Some(es10b::DEFAULT_TAC));-    download::DownloadOptions {-        confirmation_code,-        tac,-        imei,+    download::DownloadOptions { confirmation_code, tac, imei }+}++fn non_empty(s: Option<String>) -> Option<String> {+    s.filter(|c| !c.is_empty())+}++fn non_blank(s: Option<String>) -> Option<String> {+    s.filter(|c| !c.trim().is_empty())+}++/// `{success, message, iccid}` reply shared by both download entries.+fn download_result_json(result: Result<es10b::InstallResult, String>) -> serde_json::Value {+    match result {+        Ok(result) => serde_json::json!({+            "success": result.success,+            "message": result.message,+            "iccid": result.installed_iccid,+        }),+        Err(message) => serde_json::json!({ "success": false, "message": message }),+    }+}++fn authenticate_success_json(session: &download::DownloadSession) -> serde_json::Value {+    serde_json::json!({+        "error": serde_json::Value::Null,+        "transactionId": session.transaction_id,+        "carrier": empty_to_null(&session.metadata.service_provider),+        "profileName": empty_to_null(&session.metadata.profile_name),+        "iccid": empty_to_null(&session.metadata.iccid_display),+        "ccRequired": session.cc_required,+    })+}++fn authenticate_error_json(message: &str) -> serde_json::Value {+    serde_json::json!({+        "error": message,+        "transactionId": serde_json::Value::Null,+        "carrier": serde_json::Value::Null,+        "profileName": serde_json::Value::Null,+        "iccid": serde_json::Value::Null,+        "ccRequired": false,+    })+}++fn finish_json_value(success: bool, message: &str) -> serde_json::Value {+    serde_json::json!({ "success": success, "message": message })+}++/// SetNickname request to seed a freshly installed profile, if applicable.+fn nickname_request(result: &es10b::InstallResult, nickname: Option<&str>) -> Option<Vec<u8>> {+    if !result.success {+        return None;+    }+    let name = nickname?;+    let iccid = crate::es10::hex_decode(&result.installed_iccid);+    if iccid.is_empty() {+        return None;     }+    Some(crate::es10::build_set_nickname(&iccid, name.trim()))+}++/// A failed/absent Kotlin progress callback never aborts the install.+fn progress_decision(result: Option<bool>) -> bool {+    result.unwrap_or(true) }  /// Parses 8 hex digits into a TAC. Malformed input falls back to the default@@ -285,21 +344,12 @@ fn empty_to_null(s: &str) -> serde_json::Value {  /// Authenticate-path error reply. fn auth_error(env: &mut Env, message: &str) -> jstring {-    let json = serde_json::json!({-        "error": message,-        "transactionId": serde_json::Value::Null,-        "carrier": serde_json::Value::Null,-        "profileName": serde_json::Value::Null,-        "iccid": serde_json::Value::Null,-        "ccRequired": false,-    });-    new_jstring(env, &json.to_string())+    new_jstring(env, &authenticate_error_json(message).to_string()) }  /// Finish-path `{success, message}` reply. fn finish_json(env: &mut Env, success: bool, message: &str) -> jstring {-    let json = serde_json::json!({ "success": success, "message": message });-    new_jstring(env, &json.to_string())+    new_jstring(env, &finish_json_value(success, message).to_string()) }  /// [`download::ProgressCallback`] that forwards segment counts to Kotlin@@ -325,80 +375,10 @@ impl download::ProgressCallback for JniProgress {             .and_then(|v| v.z());         // Clear a pending Kotlin exception so later JNI calls stay valid.         let _ = env.exception_clear();-        result.unwrap_or(true)+        progress_decision(result.ok())     } }  #[cfg(test)]-mod tests {-    use super::*;--    /// The session store is process-global, so store tests must not run-    /// concurrently with each other (cargo test defaults to parallel threads).-    static TEST_LOCK: Mutex<()> = Mutex::new(());--    fn session(id: &str) -> download::DownloadSession {-        download::DownloadSession::for_test(id)-    }--    #[test]-    fn session_survives_take_on_another_thread() {-        let _guard = TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());-        sessions().clear();-        session_put("tx-cross-thread".to_string(), session("tx-cross-thread"));-        // Dispatchers.IO does not pin authenticate/finish to one thread; the-        // take must succeed from a different OS thread than the put.-        let taken = std::thread::spawn(|| session_take("tx-cross-thread"))-            .join()-            .unwrap();-        assert_eq!(taken.unwrap().transaction_id, "tx-cross-thread");-        assert!(session_take("tx-cross-thread").is_none());-    }--    #[test]-    fn parse_tac_and_cancel_reason_and_empty_to_null() {-        assert_eq!(parse_tac("35290611"), Some([0x35, 0x29, 0x06, 0x11]));-        assert_eq!(parse_tac(" 35290611 "), Some(es10b::DEFAULT_TAC));-        // Malformed TAC (odd, non-hex, wrong length) falls back to None.-        assert_eq!(parse_tac("3529061"), None);-        assert_eq!(parse_tac("zz290611"), None);-        assert_eq!(parse_tac("3529061100"), None);-        assert_eq!(parse_tac(""), None);-        assert_eq!(cancel_reason(0), es10b::CancelReason::EndUserRejection);-        assert_eq!(cancel_reason(1), es10b::CancelReason::Postponed);-        assert_eq!(cancel_reason(2), es10b::CancelReason::Timeout);-        assert_eq!(cancel_reason(3), es10b::CancelReason::PprNotAllowed);-        assert_eq!(cancel_reason(4), es10b::CancelReason::MetadataMismatch);-        assert_eq!(cancel_reason(5), es10b::CancelReason::LoadBppExecutionError);-        assert_eq!(cancel_reason(6), es10b::CancelReason::EndUserRejection);-        assert_eq!(cancel_reason(-1), es10b::CancelReason::EndUserRejection);-        assert_eq!(empty_to_null(""), serde_json::Value::Null);-        assert_eq!(empty_to_null("Carrier"), serde_json::Value::String("Carrier".to_string()));-    }--    #[test]-    fn session_put_replaces_same_handle_and_take_missing() {-        let _guard = TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());-        sessions().clear();-        assert!(session_take("nope").is_none());-        session_put("tx-dup".to_string(), session("tx-dup"));-        session_put("tx-dup".to_string(), session("tx-dup"));-        // Re-put must not duplicate the handle (eviction counts once).-        assert_eq!(sessions().len(), 1);-        assert!(session_take("tx-dup").is_some());-        assert!(session_take("tx-dup").is_none());-    }--    #[test]-    fn session_eviction_is_oldest_first() {-        let _guard = TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());-        sessions().clear();-        for i in 0..=MAX_SESSIONS {-            session_put(format!("tx-{i}"), session(&format!("tx-{i}")));-        }-        assert!(session_take("tx-0").is_none(), "oldest must be evicted");-        for i in 1..=MAX_SESSIONS {-            assert!(session_take(&format!("tx-{i}")).is_some());-        }-    }-}+#[path = "jni_download_tests.rs"]+mod jni_download_tests;
euicc/src/main/rust/src/jni_download_tests.rs
diff --git a/euicc/src/main/rust/src/jni_download_tests.rs b/euicc/src/main/rust/src/jni_download_tests.rsnew file mode 100644index 0000000000..e9c478fae5--- /dev/null+++ b/euicc/src/main/rust/src/jni_download_tests.rs@@ -0,0 +1,155 @@+use super::*;++/// The session store is process-global, so store tests must not run+/// concurrently with each other (cargo test defaults to parallel threads).+static TEST_LOCK: Mutex<()> = Mutex::new(());++fn session(id: &str) -> download::DownloadSession {+    download::DownloadSession::for_test(id)+}++#[test]+fn session_survives_take_on_another_thread() {+    let _guard = TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());+    sessions().clear();+    session_put("tx-cross-thread".to_string(), session("tx-cross-thread"));+    // Dispatchers.IO does not pin authenticate/finish to one thread; the+    // take must succeed from a different OS thread than the put.+    let taken = std::thread::spawn(|| session_take("tx-cross-thread"))+        .join()+        .unwrap();+    assert_eq!(taken.unwrap().transaction_id, "tx-cross-thread");+    assert!(session_take("tx-cross-thread").is_none());+}++#[test]+fn parse_tac_and_cancel_reason_and_empty_to_null() {+    assert_eq!(parse_tac("35290611"), Some([0x35, 0x29, 0x06, 0x11]));+    assert_eq!(parse_tac(" 35290611 "), Some(es10b::DEFAULT_TAC));+    // Malformed TAC (odd, non-hex, wrong length) falls back to None.+    assert_eq!(parse_tac("3529061"), None);+    assert_eq!(parse_tac("zz290611"), None);+    assert_eq!(parse_tac("3529061100"), None);+    assert_eq!(parse_tac(""), None);+    assert_eq!(cancel_reason(0), es10b::CancelReason::EndUserRejection);+    assert_eq!(cancel_reason(1), es10b::CancelReason::Postponed);+    assert_eq!(cancel_reason(2), es10b::CancelReason::Timeout);+    assert_eq!(cancel_reason(3), es10b::CancelReason::PprNotAllowed);+    assert_eq!(cancel_reason(4), es10b::CancelReason::MetadataMismatch);+    assert_eq!(cancel_reason(5), es10b::CancelReason::LoadBppExecutionError);+    assert_eq!(cancel_reason(6), es10b::CancelReason::EndUserRejection);+    assert_eq!(cancel_reason(-1), es10b::CancelReason::EndUserRejection);+    assert_eq!(empty_to_null(""), serde_json::Value::Null);+    assert_eq!(empty_to_null("Carrier"), serde_json::Value::String("Carrier".to_string()));+}++#[test]+fn session_put_replaces_same_handle_and_take_missing() {+    let _guard = TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());+    sessions().clear();+    assert!(session_take("nope").is_none());+    session_put("tx-dup".to_string(), session("tx-dup"));+    session_put("tx-dup".to_string(), session("tx-dup"));+    // Re-put must not duplicate the handle (eviction counts once).+    assert_eq!(sessions().len(), 1);+    assert!(session_take("tx-dup").is_some());+    assert!(session_take("tx-dup").is_none());+}++#[test]+fn download_helpers_json_and_options() {+    let ok = es10b::InstallResult { success: true, message: "Profile installed".into(), seq_number: 1, installed_iccid: "abcd".into(), bpp_command_id: None, error_reason: None, notification: vec![] };+    let v = download_result_json(Ok(ok.clone()));+    assert_eq!(v["success"], true);+    assert_eq!(v["iccid"], "abcd");+    let v = download_result_json(Err("nope".into()));+    assert_eq!(v["success"], false);+    assert_eq!(v["message"], "nope");+    assert_eq!(v["iccid"], serde_json::Value::Null);+    let s = session("tx-json");+    let v = authenticate_success_json(&s);+    assert_eq!(v["transactionId"], "tx-json");+    assert_eq!(v["error"], serde_json::Value::Null);+    assert_eq!(v["ccRequired"], false);+    let v = authenticate_error_json("bad code");+    assert_eq!(v["error"], "bad code");+    assert_eq!(v["transactionId"], serde_json::Value::Null);+    assert_eq!(finish_json_value(false, "expired")["message"], "expired");+    // Options: blank dropped, bad TAC falls back to default, good TAC kept.+    let o = download_options_from(Some("  ".into()), Some("zz".into()), Some("  ".into()));+    assert_eq!(o.confirmation_code, None);+    assert_eq!(o.imei, None);+    assert_eq!(o.tac, Some(es10b::DEFAULT_TAC));+    let o = download_options_from(Some("1234".into()), Some("35290611".into()), Some("490154203237518".into()));+    assert_eq!(o.confirmation_code.as_deref(), Some("1234"));+    assert_eq!(o.tac, Some([0x35, 0x29, 0x06, 0x11]));+    assert!(o.imei.is_some());+    let o = download_options_from(None, None, None);+    assert_eq!(o.tac, Some(es10b::DEFAULT_TAC));+    assert_eq!(non_empty(Some(String::new())), None);+    assert_eq!(non_empty(Some(" x".into())), Some(" x".to_string()));+    assert_eq!(non_blank(Some("  ".into())), None);+    // Nickname seeding only on success with a decodable ICCID + name.+    assert!(nickname_request(&ok, Some(" Carrier ")).is_some());+    assert!(nickname_request(&ok, None).is_none());+    let failed = es10b::InstallResult { success: false, ..ok.clone() };+    assert!(nickname_request(&failed, Some("x")).is_none());+    let no_iccid = es10b::InstallResult { installed_iccid: String::new(), ..ok.clone() };+    assert!(nickname_request(&no_iccid, Some("x")).is_none());+    assert!(progress_decision(Some(false)) == false);+    assert!(progress_decision(Some(true)));+    assert!(progress_decision(None));+}++#[test]+fn run_flows_with_mock_transport() {+    let _guard = TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());+    sessions().clear();+    // run_download: bad code, success, failure.+    let mut ok_fn = |_: &mut (), _c: &str| Ok(es10b::InstallResult { success: true, message: "m".into(), seq_number: 0, installed_iccid: "aa".into(), bpp_command_id: None, error_reason: None, notification: vec![] });+    assert_eq!(run_download(&mut (), None, &mut ok_fn)["message"], "Invalid activation code");+    assert_eq!(run_download(&mut (), Some("LPA:1".into()), &mut ok_fn)["iccid"], "aa");+    let mut err_fn = |_: &mut (), _c: &str| Err::<es10b::InstallResult, String>("down".into());+    assert_eq!(run_download(&mut (), Some("LPA:1".into()), &mut err_fn)["message"], "down");+    // run_authenticate success stores the session; failure does not.+    let mut auth_ok = |_: &mut (), _c: &str, _o: &download::DownloadOptions| Ok(session("tx-flow"));+    let v = run_authenticate(&mut (), "code", &download::DownloadOptions::default(), &mut auth_ok);+    assert_eq!(v["transactionId"], "tx-flow");+    assert!(session_take("tx-flow").is_some());+    let mut auth_err = |_: &mut (), _c: &str, _o: &download::DownloadOptions| Err::<download::DownloadSession, String>("bad".into());+    assert_eq!(run_authenticate(&mut (), "code", &download::DownloadOptions::default(), &mut auth_err)["error"], "bad");+    // run_finish: expired, success (with nickname seeding), failure.+    let mut fin_ok = |_: &mut (), _s: &download::DownloadSession, _c: Option<&str>| Ok(es10b::InstallResult { success: true, message: "m".into(), seq_number: 0, installed_iccid: "abcd".into(), bpp_command_id: None, error_reason: None, notification: vec![] });+    let applied = std::cell::RefCell::new(Vec::<Vec<u8>>::new());+    let mut apply = |_: &mut (), req: &[u8]| applied.borrow_mut().push(req.to_vec());+    assert_eq!(run_finish(&mut (), "missing", None, None, &mut fin_ok, &mut apply)["message"], "Download session expired — start again");+    session_put("tx-fin".into(), session("tx-fin"));+    let v = run_finish(&mut (), "tx-fin", Some("1234"), Some("Carrier"), &mut fin_ok, &mut apply);+    assert_eq!(v["success"], true);+    assert_eq!(applied.borrow().len(), 1, "nickname seeded once");+    session_put("tx-fin2".into(), session("tx-fin2"));+    let mut fin_err = |_: &mut (), _s: &download::DownloadSession, _c: Option<&str>| Err::<es10b::InstallResult, String>("install broke".into());+    assert_eq!(run_finish(&mut (), "tx-fin2", None, None, &mut fin_err, &mut apply)["message"], "install broke");+    // run_cancel: bad handle false; present session cancelled + consumed; absent still true.+    let cancelled = std::cell::RefCell::new(Vec::<i32>::new());+    let mut cancel_fn = |_: &mut (), _s: &download::DownloadSession, r: es10b::CancelReason| cancelled.borrow_mut().push(r as i32);+    assert!(!run_cancel(&mut (), None, 0, &mut cancel_fn));+    session_put("tx-cancel".into(), session("tx-cancel"));+    assert!(run_cancel(&mut (), Some("tx-cancel".into()), 2, &mut cancel_fn));+    assert_eq!(*cancelled.borrow(), vec![2]);+    assert!(run_cancel(&mut (), Some("tx-cancel".into()), 0, &mut cancel_fn));+    assert_eq!(cancelled.borrow().len(), 1);+}++#[test]+fn session_eviction_is_oldest_first() {+    let _guard = TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());+    sessions().clear();+    for i in 0..=MAX_SESSIONS {+        session_put(format!("tx-{i}"), session(&format!("tx-{i}")));+    }+    assert!(session_take("tx-0").is_none(), "oldest must be evicted");+    for i in 1..=MAX_SESSIONS {+        assert!(session_take(&format!("tx-{i}")).is_some());+    }+}
euicc/src/main/rust/src/jni_tests.rs
diff --git a/euicc/src/main/rust/src/jni_tests.rs b/euicc/src/main/rust/src/jni_tests.rsindex 738cf8c41a..4be2082624 100644--- a/euicc/src/main/rust/src/jni_tests.rs+++ b/euicc/src/main/rust/src/jni_tests.rs@@ -50,3 +50,64 @@ fn chunk_is_clamped_to_apdu_limits() {     assert_eq!(apdus[0][4], 255);     assert_eq!(apdus[1][4], 45); }++#[test]+fn store_data_with_reassembles_blocks() {+    // Two chunks; intermediate reply carries data, final carries data + SW.+    let cmd: Vec<u8> = (0..70u8).collect();+    let mut replies: Vec<Vec<u8>> = vec![vec![0xAA, 0x90, 0x00], vec![0xBB, 0xCC, 0x90, 0x00]];+    let mut tx = |_: &mut (), _apdu: &[u8]| Ok::<Vec<u8>, String>(replies.remove(0));+    assert_eq!(store_data_with(&mut (), &cmd, 63, &mut tx).unwrap(), vec![0xAA, 0xBB, 0xCC]);+    // Empty command: one empty block, empty data back.+    let mut tx = |_: &mut (), _apdu: &[u8]| Ok::<Vec<u8>, String>(vec![0x90, 0x00]);+    assert_eq!(store_data_with(&mut (), &[], 63, &mut tx).unwrap(), Vec::<u8>::new());+}++#[test]+fn store_data_with_error_rules() {+    let mut short = |_: &mut (), _apdu: &[u8]| Ok::<Vec<u8>, String>(vec![0x90]);+    assert_eq!(store_data_with(&mut (), &[1], 63, &mut short).unwrap_err(), "APDU response too short");+    let mut bad_sw = |_: &mut (), _apdu: &[u8]| Ok::<Vec<u8>, String>(vec![0x6A, 0x88]);+    assert_eq!(store_data_with(&mut (), &[1], 63, &mut bad_sw).unwrap_err(), "eUICC returned SW=6A88");+    // Intermediate non-success SW fails fast even if a later block would succeed.+    let mut replies: Vec<Vec<u8>> = vec![vec![0x63, 0xC1], vec![0x90, 0x00]];+    let mut tx = |_: &mut (), _apdu: &[u8]| Ok::<Vec<u8>, String>(replies.remove(0));+    assert_eq!(store_data_with(&mut (), &[0u8; 70], 63, &mut tx).unwrap_err(), "eUICC returned SW=63C1");+    let mut boom = |_: &mut (), _apdu: &[u8]| Err::<Vec<u8>, String>("transport down".into());+    assert_eq!(store_data_with(&mut (), &[1], 63, &mut boom).unwrap_err(), "transport down");+}++#[test]+fn json_converters_and_result_code() {+    let p = crate::es10::ProfileInfo { iccid: "89".into(), iccid_display: "8901".into(), isdp_aid: "A0".into(), state: "enabled".into(), class: "operational".into(), nickname: "nick".into(), service_provider: "Carrier".into(), name: "Plan".into() };+    let v: serde_json::Value = serde_json::from_str(&profiles_json(&[p])).unwrap();+    assert_eq!(v[0]["iccidDisplay"], "8901");+    assert_eq!(v[0]["serviceProvider"], "Carrier");+    assert_eq!(profiles_json(&[]), "[]");+    let n = crate::es10::NotificationInfo { seq_number: 7, operation: "install".into(), address: "a.b".into(), iccid_display: "8901".into() };+    let v: serde_json::Value = serde_json::from_str(&notifications_json(&[n])).unwrap();+    assert_eq!(v[0]["seqNumber"], 7);+    assert_eq!(v[0]["operation"], "install");+    let info = crate::es10::EuiccInfo1 { svn: "2.2.0".into(), ci_pkid_verification: vec!["aa".into()], ci_pkid_signing: vec!["bb".into()] };+    let v: serde_json::Value = serde_json::from_str(&euicc_info_json(&info)).unwrap();+    assert_eq!(v["svn"], "2.2.0");+    assert_eq!(v["ciPkIdListForVerification"][0], "aa");+    // result_code: build a parseable Enable result (BF31 { 80 00 }) and failures.+    let ok_resp = crate::es10::build_enable(&[0x01], true);+    let _ = ok_resp;+    let resp = crate::asn1::tlv(crate::es10::RESULT_TAG_ENABLE, &crate::asn1::tlv(0x80, &[0x00]));+    assert_eq!(result_code(Ok(resp), crate::es10::RESULT_TAG_ENABLE), 0);+    let resp = crate::asn1::tlv(crate::es10::RESULT_TAG_ENABLE, &crate::asn1::tlv(0x80, &[0x02]));+    assert_eq!(result_code(Ok(resp), crate::es10::RESULT_TAG_ENABLE), 2);+    assert_eq!(result_code(Err("x".into()), crate::es10::RESULT_TAG_ENABLE), -1);+    assert_eq!(result_code(Ok(vec![]), crate::es10::RESULT_TAG_ENABLE), -1);+    assert_eq!(seq_arg(-1), None);+    assert_eq!(seq_arg(0), Some(0));+    assert_eq!(seq_arg(42), Some(42));+}++#[test]+fn remove_code_mapping() {+    assert_eq!(remove_code(Err("x".into())), -1);+    assert_eq!(remove_code(Ok(vec![])), -1);+}