tauri-plugin-secure-element 0.1.0-beta.4

Tauri plugin for secure element use on iOS (Secure Enclave) and Android (Strongbox and TEE).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use serde::de::DeserializeOwned;
use tauri::{plugin::PluginApi, AppHandle, Runtime};

use crate::models::*;

// macOS FFI bindings - using extern "C" for direct linking
#[cfg(target_os = "macos")]
extern "C" {
    fn secure_element_list_keys(
        key_name: *const std::ffi::c_char,
        public_key: *const std::ffi::c_char,
    ) -> *mut std::ffi::c_char;
    fn secure_element_check_support() -> *mut std::ffi::c_char;
    fn secure_element_generate_secure_key(
        key_name: *const std::ffi::c_char,
        auth_mode: *const std::ffi::c_char,
    ) -> *mut std::ffi::c_char;
    fn secure_element_sign_with_key(
        key_name: *const std::ffi::c_char,
        data_base64: *const std::ffi::c_char,
    ) -> *mut std::ffi::c_char;
    fn secure_element_delete_key(
        key_name: *const std::ffi::c_char,
        public_key: *const std::ffi::c_char,
    ) -> *mut std::ffi::c_char;
}

/// Helper module for macOS FFI operations
#[cfg(target_os = "macos")]
mod ffi_helpers {
    use std::ffi::CStr;

    /// RAII guard for malloc'd pointers that automatically calls libc::free on drop.
    /// Ensures memory is freed even if a panic occurs during string conversion.
    pub struct MallocGuard(*mut std::ffi::c_char);

    impl MallocGuard {
        /// Creates a new guard that will free the pointer on drop.
        /// Returns None if the pointer is null.
        pub fn new(ptr: *mut std::ffi::c_char) -> Option<Self> {
            if ptr.is_null() {
                None
            } else {
                Some(Self(ptr))
            }
        }

        /// Returns the raw pointer for use with CStr functions.
        pub fn as_ptr(&self) -> *const std::ffi::c_char {
            self.0
        }
    }

    impl Drop for MallocGuard {
        fn drop(&mut self) {
            if !self.0.is_null() {
                unsafe {
                    libc::free(self.0 as *mut libc::c_void);
                }
            }
        }
    }

    /// Converts an FFI C string pointer to a Rust String and frees the memory.
    /// The pointer must have been allocated by Swift using malloc/strdup.
    ///
    /// # Safety
    /// - `ptr` must be a valid, non-null pointer to a null-terminated C string
    /// - `ptr` must have been allocated by malloc (will be freed with libc::free)
    pub unsafe fn ffi_string_to_owned(ptr: *mut std::ffi::c_char) -> crate::Result<String> {
        let guard = MallocGuard::new(ptr)
            .ok_or_else(|| crate::Error::Io(std::io::Error::other("FFI call returned null")))?;

        // Convert to owned String - guard ensures ptr is freed even if this panics
        let s = CStr::from_ptr(guard.as_ptr())
            .to_str()
            .map_err(|_| {
                crate::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "Invalid UTF-8 in FFI result",
                ))
            })?
            .to_string();

        if s.is_empty() {
            return Err(crate::Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "FFI call returned empty string",
            )));
        }

        Ok(s)
    }

    /// Maximum size of a JSON response from FFI (1MB).
    /// Prevents memory exhaustion from unexpectedly large responses.
    const MAX_FFI_RESPONSE_SIZE: usize = 1024 * 1024;

    /// Parses a JSON response from FFI, checking for error field first.
    /// Returns the parsed response or an error if the JSON contains an "error" field.
    pub fn parse_ffi_response<T: serde::de::DeserializeOwned>(json: &str) -> crate::Result<T> {
        if json.len() > MAX_FFI_RESPONSE_SIZE {
            return Err(crate::Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "FFI response exceeds maximum allowed size",
            )));
        }

        // First check if response contains an error
        let value: serde_json::Value = serde_json::from_str(json).map_err(|e| {
            crate::Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Failed to parse JSON: {}", e),
            ))
        })?;

        if let Some(error_msg) = value.get("error").and_then(|v| v.as_str()) {
            return Err(crate::Error::Io(std::io::Error::other(error_msg)));
        }

        // Now deserialize to the expected type
        serde_json::from_str(json).map_err(|e| {
            crate::Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Failed to deserialize response: {}", e),
            ))
        })
    }

    /// Converts an optional String to a CString, returning the pointer and keeping the CString alive.
    /// Returns (null pointer, None) if the input is None or contains null bytes.
    pub fn optional_to_cstring(
        s: Option<&String>,
    ) -> (*const std::ffi::c_char, Option<std::ffi::CString>) {
        match s {
            Some(s) => match std::ffi::CString::new(s.as_str()) {
                Ok(cstr) => {
                    let ptr = cstr.as_ptr();
                    (ptr, Some(cstr))
                }
                Err(_) => (std::ptr::null(), None),
            },
            None => (std::ptr::null(), None),
        }
    }
}

#[cfg(target_os = "windows")]
use crate::windows;

pub fn init<R: Runtime, C: DeserializeOwned>(
    app: &AppHandle<R>,
    _api: PluginApi<R, C>,
) -> crate::Result<SecureElement<R>> {
    Ok(SecureElement(app.clone()))
}

/// Access to the secure-element APIs.
pub struct SecureElement<R: Runtime>(AppHandle<R>);

impl<R: Runtime> SecureElement<R> {
    /// Gets the application identifier for key scoping
    #[cfg(target_os = "windows")]
    fn get_app_id(&self) -> String {
        self.0.config().identifier.clone()
    }
}

impl<R: Runtime> SecureElement<R> {
    pub fn ping(&self, payload: PingRequest) -> crate::Result<PingResponse> {
        Ok(PingResponse {
            value: payload.value,
        })
    }

    /// Gets the HWND from the main window for Windows Hello UI parenting
    #[cfg(target_os = "windows")]
    fn get_main_window_hwnd(&self) -> Option<isize> {
        use raw_window_handle::HasWindowHandle;
        use tauri::Manager;

        let webview_windows = self.0.webview_windows();
        let window = webview_windows.values().next()?;
        let handle = window.window_handle().ok()?;
        windows::hwnd_from_raw(handle.as_raw())
    }

    pub fn generate_secure_key(
        &self,
        payload: GenerateSecureKeyRequest,
    ) -> crate::Result<GenerateSecureKeyResponse> {
        #[cfg(target_os = "macos")]
        {
            use std::ffi::CString;

            let key_name_cstr = CString::new(payload.key_name.as_str()).map_err(|e| {
                crate::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("Invalid key_name: {}", e),
                ))
            })?;

            let auth_mode_str = match payload.auth_mode {
                crate::models::AuthenticationMode::None => "none",
                crate::models::AuthenticationMode::PinOrBiometric => "pinOrBiometric",
                crate::models::AuthenticationMode::BiometricOnly => "biometricOnly",
            };
            let auth_mode_cstr = CString::new(auth_mode_str).map_err(|e| {
                crate::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("Invalid auth_mode: {}", e),
                ))
            })?;

            let result_ptr = unsafe {
                secure_element_generate_secure_key(key_name_cstr.as_ptr(), auth_mode_cstr.as_ptr())
            };

            let json = unsafe { ffi_helpers::ffi_string_to_owned(result_ptr)? };
            ffi_helpers::parse_ffi_response(&json)
        }
        #[cfg(target_os = "windows")]
        {
            use base64::Engine;

            let app_id = self.get_app_id();

            // Create the key with the appropriate provider based on auth mode
            let key = windows::create_key(&app_id, &payload.key_name, &payload.auth_mode)?;

            // Export the public key
            let public_key_bytes = windows::export_public_key(&key)?;
            let public_key = base64::engine::general_purpose::STANDARD.encode(&public_key_bytes);

            Ok(GenerateSecureKeyResponse {
                key_name: payload.key_name,
                public_key,
            })
        }
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            let _ = payload;
            Err(crate::Error::Io(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "Secure element not available on this platform",
            )))
        }
    }

    pub fn list_keys(&self, payload: ListKeysRequest) -> crate::Result<ListKeysResponse> {
        #[cfg(target_os = "macos")]
        {
            let (key_name_ptr, _key_name_cstr_guard) =
                ffi_helpers::optional_to_cstring(payload.key_name.as_ref());
            let (public_key_ptr, _public_key_cstr_guard) =
                ffi_helpers::optional_to_cstring(payload.public_key.as_ref());

            let result_ptr = unsafe { secure_element_list_keys(key_name_ptr, public_key_ptr) };

            let json = unsafe { ffi_helpers::ffi_string_to_owned(result_ptr)? };
            ffi_helpers::parse_ffi_response(&json)
        }
        #[cfg(target_os = "windows")]
        {
            let app_id = self.get_app_id();

            // List keys from both providers
            let keys = windows::list_keys(
                &app_id,
                payload.key_name.as_deref(),
                payload.public_key.as_deref(),
            )?;

            Ok(ListKeysResponse { keys })
        }
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            let _ = payload;
            Err(crate::Error::Io(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "Secure element not available on this platform",
            )))
        }
    }

    pub fn sign_with_key(&self, payload: SignWithKeyRequest) -> crate::Result<SignWithKeyResponse> {
        #[cfg(target_os = "macos")]
        {
            use base64::Engine;
            use std::ffi::CString;

            let key_name_cstr = CString::new(payload.key_name.as_str()).map_err(|e| {
                crate::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("Invalid key_name: {}", e),
                ))
            })?;

            let data_base64 = base64::engine::general_purpose::STANDARD.encode(&payload.data);
            let data_base64_cstr = CString::new(data_base64.as_str()).map_err(|e| {
                crate::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("Invalid data: {}", e),
                ))
            })?;

            let result_ptr = unsafe {
                secure_element_sign_with_key(key_name_cstr.as_ptr(), data_base64_cstr.as_ptr())
            };

            let json = unsafe { ffi_helpers::ffi_string_to_owned(result_ptr)? };

            // Parse and extract signature manually since we need to decode base64
            let value: serde_json::Value = serde_json::from_str(&json).map_err(|e| {
                crate::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Failed to parse JSON: {}", e),
                ))
            })?;

            if let Some(error_msg) = value.get("error").and_then(|v| v.as_str()) {
                return Err(crate::Error::Io(std::io::Error::other(error_msg)));
            }

            let signature_base64 =
                value
                    .get("signature")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        crate::Error::Io(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "Missing signature in response",
                        ))
                    })?;

            let signature = base64::engine::general_purpose::STANDARD
                .decode(signature_base64)
                .map_err(|e| {
                    crate::Error::Io(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Failed to decode signature: {}", e),
                    ))
                })?;

            Ok(SignWithKeyResponse { signature })
        }
        #[cfg(target_os = "windows")]
        {
            let app_id = self.get_app_id();

            // Open the key and detect which provider it's from
            let (key, provider_type) = windows::open_key_auto(&app_id, &payload.key_name)?;

            // Hash the data first (NCrypt expects pre-hashed data for ECDSA)
            let hash = windows::sha256_hash(&payload.data)?;

            // Sign the hash - use Windows Hello for NGC keys
            let signature = match provider_type {
                windows::KeyProviderType::Ngc => {
                    // Get HWND for Windows Hello dialog parenting
                    let hwnd = self.get_main_window_hwnd();
                    windows::sign_hash_with_window(&key, &hash, hwnd)?
                }
                windows::KeyProviderType::Tpm => {
                    // Silent signing for TPM keys
                    windows::sign_hash(&key, &hash)?
                }
            };

            Ok(SignWithKeyResponse { signature })
        }
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            let _ = payload;
            Err(crate::Error::Io(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "Secure element not available on this platform",
            )))
        }
    }

    pub fn delete_key(&self, payload: DeleteKeyRequest) -> crate::Result<DeleteKeyResponse> {
        #[cfg(target_os = "macos")]
        {
            let (key_name_ptr, _key_name_cstr_guard) =
                ffi_helpers::optional_to_cstring(payload.key_name.as_ref());
            let (public_key_ptr, _public_key_cstr_guard) =
                ffi_helpers::optional_to_cstring(payload.public_key.as_ref());

            let result_ptr = unsafe { secure_element_delete_key(key_name_ptr, public_key_ptr) };

            let json = unsafe { ffi_helpers::ffi_string_to_owned(result_ptr)? };

            // Parse and extract success field
            let value: serde_json::Value = serde_json::from_str(&json).map_err(|e| {
                crate::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Failed to parse JSON: {}", e),
                ))
            })?;

            if let Some(error_msg) = value.get("error").and_then(|v| v.as_str()) {
                return Err(crate::Error::Io(std::io::Error::other(error_msg)));
            }

            let success = value
                .get("success")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);

            Ok(DeleteKeyResponse { success })
        }
        #[cfg(target_os = "windows")]
        {
            let app_id = self.get_app_id();

            // If key_name is provided, delete by name
            // If public_key is provided, find the key with that public key first
            // If neither, return error
            let key_name = if let Some(name) = &payload.key_name {
                name.clone()
            } else if let Some(public_key) = &payload.public_key {
                // Find key by public key - fail silently if not found
                let keys = match windows::list_keys(&app_id, None, Some(public_key)) {
                    Ok(keys) => keys,
                    Err(_) => return Ok(DeleteKeyResponse { success: true }),
                };
                if keys.is_empty() {
                    return Ok(DeleteKeyResponse { success: true });
                }
                keys[0].key_name.clone()
            } else {
                return Err(crate::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "Either key_name or public_key must be provided",
                )));
            };

            // Open key - fail silently if key not found
            // Use open_key_auto to find the key in either provider
            let (key, _provider_type) = match windows::open_key_auto(&app_id, &key_name) {
                Ok(result) => result,
                Err(_) => return Ok(DeleteKeyResponse { success: true }),
            };
            let success = windows::delete_key(key)?;

            Ok(DeleteKeyResponse { success })
        }
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            let _ = payload;
            Err(crate::Error::Io(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "Secure element not available on this platform",
            )))
        }
    }

    pub fn check_secure_element_support(&self) -> crate::Result<CheckSecureElementSupportResponse> {
        #[cfg(target_os = "macos")]
        {
            let result_ptr = unsafe { secure_element_check_support() };
            let json = unsafe { ffi_helpers::ffi_string_to_owned(result_ptr)? };
            ffi_helpers::parse_ffi_response(&json)
        }
        #[cfg(target_os = "windows")]
        {
            Ok(windows::get_secure_element_capabilities())
        }
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            // On unsupported desktop platforms, return that secure element is not supported
            Ok(CheckSecureElementSupportResponse {
                discrete: false,
                integrated: false,
                firmware: false,
                emulated: false,
                strongest: crate::models::SecureElementBacking::None,
                can_enforce_biometric_only: false,
            })
        }
    }
}