corteq-onepassword 0.1.5

Secure 1Password SDK wrapper with FFI bindings for Rust applications
Documentation
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! Native library loading for the 1Password SDK.
//!
//! This module handles loading the `libop_uniffi_core` native library
//! at runtime using the `libloading` crate. The library uses UniFFI-generated
//! bindings with RustBuffer-based data passing.

use super::uniffi_types::{ForeignBytes, RustBuffer, RustCallStatus, CALL_SUCCESS};
use crate::error::{Error, Result};
use libloading::{Library, Symbol};
use std::ffi::c_void;
use std::path::{Path, PathBuf};
use std::sync::Arc;

// UniFFI symbol names for the 1Password SDK
const SYMBOL_INIT_CLIENT: &[u8] = b"uniffi_op_uniffi_core_fn_func_init_client\0";
const SYMBOL_INVOKE_SYNC: &[u8] = b"uniffi_op_uniffi_core_fn_func_invoke_sync\0";
const SYMBOL_RELEASE_CLIENT: &[u8] = b"uniffi_op_uniffi_core_fn_func_release_client\0";
const SYMBOL_RUSTBUFFER_FREE: &[u8] = b"ffi_op_uniffi_core_rustbuffer_free\0";
const SYMBOL_RUSTBUFFER_FROM_BYTES: &[u8] = b"ffi_op_uniffi_core_rustbuffer_from_bytes\0";

// Async future handling symbols
const SYMBOL_FUTURE_POLL_RUST_BUFFER: &[u8] = b"ffi_op_uniffi_core_rust_future_poll_rust_buffer\0";
const SYMBOL_FUTURE_COMPLETE_RUST_BUFFER: &[u8] =
    b"ffi_op_uniffi_core_rust_future_complete_rust_buffer\0";
const SYMBOL_FUTURE_FREE_RUST_BUFFER: &[u8] = b"ffi_op_uniffi_core_rust_future_free_rust_buffer\0";

/// Type alias for the init_client FFI function.
///
/// Takes a JSON config as a RustBuffer and returns a future handle.
/// The actual client_id (as a string) is obtained by polling and completing the future.
type InitClientFn = unsafe extern "C" fn(config: RustBuffer) -> *mut c_void;

/// Type alias for the invoke_sync FFI function.
///
/// Takes method JSON as RustBuffer (client ID is in the JSON payload), returns result as RustBuffer.
type InvokeSyncFn =
    unsafe extern "C" fn(method: RustBuffer, call_status: *mut RustCallStatus) -> RustBuffer;

/// Type alias for the release_client FFI function.
///
/// Releases a client session by client_id (string serialized as RustBuffer).
type ReleaseClientFn =
    unsafe extern "C" fn(client_id: RustBuffer, call_status: *mut RustCallStatus);

/// Type alias for the rustbuffer_free FFI function.
///
/// Frees a RustBuffer.
type RustBufferFreeFn = unsafe extern "C" fn(buf: RustBuffer, call_status: *mut RustCallStatus);

/// Type alias for the rustbuffer_from_bytes FFI function.
///
/// Creates a RustBuffer from foreign bytes.
type RustBufferFromBytesFn =
    unsafe extern "C" fn(bytes: ForeignBytes, call_status: *mut RustCallStatus) -> RustBuffer;

/// Callback type for async future polling.
///
/// Called when a future poll completes with (callback_data, poll_code).
/// poll_code: 0 = READY, 1 = MAYBE_READY (need to poll again)
type FutureContinuationCallback = extern "C" fn(callback_data: usize, poll_code: i8);

/// Type alias for the rust_future_poll_rust_buffer FFI function.
///
/// Polls an async future that returns a RustBuffer.
type FuturePollRustBufferFn = unsafe extern "C" fn(
    handle: *mut c_void,
    callback: FutureContinuationCallback,
    callback_data: usize,
);

/// Type alias for the rust_future_complete_rust_buffer FFI function.
///
/// Completes an async future and returns the result as a RustBuffer.
type FutureCompleteRustBufferFn =
    unsafe extern "C" fn(handle: *mut c_void, call_status: *mut RustCallStatus) -> RustBuffer;

/// Type alias for the rust_future_free_rust_buffer FFI function.
///
/// Frees an async future handle.
type FutureFreeRustBufferFn = unsafe extern "C" fn(handle: *mut c_void);

/// Wrapper around the loaded native library.
///
/// This struct manages the lifecycle of the loaded library and provides
/// safe access to FFI functions.
pub(crate) struct NativeLibrary {
    /// The loaded library (kept alive for the lifetime of this struct).
    #[allow(dead_code)]
    library: Library,

    /// Pointer to init_client function.
    init_client: InitClientFn,

    /// Pointer to invoke_sync function.
    invoke_sync: InvokeSyncFn,

    /// Pointer to release_client function.
    release_client: ReleaseClientFn,

    /// Pointer to rustbuffer_free function.
    rustbuffer_free: RustBufferFreeFn,

    /// Pointer to rustbuffer_from_bytes function.
    rustbuffer_from_bytes: RustBufferFromBytesFn,

    /// Pointer to rust_future_poll_rust_buffer function.
    future_poll_rust_buffer: FuturePollRustBufferFn,

    /// Pointer to rust_future_complete_rust_buffer function.
    future_complete_rust_buffer: FutureCompleteRustBufferFn,

    /// Pointer to rust_future_free_rust_buffer function.
    future_free_rust_buffer: FutureFreeRustBufferFn,
}

// SAFETY: The library handle and function pointers are thread-safe.
// The SDK internally handles synchronization for concurrent calls.
unsafe impl Send for NativeLibrary {}
unsafe impl Sync for NativeLibrary {}

impl NativeLibrary {
    /// Load the native library from the given path.
    ///
    /// # Safety
    ///
    /// This function loads a native library which is inherently unsafe.
    /// The library must be the official 1Password SDK library verified
    /// via SHA256 checksum during the build process.
    pub fn load(path: &Path) -> Result<Self> {
        // SAFETY: We trust the library path from the build script which
        // verified the SHA256 checksum.
        let library = unsafe { Library::new(path) }.map_err(|e| Error::LibraryLoadError {
            message: format!("failed to load library at {}: {}", path.display(), e),
        })?;

        // Load function symbols
        // SAFETY: These symbols are defined by the UniFFI-generated library
        let init_client: InitClientFn = unsafe {
            let sym: Symbol<InitClientFn> =
                library
                    .get(SYMBOL_INIT_CLIENT)
                    .map_err(|e| Error::LibraryLoadError {
                        message: format!("failed to load init_client: {e}"),
                    })?;
            *sym
        };

        let invoke_sync: InvokeSyncFn = unsafe {
            let sym: Symbol<InvokeSyncFn> =
                library
                    .get(SYMBOL_INVOKE_SYNC)
                    .map_err(|e| Error::LibraryLoadError {
                        message: format!("failed to load invoke_sync: {e}"),
                    })?;
            *sym
        };

        let release_client: ReleaseClientFn = unsafe {
            let sym: Symbol<ReleaseClientFn> =
                library
                    .get(SYMBOL_RELEASE_CLIENT)
                    .map_err(|e| Error::LibraryLoadError {
                        message: format!("failed to load release_client: {e}"),
                    })?;
            *sym
        };

        let rustbuffer_free: RustBufferFreeFn = unsafe {
            let sym: Symbol<RustBufferFreeFn> =
                library
                    .get(SYMBOL_RUSTBUFFER_FREE)
                    .map_err(|e| Error::LibraryLoadError {
                        message: format!("failed to load rustbuffer_free: {e}"),
                    })?;
            *sym
        };

        let rustbuffer_from_bytes: RustBufferFromBytesFn = unsafe {
            let sym: Symbol<RustBufferFromBytesFn> = library
                .get(SYMBOL_RUSTBUFFER_FROM_BYTES)
                .map_err(|e| Error::LibraryLoadError {
                    message: format!("failed to load rustbuffer_from_bytes: {e}"),
                })?;
            *sym
        };

        let future_poll_rust_buffer: FuturePollRustBufferFn = unsafe {
            let sym: Symbol<FuturePollRustBufferFn> = library
                .get(SYMBOL_FUTURE_POLL_RUST_BUFFER)
                .map_err(|e| Error::LibraryLoadError {
                message: format!("failed to load rust_future_poll_rust_buffer: {e}"),
            })?;
            *sym
        };

        let future_complete_rust_buffer: FutureCompleteRustBufferFn = unsafe {
            let sym: Symbol<FutureCompleteRustBufferFn> = library
                .get(SYMBOL_FUTURE_COMPLETE_RUST_BUFFER)
                .map_err(|e| Error::LibraryLoadError {
                    message: format!("failed to load rust_future_complete_rust_buffer: {e}"),
                })?;
            *sym
        };

        let future_free_rust_buffer: FutureFreeRustBufferFn = unsafe {
            let sym: Symbol<FutureFreeRustBufferFn> = library
                .get(SYMBOL_FUTURE_FREE_RUST_BUFFER)
                .map_err(|e| Error::LibraryLoadError {
                message: format!("failed to load rust_future_free_rust_buffer: {e}"),
            })?;
            *sym
        };

        Ok(Self {
            library,
            init_client,
            invoke_sync,
            release_client,
            rustbuffer_free,
            rustbuffer_from_bytes,
            future_poll_rust_buffer,
            future_complete_rust_buffer,
            future_free_rust_buffer,
        })
    }

    /// Convert a string to a RustBuffer.
    ///
    /// The returned buffer is owned by Rust and must be freed or passed
    /// to an FFI function that takes ownership.
    fn string_to_rustbuffer(&self, s: &str) -> Result<RustBuffer> {
        let bytes = s.as_bytes();
        let foreign_bytes = ForeignBytes {
            len: bytes.len() as i32,
            data: bytes.as_ptr(),
        };

        let mut call_status = RustCallStatus::new();

        // SAFETY: foreign_bytes points to valid data for the duration of this call
        let buffer = unsafe { (self.rustbuffer_from_bytes)(foreign_bytes, &mut call_status) };

        if !call_status.is_success() {
            let error_msg = self.extract_error_message(&call_status);
            // SAFETY: We checked that call failed, so error_buf is initialized
            let error_buf = unsafe { call_status.take_error_buf() };
            if !error_buf.is_empty() {
                self.free_rustbuffer(error_buf);
            }
            return Err(Error::SdkError {
                message: error_msg.unwrap_or_else(|| "failed to allocate buffer".to_string()),
            });
        }

        Ok(buffer)
    }

    /// Convert a RustBuffer to a String.
    ///
    /// This consumes the buffer (it will be freed after reading).
    fn rustbuffer_to_string(&self, buffer: RustBuffer) -> Option<String> {
        if buffer.is_empty() {
            return None;
        }

        // SAFETY: The buffer was returned by an FFI call and is valid
        let bytes = unsafe { buffer.as_slice() };
        let result = String::from_utf8_lossy(bytes).into_owned();

        // Free the buffer
        self.free_rustbuffer(buffer);

        Some(result)
    }

    /// Free a RustBuffer.
    fn free_rustbuffer(&self, buffer: RustBuffer) {
        if buffer.is_empty() {
            return;
        }

        let mut call_status = RustCallStatus::new();
        // SAFETY: The buffer was allocated by the SDK
        unsafe {
            (self.rustbuffer_free)(buffer, &mut call_status);
        }
        // We ignore errors from free - there's nothing we can do about them
    }

    /// Extract error message from a RustCallStatus.
    ///
    /// # Safety
    ///
    /// This should only be called when `status.code != CALL_SUCCESS`.
    fn extract_error_message(&self, status: &RustCallStatus) -> Option<String> {
        if status.code == CALL_SUCCESS {
            return None;
        }

        // SAFETY: We checked that code indicates an error, so error_buf is initialized
        let error_buf = unsafe { status.error_buf() };

        // The error_buf contains serialized error data
        // For now, we'll try to read it as UTF-8 text
        if error_buf.is_empty() {
            return Some(match status.code {
                1 => "SDK error (no details)".to_string(),
                2 => "SDK panicked".to_string(),
                _ => format!("Unknown error code: {}", status.code),
            });
        }

        // SAFETY: error_buf was set by the FFI call and we verified it's not empty
        let bytes = unsafe { error_buf.as_slice() };
        Some(String::from_utf8_lossy(bytes).into_owned())
    }

    /// Initialize a new client session.
    ///
    /// This is an async operation internally - we poll the future until complete.
    /// Returns the client_id as a string.
    pub fn init_client(&self, config_json: &str) -> Result<String> {
        let config_buffer = self.string_to_rustbuffer(config_json)?;

        // Call init_client which returns a future handle (no call_status for async start)
        // SAFETY: config_buffer is a valid RustBuffer
        let future_handle = unsafe { (self.init_client)(config_buffer) };

        if future_handle.is_null() {
            return Err(Error::AuthenticationFailed {
                message: "init_client returned null future handle".to_string(),
            });
        }

        // Poll the future until ready using a blocking approach
        self.poll_future_blocking(future_handle);

        // Complete the future and get the result
        let mut call_status = RustCallStatus::new();
        // SAFETY: future_handle is valid and we've polled until ready
        let result_buffer =
            unsafe { (self.future_complete_rust_buffer)(future_handle, &mut call_status) };

        // Free the future handle
        // SAFETY: future_handle is valid
        unsafe { (self.future_free_rust_buffer)(future_handle) };

        // Check for errors
        if !call_status.is_success() {
            let error_msg = self.extract_error_message(&call_status);
            // SAFETY: We checked that call failed, so error_buf is initialized
            let error_buf = unsafe { call_status.take_error_buf() };
            if !error_buf.is_empty() {
                self.free_rustbuffer(error_buf);
            }
            return Err(Error::AuthenticationFailed {
                message: error_msg.unwrap_or_else(|| "unknown error".to_string()),
            });
        }

        // Extract the client_id string from the result buffer
        self.rustbuffer_to_string(result_buffer)
            .ok_or_else(|| Error::AuthenticationFailed {
                message: "empty client_id from SDK".to_string(),
            })
    }

    /// Poll a future until it's ready using a blocking approach.
    ///
    /// Uses a local atomic and the callback_data parameter to avoid race conditions
    /// when multiple threads call this method simultaneously.
    fn poll_future_blocking(&self, future_handle: *mut c_void) {
        use std::sync::atomic::{AtomicI8, Ordering};

        // Poll code constants
        const POLL_READY: i8 = 0;
        const POLL_MAYBE_READY: i8 = 1;

        // Use local atomic for thread safety - each call gets its own storage
        // This fixes the race condition (CWE-362) from using a shared static
        let poll_result = AtomicI8::new(-1);

        // Callback that stores the poll code via the callback_data pointer
        extern "C" fn poll_callback(callback_data: usize, poll_code: i8) {
            // SAFETY: callback_data is a valid pointer to AtomicI8 on the caller's stack
            let result_ptr = callback_data as *const AtomicI8;
            unsafe { (*result_ptr).store(poll_code, Ordering::SeqCst) };
        }

        loop {
            // Reset the poll result
            poll_result.store(-1, Ordering::SeqCst);

            // Pass pointer to local atomic as callback_data
            let callback_data = &poll_result as *const AtomicI8 as usize;

            // Poll the future
            // SAFETY: future_handle is valid, callback is valid, callback_data points to valid stack memory
            unsafe {
                (self.future_poll_rust_buffer)(future_handle, poll_callback, callback_data);
            }

            // Wait for the callback to be called
            // The callback is called synchronously or from another thread
            loop {
                let result = poll_result.load(Ordering::SeqCst);
                if result >= 0 {
                    if result == POLL_READY {
                        return; // Future is ready
                    } else if result == POLL_MAYBE_READY {
                        break; // Need to poll again
                    }
                }
                // Small yield to avoid busy-spinning
                std::thread::yield_now();
            }
        }
    }

    /// Invoke an SDK method synchronously.
    ///
    /// The client_id must be included in the JSON payload as `invocation.clientId`.
    pub fn invoke_sync(&self, method_json: &str) -> Result<String> {
        let method_buffer = self.string_to_rustbuffer(method_json)?;

        let mut call_status = RustCallStatus::new();

        // SAFETY: method_buffer is valid, call_status is valid
        let result_buffer = unsafe { (self.invoke_sync)(method_buffer, &mut call_status) };

        if !call_status.is_success() {
            let error_msg = self.extract_error_message(&call_status);
            // SAFETY: We checked that call failed, so error_buf is initialized
            let error_buf = unsafe { call_status.take_error_buf() };
            if !error_buf.is_empty() {
                self.free_rustbuffer(error_buf);
            }
            // NOTE: Don't free result_buffer on error - it's undefined/invalid in that case
            return Err(Error::SdkError {
                message: error_msg.unwrap_or_else(|| "invocation failed".to_string()),
            });
        }

        // Convert and free the result buffer
        let response = self.rustbuffer_to_string(result_buffer);
        response.ok_or_else(|| Error::SdkError {
            message: "empty response from SDK".to_string(),
        })
    }

    /// Release a client session.
    ///
    /// The client_id is a string that was returned by init_client.
    pub fn release_client(&self, client_id: &str) {
        // Convert client_id string to RustBuffer
        let client_id_buffer = match self.string_to_rustbuffer(client_id) {
            Ok(buf) => buf,
            Err(_) => return, // Can't do much if we can't allocate the buffer
        };

        let mut call_status = RustCallStatus::new();

        // SAFETY: client_id_buffer is valid RustBuffer
        unsafe {
            (self.release_client)(client_id_buffer, &mut call_status);
        }

        // Only access error_buf if the call failed
        // (error_buf is MaybeUninit on success and contains garbage)
        if !call_status.is_success() {
            // SAFETY: We checked that call failed, so error_buf is initialized
            let error_buf = unsafe { call_status.take_error_buf() };
            if !error_buf.is_empty() {
                self.free_rustbuffer(error_buf);
            }
        }
    }
}

/// Find the library path.
///
/// This looks for the library in the following locations (in order):
/// 1. Path specified by `ONEPASSWORD_LIB_PATH` environment variable
/// 2. Bundled library in `src/libs/{platform}/`
/// 3. Build output directory (`OUT_DIR/lib/`) for PyPI download fallback
/// 4. System library paths (`/usr/local/lib`, `/usr/lib`) - **only if
///    `ONEPASSWORD_ALLOW_SYSTEM_LIB=1` is set** (disabled by default for security)
///
/// # Security
///
/// System path searching is disabled by default to prevent library hijacking attacks
/// (CWE-426). If an attacker has write access to system library directories, they could
/// substitute a malicious library. Use `ONEPASSWORD_ALLOW_SYSTEM_LIB=1` only if you
/// trust the system library paths on your deployment target.
pub(crate) fn find_library_path() -> Result<PathBuf> {
    // Check environment variable override
    if let Ok(path_str) = std::env::var("ONEPASSWORD_LIB_PATH") {
        let path = PathBuf::from(&path_str);
        if !path.exists() {
            return Err(Error::LibraryLoadError {
                message: format!(
                    "ONEPASSWORD_LIB_PATH points to non-existent file: {}",
                    path.display()
                ),
            });
        }

        // Canonicalize to prevent path traversal attacks (CWE-22)
        // This resolves symlinks and ".." sequences
        let canonical = path.canonicalize().map_err(|e| Error::LibraryLoadError {
            message: format!("failed to canonicalize ONEPASSWORD_LIB_PATH: {e}"),
        })?;

        // Verify filename matches expected library name to prevent loading arbitrary libraries
        let expected_name = library_filename();
        let actual_name = canonical.file_name().and_then(|n| n.to_str()).unwrap_or("");

        if actual_name != expected_name {
            return Err(Error::LibraryLoadError {
                message: format!(
                    "ONEPASSWORD_LIB_PATH must point to '{expected_name}', got '{actual_name}'"
                ),
            });
        }

        return Ok(canonical);
    }

    let lib_name = library_filename();

    // Check bundled library path (src/libs/{platform}/)
    let platform_dir = format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH);
    let bundled_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("src")
        .join("libs")
        .join(&platform_dir)
        .join(&lib_name);
    if bundled_path.exists() {
        return Ok(bundled_path);
    }

    // Check the build output directory (for PyPI download fallback)
    let out_dir_lib = PathBuf::from(env!("OUT_DIR")).join("lib").join(&lib_name);
    if out_dir_lib.exists() {
        return Ok(out_dir_lib);
    }

    // Try common system paths - only if explicitly allowed (CWE-426 mitigation)
    // This is disabled by default to prevent library hijacking attacks
    if std::env::var("ONEPASSWORD_ALLOW_SYSTEM_LIB").is_ok() {
        let system_paths = [PathBuf::from("/usr/local/lib"), PathBuf::from("/usr/lib")];

        for dir in &system_paths {
            let path = dir.join(&lib_name);
            if path.exists() {
                return Ok(path);
            }
        }
    }

    Err(Error::LibraryLoadError {
        message: format!(
            "could not find {lib_name}. Set ONEPASSWORD_LIB_PATH to a custom path, \
             rebuild the crate with bundled libraries, or set ONEPASSWORD_ALLOW_SYSTEM_LIB=1 \
             to search system paths (not recommended for security reasons)."
        ),
    })
}

/// Get the library filename for the current platform.
fn library_filename() -> String {
    #[cfg(target_os = "linux")]
    {
        "libop_uniffi_core.so".to_string()
    }

    #[cfg(target_os = "macos")]
    {
        "libop_uniffi_core.dylib".to_string()
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        compile_error!("Unsupported platform. Only Linux and macOS are supported.");
    }
}

/// Load the native library from the default location.
pub(crate) fn load_library() -> Result<Arc<NativeLibrary>> {
    let path = find_library_path()?;
    let library = NativeLibrary::load(&path)?;
    Ok(Arc::new(library))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;

    // ==========================================================================
    // Unit tests (no credentials needed)
    // ==========================================================================

    #[test]
    fn test_library_filename_format() {
        let name = library_filename();
        assert!(name.starts_with("libop_uniffi_core"));
        assert!(name.ends_with(".so") || name.ends_with(".dylib"));
    }

    #[test]
    fn test_find_library_path_finds_bundled() {
        let path = find_library_path().expect("should find bundled library");
        assert!(path.exists(), "library path should exist: {path:?}");
        assert!(
            path.to_string_lossy().contains("libop_uniffi_core"),
            "path should contain library name"
        );
    }

    #[test]
    #[serial]
    fn test_load_library_loads_all_symbols() {
        let library = load_library().expect("should load library");
        // If we got here, all FFI symbols were resolved successfully
        assert!(Arc::strong_count(&library) >= 1);
    }

    #[test]
    fn test_native_library_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<NativeLibrary>();
    }

    #[test]
    fn test_native_library_load_from_bundled_path() {
        let path = find_library_path().unwrap();
        let library = NativeLibrary::load(&path).expect("should load from bundled path");
        // Verify library is usable (we can't call functions without a token)
        let _ = &library;
    }

    #[test]
    #[serial]
    fn test_find_library_path_with_invalid_env_var() {
        let original = std::env::var("ONEPASSWORD_LIB_PATH").ok();

        // Set to non-existent path
        // SAFETY: This test is serialized to avoid race conditions
        unsafe {
            std::env::set_var(
                "ONEPASSWORD_LIB_PATH",
                "/nonexistent/path/libop_uniffi_core.so",
            );
        }
        let result = find_library_path();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("non-existent"));

        // Restore
        // SAFETY: This test is serialized to avoid race conditions
        unsafe {
            match original {
                Some(val) => std::env::set_var("ONEPASSWORD_LIB_PATH", val),
                None => std::env::remove_var("ONEPASSWORD_LIB_PATH"),
            }
        }
    }

    #[test]
    #[serial]
    fn test_find_library_path_with_wrong_filename() {
        let original = std::env::var("ONEPASSWORD_LIB_PATH").ok();

        // Set to a file that exists but has wrong name
        // SAFETY: This test is serialized to avoid race conditions
        unsafe {
            std::env::set_var("ONEPASSWORD_LIB_PATH", "/etc/passwd");
        }
        let result = find_library_path();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("must point to"));

        // Restore
        // SAFETY: This test is serialized to avoid race conditions
        unsafe {
            match original {
                Some(val) => std::env::set_var("ONEPASSWORD_LIB_PATH", val),
                None => std::env::remove_var("ONEPASSWORD_LIB_PATH"),
            }
        }
    }

    // ==========================================================================
    // Integration tests (require OP_SERVICE_ACCOUNT_TOKEN)
    // ==========================================================================

    fn get_test_token() -> Option<String> {
        std::env::var("OP_SERVICE_ACCOUNT_TOKEN").ok()
    }

    #[test]
    #[ignore = "requires OP_SERVICE_ACCOUNT_TOKEN"]
    fn test_init_client_with_valid_token() {
        let token = get_test_token().expect("OP_SERVICE_ACCOUNT_TOKEN required");
        let library = load_library().expect("should load library");

        // Build the init config JSON (same structure as protocol.rs)
        let config = serde_json::json!({
            "serviceAccountToken": token,
            "programmingLanguage": "Rust",
            "sdkVersion": "0030201",
            "integrationName": "test-loader",
            "integrationVersion": "0.1.0",
            "requestLibraryName": "reqwest",
            "requestLibraryVersion": "0.11",
            "os": std::env::consts::OS,
            "osVersion": "0.0.0",
            "architecture": std::env::consts::ARCH
        });

        let config_json = serde_json::to_string(&config).unwrap();
        let client_id = library
            .init_client(&config_json)
            .expect("should init client");

        // Client ID should be a valid numeric string
        assert!(!client_id.is_empty(), "client_id should not be empty");
        assert!(
            client_id.parse::<u64>().is_ok(),
            "client_id should be numeric: {client_id}"
        );

        // Clean up
        library.release_client(&client_id);
    }

    #[test]
    #[ignore = "requires OP_SERVICE_ACCOUNT_TOKEN"]
    fn test_init_client_with_invalid_token() {
        let library = load_library().expect("should load library");

        // Use an invalid token format
        let config = serde_json::json!({
            "serviceAccountToken": "invalid-token-12345",
            "programmingLanguage": "Rust",
            "sdkVersion": "0030201",
            "integrationName": "test-loader",
            "integrationVersion": "0.1.0",
            "requestLibraryName": "reqwest",
            "requestLibraryVersion": "0.11",
            "os": std::env::consts::OS,
            "osVersion": "0.0.0",
            "architecture": std::env::consts::ARCH
        });

        let config_json = serde_json::to_string(&config).unwrap();
        let result = library.init_client(&config_json);

        assert!(result.is_err(), "should fail with invalid token");
    }

    #[test]
    #[ignore = "requires OP_SERVICE_ACCOUNT_TOKEN and TEST_SECRET_REF"]
    fn test_invoke_sync_resolves_secret() {
        let token = get_test_token().expect("OP_SERVICE_ACCOUNT_TOKEN required");
        let secret_ref = std::env::var("TEST_SECRET_REF").expect("TEST_SECRET_REF required");
        let library = load_library().expect("should load library");

        // Initialize client
        let config = serde_json::json!({
            "serviceAccountToken": token,
            "programmingLanguage": "Rust",
            "sdkVersion": "0030201",
            "integrationName": "test-loader",
            "integrationVersion": "0.1.0",
            "requestLibraryName": "reqwest",
            "requestLibraryVersion": "0.11",
            "os": std::env::consts::OS,
            "osVersion": "0.0.0",
            "architecture": std::env::consts::ARCH
        });
        let config_json = serde_json::to_string(&config).unwrap();
        let client_id_str = library.init_client(&config_json).unwrap();
        let client_id: u64 = client_id_str.parse().unwrap();

        // Build invocation JSON
        let invocation = serde_json::json!({
            "invocation": {
                "clientId": client_id,
                "parameters": {
                    "name": "SecretsResolve",
                    "parameters": {
                        "secret_reference": secret_ref
                    }
                }
            }
        });
        let request_json = serde_json::to_string(&invocation).unwrap();

        // Invoke
        let response = library
            .invoke_sync(&request_json)
            .expect("should resolve secret");
        assert!(!response.is_empty(), "response should not be empty");

        // Clean up
        library.release_client(&client_id_str);
    }

    #[test]
    #[ignore = "requires OP_SERVICE_ACCOUNT_TOKEN"]
    fn test_release_client_succeeds() {
        let token = get_test_token().expect("OP_SERVICE_ACCOUNT_TOKEN required");
        let library = load_library().expect("should load library");

        // Initialize client
        let config = serde_json::json!({
            "serviceAccountToken": token,
            "programmingLanguage": "Rust",
            "sdkVersion": "0030201",
            "integrationName": "test-loader",
            "integrationVersion": "0.1.0",
            "requestLibraryName": "reqwest",
            "requestLibraryVersion": "0.11",
            "os": std::env::consts::OS,
            "osVersion": "0.0.0",
            "architecture": std::env::consts::ARCH
        });
        let config_json = serde_json::to_string(&config).unwrap();
        let client_id = library.init_client(&config_json).unwrap();

        // Release should not panic
        library.release_client(&client_id);

        // Releasing again should be safe (idempotent or no-op)
        library.release_client(&client_id);
    }
}