auths-core 0.1.3

Core cryptography and keychain integration for Auths
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! FFI bindings to expose core functionality to other languages (Swift, Kotlin, C, etc.).
//!
//! Provides functions for key management (import, rotate, export), cryptographic
//! operations, and agent-based signing.
//!
//! # Safety
//! Functions returning pointers (`*mut c_char`, `*mut u8`) allocate memory
//! using `libc::malloc`. The caller is responsible for freeing this memory
//! using the corresponding `ffi_free_*` function (`ffi_free_str`, `ffi_free_bytes`).
//! Input C string pointers (`*const c_char`) must be valid, null-terminated UTF-8 strings.
//! Input byte pointers (`*const u8`/`*const c_uchar`) must be valid for the specified length.
//! Output length pointers (`*mut usize`) must be valid pointers.
//! Operations involving raw pointers or calling C functions are wrapped in `unsafe` blocks.

use crate::agent::AgentHandle;
use crate::api::runtime::{
    agent_sign_with_handle, export_key_openssh_pem, export_key_openssh_pub, rotate_key,
};
use crate::config::{EnvironmentConfig, KeychainConfig};
use crate::config::{current_algorithm, set_encryption_algorithm};
use crate::crypto::EncryptionAlgorithm;
use crate::crypto::encryption::{decrypt_bytes, encrypt_bytes};
use crate::crypto::signer::extract_seed_from_key_bytes;
use crate::crypto::signer::{decrypt_keypair, encrypt_keypair};
use crate::error::AgentError;
use crate::storage::keychain::{
    IdentityDID, KeyAlias, KeyRole, KeyStorage, get_platform_keychain_with_config,
};
use log::{debug, error, info, warn};
use parking_lot::RwLock;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_uchar};
use std::panic;
use std::path::PathBuf;
use std::ptr;
use std::slice;
use std::sync::{Arc, LazyLock};

// --- FFI Error Codes ---

/// Successful operation
pub const FFI_OK: c_int = 0;
/// Invalid UTF-8 in C string input
pub const FFI_ERR_INVALID_UTF8: c_int = -1;
/// Agent not initialized (call ffi_init_agent first)
pub const FFI_ERR_AGENT_NOT_INITIALIZED: c_int = -2;
/// Null configuration context (call ffi_context_new first)
pub const FFI_ERR_NULL_CONTEXT: c_int = -3;
/// Keychain backend failed to initialize
pub const FFI_ERR_KEYCHAIN: c_int = 5;
/// Internal panic occurred
pub const FFI_ERR_PANIC: c_int = -127;

// --- FFI Agent Handle ---

/// Global FFI agent handle.
///
/// This static holds the `AgentHandle` used by FFI functions. It must be initialized
/// by calling `ffi_init_agent()` before using functions like `ffi_agent_sign()`.
static FFI_AGENT: LazyLock<RwLock<Option<Arc<AgentHandle>>>> = LazyLock::new(|| RwLock::new(None));

/// Initializes the FFI agent with the specified socket path.
///
/// Must be called before using `ffi_agent_sign()` or other agent-related FFI functions.
///
/// # Safety
/// - `socket_path` must be null or point to a valid C string.
///
/// # Returns
/// - 0 on success
/// - 1 if the socket path is invalid
/// - FFI_ERR_PANIC (-127) if a panic occurred
#[unsafe(no_mangle)]
#[allow(clippy::disallowed_methods)] // INVARIANT: FFI boundary — home-dir fallback for default socket path
pub unsafe extern "C" fn ffi_init_agent(socket_path: *const c_char) -> c_int {
    let result = panic::catch_unwind(|| {
        let path_str = match unsafe { c_str_to_str_safe(socket_path) } {
            Ok(s) if !s.is_empty() => s,
            Ok(_) => {
                // Empty path - use default
                let home = match dirs::home_dir() {
                    Some(h) => h,
                    None => {
                        error!("FFI ffi_init_agent: Could not determine home directory");
                        return 1;
                    }
                };
                let default_path = home.join(".auths").join("agent.sock");
                let handle = Arc::new(AgentHandle::new(default_path));
                let mut guard = FFI_AGENT.write();
                *guard = Some(handle);
                info!("FFI agent initialized with default socket path");
                return 0;
            }
            Err(code) => return code,
        };

        let socket = PathBuf::from(path_str);
        let handle = Arc::new(AgentHandle::new(socket));

        let mut guard = FFI_AGENT.write();
        *guard = Some(handle);
        info!("FFI agent initialized with socket path: {}", path_str);
        0
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_init_agent: panic occurred");
        FFI_ERR_PANIC
    })
}

/// Shuts down the FFI agent, clearing all keys from memory.
///
/// After calling this, `ffi_agent_sign()` will return an error until
/// `ffi_init_agent()` is called again.
///
/// # Safety
/// This function is safe to call at any time.
///
/// # Returns
/// - 0 on success
/// - FFI_ERR_PANIC (-127) if a panic occurred
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_shutdown_agent() -> c_int {
    let result = panic::catch_unwind(|| {
        let mut guard = FFI_AGENT.write();
        if let Some(handle) = guard.take() {
            if let Err(e) = handle.shutdown() {
                warn!("FFI ffi_shutdown_agent: Shutdown returned error: {}", e);
            }
            info!("FFI agent shut down");
        } else {
            debug!("FFI ffi_shutdown_agent: Agent was not initialized");
        }
        0
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_shutdown_agent: panic occurred");
        FFI_ERR_PANIC
    })
}

/// Gets a clone of the FFI agent handle.
///
/// Returns `None` if the agent has not been initialized.
fn get_ffi_agent() -> Option<Arc<AgentHandle>> {
    FFI_AGENT.read().clone()
}

// --- Helper Functions ---

/// Safely converts a C string pointer to a Rust `&str`.
/// Returns `Ok("")` if the pointer is null.
/// Returns `Err(FFI_ERR_INVALID_UTF8)` if the C string is not valid UTF-8.
///
/// # Safety
/// The caller must ensure `ptr` is either null or points to a valid,
/// null-terminated C string with a lifetime that encompasses this function call.
pub unsafe fn c_str_to_str_safe<'a>(ptr: *const c_char) -> Result<&'a str, c_int> {
    if ptr.is_null() {
        Ok("")
    } else {
        // Safety: Assumes ptr is valid C string per function contract.
        unsafe {
            CStr::from_ptr(ptr)
                .to_str()
                .map_err(|_| FFI_ERR_INVALID_UTF8)
        }
    }
}

/// Converts a Rust `Result<T, E: Display>` to a C-style integer error code.
/// Logs the error on failure. Returns 0 on Ok, 1 on Err (general error).
/// Consider more specific error codes in the future.
///
/// # Safety
/// This function is marked unsafe for FFI compatibility but does not perform
/// any unsafe operations itself.
pub unsafe fn result_to_c_int<T, E: std::fmt::Display>(
    result: Result<T, E>,
    fn_name: &str,
) -> c_int {
    match result {
        Ok(_) => 0,
        Err(e) => {
            error!("FFI call {} failed: {}", fn_name, e);
            1 // General error code
        }
    }
}

/// Helper to allocate memory via malloc, copy Rust slice data into it,
/// set the out_len pointer, and return the raw pointer.
/// Returns null pointer on allocation failure.
///
/// # Safety
/// - `out_len` must be a valid pointer to `usize`.
/// - The caller must ensure the returned pointer (if not null) is eventually freed
///   using `ffi_free_bytes`.
/// - Operations involve raw pointers and calling `libc::malloc`, requiring `unsafe` block.
pub unsafe fn malloc_and_copy_bytes(data: &[u8], out_len: *mut usize) -> *mut u8 {
    // Safety: Operations require unsafe block.
    unsafe {
        if out_len.is_null() {
            error!("malloc_and_copy_bytes failed: out_len pointer is null.");
            return ptr::null_mut();
        }
        // Dereferencing out_len is unsafe
        *out_len = data.len();
        // Calling C function is unsafe
        let ptr = libc::malloc(data.len()) as *mut u8;
        if ptr.is_null() {
            error!(
                "malloc_and_copy_bytes failed: malloc returned null for size {}",
                data.len()
            );
            *out_len = 0; // Reset len on failure
            return ptr::null_mut();
        }
        // Pointer copy is unsafe
        ptr::copy_nonoverlapping(data.as_ptr(), ptr, data.len());
        ptr
    }
}

/// Helper to convert a Rust String (or Zeroizing<String>) into a C string,
/// allocating memory via `CString::into_raw`.
/// Returns null pointer on allocation failure or if the string contains null bytes.
///
/// # Safety
/// - The caller must ensure the returned pointer (if not null) is eventually freed
///   using `ffi_free_str`.
/// - Calls `CString::into_raw` which transfers ownership.
fn malloc_and_copy_string(s: &str) -> *mut c_char {
    match CString::new(s) {
        Ok(c_string) => c_string.into_raw(), // Transfers ownership, C caller must free
        Err(e) => {
            error!(
                "malloc_and_copy_string failed: CString creation error: {}",
                e
            );
            ptr::null_mut()
        }
    }
}

// --- FFI Configuration Context ---

/// Maximum accepted byte length for the `config_json` argument of [`ffi_context_new`].
pub const FFI_CONTEXT_CONFIG_MAX_BYTES: usize = 64 * 1024;

/// Opaque configuration context for keychain-backed FFI functions.
///
/// Carries the [`EnvironmentConfig`] that selects the keychain backend, the
/// encrypted-file path/passphrase, and the Auths home directory. Created with
/// [`ffi_context_new`] and released with [`ffi_context_free`]; passed as the
/// first argument to every keychain-backed FFI function.
pub struct AuthsFfiContext {
    env: EnvironmentConfig,
}

/// JSON wire form accepted by [`ffi_context_new`]. All fields are optional;
/// absent fields fall back to platform defaults (not environment variables).
#[derive(Debug, Default, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct FfiContextConfig {
    auths_home: Option<PathBuf>,
    keychain_backend: Option<String>,
    keychain_file: Option<PathBuf>,
    keychain_passphrase: Option<String>,
    ssh_agent_socket: Option<PathBuf>,
}

impl FfiContextConfig {
    fn into_environment(self) -> EnvironmentConfig {
        let mut builder = EnvironmentConfig::builder().keychain(KeychainConfig {
            backend: self.keychain_backend,
            file_path: self.keychain_file,
            passphrase: self.keychain_passphrase,
        });
        if let Some(home) = self.auths_home {
            builder = builder.auths_home(home);
        }
        if let Some(socket) = self.ssh_agent_socket {
            builder = builder.ssh_agent_socket(socket);
        }
        builder.build()
    }
}

/// Creates an FFI configuration context.
///
/// Args:
/// * `config_json`: Null or empty to capture the process environment
///   (`AUTHS_HOME`, `AUTHS_KEYCHAIN_BACKEND`, `AUTHS_KEYCHAIN_FILE`,
///   `AUTHS_PASSPHRASE`, `SSH_AUTH_SOCK`), or a JSON object with optional
///   fields `auths_home`, `keychain_backend` (`"file"` / `"memory"`),
///   `keychain_file`, `keychain_passphrase`, `ssh_agent_socket`.
///
/// Usage:
/// ```ignore
/// let ctx = unsafe { ffi_context_new(std::ptr::null()) };
/// // ... pass ctx to keychain-backed FFI functions ...
/// unsafe { ffi_context_free(ctx) };
/// ```
///
/// # Safety
/// - `config_json` must be null or point to a valid, null-terminated C string.
/// - The returned pointer must be released with `ffi_context_free` and must not
///   be used after being freed.
///
/// # Returns
/// - Non-null context pointer on success
/// - NULL if `config_json` is invalid UTF-8, exceeds
///   `FFI_CONTEXT_CONFIG_MAX_BYTES`, is not valid JSON, or a panic occurred
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_context_new(config_json: *const c_char) -> *mut AuthsFfiContext {
    let result = panic::catch_unwind(|| {
        let json = match unsafe { c_str_to_str_safe(config_json) } {
            Ok(s) => s,
            Err(_) => {
                error!("FFI ffi_context_new: config_json is not valid UTF-8");
                return ptr::null_mut();
            }
        };
        if json.len() > FFI_CONTEXT_CONFIG_MAX_BYTES {
            error!(
                "FFI ffi_context_new: config_json length {} exceeds maximum {}",
                json.len(),
                FFI_CONTEXT_CONFIG_MAX_BYTES
            );
            return ptr::null_mut();
        }
        let env = if json.is_empty() {
            EnvironmentConfig::from_env()
        } else {
            match serde_json::from_str::<FfiContextConfig>(json) {
                Ok(config) => config.into_environment(),
                Err(e) => {
                    error!("FFI ffi_context_new: invalid config JSON: {}", e);
                    return ptr::null_mut();
                }
            }
        };
        Box::into_raw(Box::new(AuthsFfiContext { env }))
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_context_new: panic occurred");
        ptr::null_mut()
    })
}

/// Frees a context previously returned by `ffi_context_new`.
/// Does nothing if `ctx` is null.
///
/// # Safety
/// - `ctx` must be null or must have been returned by `ffi_context_new`.
/// - `ctx` must not be used after calling this function.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_context_free(ctx: *mut AuthsFfiContext) {
    let _ = panic::catch_unwind(|| {
        if !ctx.is_null() {
            // Safety: ctx was allocated by Box::into_raw in ffi_context_new.
            drop(unsafe { Box::from_raw(ctx) });
        }
    });
    // Note: If panic occurs during free, we just swallow it to avoid UB from unwinding across FFI
}

/// Opens the keychain selected by an FFI context.
///
/// # Safety
/// `ctx` must be null or a pointer returned by `ffi_context_new` that has not
/// been freed.
unsafe fn keychain_from_context(
    ctx: *const AuthsFfiContext,
    fn_name: &str,
) -> Result<Box<dyn KeyStorage + Send + Sync>, c_int> {
    if ctx.is_null() {
        error!("FFI {}: null context — call ffi_context_new first", fn_name);
        return Err(FFI_ERR_NULL_CONTEXT);
    }
    // Safety: non-null ctx points to a live AuthsFfiContext per function contract.
    let env = unsafe { &(*ctx).env };
    get_platform_keychain_with_config(env).map_err(|e| {
        error!("FFI {}: Failed to get platform keychain: {}", fn_name, e);
        FFI_ERR_KEYCHAIN
    })
}

// --- FFI Functions ---

/// Checks if a key with the given alias exists in the secure storage.
///
/// # Safety
/// - `ctx` must be null or a pointer returned by `ffi_context_new` that has not been freed.
/// - `alias` must be null or point to a valid C string.
///
/// # Returns
/// - `true` if the key exists
/// - `false` if key doesn't exist, `ctx` is null, invalid input, or internal error
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_key_exists(ctx: *const AuthsFfiContext, alias: *const c_char) -> bool {
    let result = panic::catch_unwind(|| {
        let alias_str = match unsafe { c_str_to_str_safe(alias) } {
            Ok(s) => s,
            Err(_) => return false,
        };
        if alias_str.is_empty() {
            return false;
        }
        let keychain = match unsafe { keychain_from_context(ctx, "ffi_key_exists") } {
            Ok(kc) => kc,
            Err(_) => return false,
        };
        let alias = KeyAlias::new_unchecked(alias_str);
        keychain.load_key(&alias).is_ok()
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_key_exists: panic occurred");
        false
    })
}

/// Imports a private key (provided as raw PKCS#8 bytes), encrypts it with the
/// given passphrase, and stores it in the secure storage under the specified
/// local alias, associated with the given controller DID.
///
/// # Safety
/// - `ctx` must be null or a pointer returned by `ffi_context_new` that has not been freed.
/// - `alias`, `controller_did`, `passphrase` must be valid C strings.
/// - `key_ptr` must point to valid PKCS#8 key data of `key_len` bytes for the duration of the call.
/// - `key_len` must be the correct length for the data pointed to by `key_ptr`.
///
/// # Returns
/// - 0 on success
/// - 1 if arguments are invalid
/// - 2 if key data is not valid PKCS#8
/// - 4 if encryption fails
/// - FFI_ERR_KEYCHAIN (5) if keychain initialization fails
/// - FFI_ERR_INVALID_UTF8 (-1) if C strings contain invalid UTF-8
/// - FFI_ERR_NULL_CONTEXT (-3) if `ctx` is null
/// - FFI_ERR_PANIC (-127) if a panic occurred
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_import_key(
    ctx: *const AuthsFfiContext,
    alias: *const c_char,    // Local keychain alias
    key_ptr: *const c_uchar, // Pointer to PKCS#8 bytes
    key_len: usize,
    controller_did: *const c_char, // Controller DID to associate
    passphrase: *const c_char,     // Passphrase to encrypt WITH
) -> c_int {
    let result = panic::catch_unwind(|| {
        // Safety: Calls unsafe helper and slice::from_raw_parts.
        let alias_str = match unsafe { c_str_to_str_safe(alias) } {
            Ok(s) => s,
            Err(code) => return code,
        };
        let did_str = match unsafe { c_str_to_str_safe(controller_did) } {
            Ok(s) => s,
            Err(code) => return code,
        };
        let pass_str = match unsafe { c_str_to_str_safe(passphrase) } {
            Ok(s) => s,
            Err(code) => return code,
        };
        let key_data = unsafe { slice::from_raw_parts(key_ptr, key_len) };

        // Argument validation
        if alias_str.is_empty()
            || did_str.is_empty()
            || !did_str.starts_with("did:")
            || pass_str.is_empty()
        {
            error!(
                "FFI import failed: Invalid arguments (alias='{}', did='{}', passphrase empty={}).",
                alias_str,
                did_str,
                pass_str.is_empty()
            );
            return 1;
        }

        // Key data validation via seed extraction
        if let Err(e) = extract_seed_from_key_bytes(key_data) {
            error!(
                "FFI import failed: Provided key data is not valid Ed25519 for alias '{}': {}",
                alias_str, e
            );
            return 2;
        }

        // Encrypt
        let encrypt_result = encrypt_keypair(key_data, pass_str);
        let encrypted_key = match encrypt_result {
            Ok(enc) => enc,
            Err(e) => {
                error!(
                    "FFI import failed: Encryption error for alias '{}': {}",
                    alias_str, e
                );
                return 4; // Encryption error
            }
        };

        #[allow(clippy::disallowed_methods)]
        // INVARIANT: validated with starts_with("did:") guard above
        let did_string = IdentityDID::new_unchecked(did_str.to_string());
        let alias = KeyAlias::new_unchecked(alias_str);

        // Store
        let keychain = match unsafe { keychain_from_context(ctx, "ffi_import_key") } {
            Ok(kc) => kc,
            Err(code) => return code,
        };
        let store_result =
            keychain.store_key(&alias, &did_string, KeyRole::Primary, &encrypted_key);

        unsafe { result_to_c_int(store_result, "ffi_import_key") }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_import_key: panic occurred");
        FFI_ERR_PANIC
    })
}

/// Rotates the keypair for a given local alias.
/// Generates a new key, encrypts it with the *new* passphrase, and replaces the
/// existing key in secure storage, keeping the association with the original Controller DID.
///
/// # Safety
/// - `ctx` must be null or a pointer returned by `ffi_context_new` that has not been freed.
/// - `alias`, `new_passphrase` must be valid C strings.
///
/// # Returns
/// - 0 on success.
/// - 1 if arguments are invalid.
/// - 2 if the original key/alias is not found.
/// - 3 if crypto operations fail.
/// - 4 if secure storage or other errors occur.
/// - FFI_ERR_KEYCHAIN (5) if keychain initialization fails
/// - FFI_ERR_INVALID_UTF8 (-1) if C strings contain invalid UTF-8
/// - FFI_ERR_NULL_CONTEXT (-3) if `ctx` is null
/// - FFI_ERR_PANIC (-127) if a panic occurred
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_rotate_key(
    ctx: *const AuthsFfiContext,
    alias: *const c_char,
    new_passphrase: *const c_char,
) -> c_int {
    let result = panic::catch_unwind(|| {
        let alias_str = match unsafe { c_str_to_str_safe(alias) } {
            Ok(s) => s,
            Err(code) => return code,
        };
        let pass_str = match unsafe { c_str_to_str_safe(new_passphrase) } {
            Ok(s) => s,
            Err(code) => return code,
        };

        // Delegate to the runtime API function
        let keychain = match unsafe { keychain_from_context(ctx, "ffi_rotate_key") } {
            Ok(kc) => kc,
            Err(code) => return code,
        };
        let rotate_result = rotate_key(alias_str, pass_str, keychain.as_ref());

        // Map AgentError to FFI return codes
        match rotate_result {
            Ok(()) => 0,
            Err(e) => {
                error!("FFI rotate_key failed for alias '{}': {}", alias_str, e);
                match e {
                    AgentError::InvalidInput(_) => 1,
                    AgentError::KeyNotFound => 2,
                    AgentError::CryptoError(_) | AgentError::KeyDeserializationError(_) => 3,
                    _ => 4, // Storage, Mutex, etc.
                }
            }
        }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_rotate_key: panic occurred");
        FFI_ERR_PANIC
    })
}

/// Exports the raw *encrypted* private key bytes associated with the alias.
/// This function does *not* require a passphrase.
///
/// # Safety
/// - `ctx` must be null or a pointer returned by `ffi_context_new` that has not been freed.
/// - `alias` must be a valid C string.
/// - `out_len` must be a valid pointer to `usize`.
/// - The returned pointer (if not null) must be freed by the caller using `ffi_free_bytes`.
///
/// # Returns
/// - Non-null pointer to encrypted key bytes on success
/// - NULL on error (null context, invalid input, key not found, or panic)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_export_encrypted_key(
    ctx: *const AuthsFfiContext,
    alias: *const c_char,
    out_len: *mut usize,
) -> *mut u8 {
    let result = panic::catch_unwind(|| {
        let alias_str = match unsafe { c_str_to_str_safe(alias) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };
        if alias_str.is_empty() || out_len.is_null() {
            if !out_len.is_null() {
                unsafe { *out_len = 0 };
            }
            return ptr::null_mut();
        }
        unsafe { *out_len = 0 };

        let keychain = match unsafe { keychain_from_context(ctx, "ffi_export_encrypted_key") } {
            Ok(kc) => kc,
            Err(_) => return ptr::null_mut(),
        };
        let alias = KeyAlias::new_unchecked(alias_str);
        match keychain.load_key(&alias) {
            Ok((_identity_did, _role, encrypted_data)) => {
                debug!(
                    "FFI export encrypted key successful for alias '{}'",
                    alias_str
                );
                unsafe { malloc_and_copy_bytes(&encrypted_data, out_len) }
            }
            Err(e) => {
                error!(
                    "FFI export encrypted key failed for alias '{}': {}",
                    alias_str, e
                );
                ptr::null_mut()
            }
        }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_export_encrypted_key: panic occurred");
        ptr::null_mut()
    })
}

/// Verifies a passphrase against the stored encrypted key for the given alias.
/// If the passphrase is correct, returns a copy of the *encrypted* key data.
///
/// # Safety
/// - `ctx` must be null or a pointer returned by `ffi_context_new` that has not been freed.
/// - `alias`, `passphrase` must be valid C strings.
/// - `out_len` must be a valid pointer to `usize`.
/// - The returned pointer (if not null) must be freed by the caller using `ffi_free_bytes`.
///
/// # Returns
/// - Non-null pointer to encrypted key bytes on success
/// - NULL on error (null context, invalid input, incorrect passphrase, or panic)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_export_private_key_with_passphrase(
    ctx: *const AuthsFfiContext,
    alias: *const c_char,
    passphrase: *const c_char,
    out_len: *mut usize,
) -> *mut u8 {
    let result = panic::catch_unwind(|| {
        let alias_str = match unsafe { c_str_to_str_safe(alias) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };
        let pass_str = match unsafe { c_str_to_str_safe(passphrase) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };

        if alias_str.is_empty() || out_len.is_null() {
            if !out_len.is_null() {
                unsafe { *out_len = 0 };
            }
            return ptr::null_mut();
        }
        unsafe { *out_len = 0 };

        let keychain =
            match unsafe { keychain_from_context(ctx, "ffi_export_private_key_with_passphrase") } {
                Ok(kc) => kc,
                Err(_) => return ptr::null_mut(),
            };
        let alias = KeyAlias::new_unchecked(alias_str);
        let export_result = || -> Result<Vec<u8>, AgentError> {
            if keychain.is_hardware_backend() {
                return Err(AgentError::BackendUnavailable {
                    backend: keychain.backend_name(),
                    reason: "hardware-backed keys (e.g. Secure Enclave) cannot be exported via this FFI path".to_string(),
                });
            }
            let (_controller_did, _role, encrypted_bytes) = keychain.load_key(&alias)?;
            // Attempt decryption only to verify passphrase
            let _decrypted_pkcs8 = decrypt_keypair(&encrypted_bytes, pass_str)?;
            debug!(
                "FFI export_private_key_with_passphrase: Passphrase verified for alias '{}'",
                alias_str
            );
            Ok(encrypted_bytes)
        }();

        match export_result {
            Ok(encrypted_data) => unsafe { malloc_and_copy_bytes(&encrypted_data, out_len) },
            Err(e) => {
                if !matches!(e, AgentError::IncorrectPassphrase) {
                    error!(
                        "FFI export_private_key_with_passphrase failed for alias '{}': {}",
                        alias_str, e
                    );
                } else {
                    debug!(
                        "FFI export_private_key_with_passphrase: Incorrect passphrase for alias '{}'",
                        alias_str
                    );
                }
                ptr::null_mut()
            }
        }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_export_private_key_with_passphrase: panic occurred");
        ptr::null_mut()
    })
}

/// Exports the decrypted private key in OpenSSH PEM format.
/// Requires the correct passphrase to decrypt the key.
///
/// # Safety
/// - `ctx` must be null or a pointer returned by `ffi_context_new` that has not been freed.
/// - `alias`, `passphrase` must be valid C strings.
/// - The returned pointer (if not null) must be freed by the caller using `ffi_free_str`.
///
/// # Returns
/// - Non-null pointer to PEM string on success
/// - NULL on error (null context, invalid input, incorrect passphrase, or panic)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_export_private_key_openssh(
    ctx: *const AuthsFfiContext,
    alias: *const c_char,
    passphrase: *const c_char,
) -> *mut c_char {
    let result = panic::catch_unwind(|| {
        let alias_str = match unsafe { c_str_to_str_safe(alias) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };
        let pass_str = match unsafe { c_str_to_str_safe(passphrase) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };

        if alias_str.is_empty() {
            return ptr::null_mut();
        }

        let keychain = match unsafe { keychain_from_context(ctx, "ffi_export_private_key_openssh") }
        {
            Ok(kc) => kc,
            Err(_) => return ptr::null_mut(),
        };
        match export_key_openssh_pem(alias_str, pass_str, keychain.as_ref()) {
            Ok(pem_zeroizing) => malloc_and_copy_string(pem_zeroizing.as_str()),
            Err(e) => {
                error!("FFI export PEM failed for alias '{}': {}", alias_str, e);
                ptr::null_mut()
            }
        }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_export_private_key_openssh: panic occurred");
        ptr::null_mut()
    })
}

/// Exports the public key in OpenSSH `.pub` format.
/// Requires the correct passphrase to decrypt the associated private key first.
///
/// # Safety
/// - `ctx` must be null or a pointer returned by `ffi_context_new` that has not been freed.
/// - `alias`, `passphrase` must be valid C strings.
/// - The returned pointer (if not null) must be freed by the caller using `ffi_free_str`.
///
/// # Returns
/// - Non-null pointer to public key string on success
/// - NULL on error (null context, invalid input, incorrect passphrase, or panic)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_export_public_key_openssh(
    ctx: *const AuthsFfiContext,
    alias: *const c_char,
    passphrase: *const c_char,
) -> *mut c_char {
    let result = panic::catch_unwind(|| {
        let alias_str = match unsafe { c_str_to_str_safe(alias) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };
        let pass_str = match unsafe { c_str_to_str_safe(passphrase) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };

        if alias_str.is_empty() {
            return ptr::null_mut();
        }

        let keychain = match unsafe { keychain_from_context(ctx, "ffi_export_public_key_openssh") }
        {
            Ok(kc) => kc,
            Err(_) => return ptr::null_mut(),
        };
        match export_key_openssh_pub(alias_str, pass_str, keychain.as_ref()) {
            Ok(formatted_pubkey) => malloc_and_copy_string(&formatted_pubkey),
            Err(e) => {
                error!(
                    "FFI export OpenSSH pubkey failed for alias '{}': {}",
                    alias_str, e
                );
                ptr::null_mut()
            }
        }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_export_public_key_openssh: panic occurred");
        ptr::null_mut()
    })
}

/// Signs a message using a key loaded into the FFI agent.
///
/// **Important:** `ffi_init_agent()` must be called before using this function.
///
/// # Safety
/// - `pubkey_ptr` must point to valid public key bytes of `pubkey_len` bytes.
/// - `data_ptr` must point to valid data bytes of `data_len` bytes.
/// - `out_len` must be a valid pointer to `usize`.
/// - The returned pointer (if not null) must be freed by the caller using `ffi_free_bytes`.
///
/// # Returns
/// - Non-null pointer to signature bytes on success
/// - NULL on error (agent not initialized, invalid input, key not found, or panic)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_agent_sign(
    pubkey_ptr: *const c_uchar,
    pubkey_len: usize,
    data_ptr: *const c_uchar,
    data_len: usize,
    out_len: *mut usize,
) -> *mut u8 {
    let result = panic::catch_unwind(|| {
        if pubkey_ptr.is_null() || data_ptr.is_null() || out_len.is_null() {
            if !out_len.is_null() {
                unsafe { *out_len = 0 };
            }
            error!("FFI agent_sign failed: Null pointer argument.");
            return ptr::null_mut();
        }

        // Get the FFI agent handle
        let handle = match get_ffi_agent() {
            Some(h) => h,
            None => {
                error!(
                    "FFI agent_sign failed: Agent not initialized. Call ffi_init_agent() first."
                );
                unsafe { *out_len = 0 };
                return ptr::null_mut();
            }
        };

        let pubkey_slice = unsafe { slice::from_raw_parts(pubkey_ptr, pubkey_len) };
        let data_slice = unsafe { slice::from_raw_parts(data_ptr, data_len) };
        unsafe { *out_len = 0 };

        match agent_sign_with_handle(&handle, pubkey_slice, data_slice) {
            Ok(signature_bytes) => unsafe { malloc_and_copy_bytes(&signature_bytes, out_len) },
            Err(e) => {
                error!("FFI agent_sign failed: {}", e);
                if matches!(e, AgentError::KeyNotFound) {
                    warn!(
                        "FFI agent_sign: Key not found in agent for pubkey prefix {:x?}",
                        &pubkey_slice[..std::cmp::min(pubkey_slice.len(), 8)]
                    );
                }
                ptr::null_mut()
            }
        }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_agent_sign: panic occurred");
        ptr::null_mut()
    })
}

// --- General Crypto & Config FFI Functions ---

/// Encrypts data using the given passphrase.
///
/// # Safety
/// - `passphrase` must be a valid null-terminated C string
/// - `input_ptr` must point to valid memory of at least `input_len` bytes
/// - `out_len` must be a valid pointer to write the output length
///
/// # Returns
/// - Non-null pointer to encrypted bytes on success
/// - NULL on error (invalid input or panic)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_encrypt_data(
    passphrase: *const c_char,
    input_ptr: *const u8,
    input_len: usize,
    out_len: *mut usize,
) -> *mut u8 {
    let result = panic::catch_unwind(|| {
        if input_ptr.is_null() || out_len.is_null() {
            if !out_len.is_null() {
                unsafe { *out_len = 0 };
            }
            error!("FFI encrypt_data failed: Null pointer argument.");
            return ptr::null_mut();
        }
        let pass = match unsafe { c_str_to_str_safe(passphrase) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };
        let input = unsafe { slice::from_raw_parts(input_ptr, input_len) };
        unsafe { *out_len = 0 };
        let algo = current_algorithm();

        match encrypt_bytes(input, pass, algo) {
            Ok(encrypted) => unsafe { malloc_and_copy_bytes(&encrypted, out_len) },
            Err(e) => {
                error!("FFI encrypt_data failed: {}", e);
                ptr::null_mut()
            }
        }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_encrypt_data: panic occurred");
        ptr::null_mut()
    })
}

/// Decrypts data using the given passphrase.
///
/// # Safety
/// - `passphrase` must be a valid null-terminated C string
/// - `input_ptr` must point to valid memory of at least `input_len` bytes
/// - `out_len` must be a valid pointer to write the output length
///
/// # Returns
/// - Non-null pointer to decrypted bytes on success
/// - NULL on error (invalid input, incorrect passphrase, or panic)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_decrypt_data(
    passphrase: *const c_char,
    input_ptr: *const u8,
    input_len: usize,
    out_len: *mut usize,
) -> *mut u8 {
    let result = panic::catch_unwind(|| {
        if input_ptr.is_null() || out_len.is_null() {
            if !out_len.is_null() {
                unsafe { *out_len = 0 };
            }
            error!("FFI decrypt_data failed: Null pointer argument.");
            return ptr::null_mut();
        }
        let pass = match unsafe { c_str_to_str_safe(passphrase) } {
            Ok(s) => s,
            Err(_) => return ptr::null_mut(),
        };
        let input = unsafe { slice::from_raw_parts(input_ptr, input_len) };
        unsafe { *out_len = 0 };

        match decrypt_bytes(input, pass) {
            Ok(decrypted) => unsafe { malloc_and_copy_bytes(&decrypted, out_len) },
            Err(e) => {
                if !matches!(e, AgentError::IncorrectPassphrase) {
                    error!("FFI decrypt_data failed: {}", e);
                } else {
                    debug!("FFI decrypt_data: Incorrect passphrase provided.");
                }
                ptr::null_mut()
            }
        }
    });
    result.unwrap_or_else(|_| {
        error!("FFI ffi_decrypt_data: panic occurred");
        ptr::null_mut()
    })
}

/// Frees a C string (`char *`) previously returned by an FFI function
/// in this library (which allocated it using `CString::into_raw`).
/// Does nothing if `ptr` is null.
///
/// # Safety
/// - `ptr` must be null or must have been previously allocated by a function
///   in this library that returns `*mut c_char` (eg, `ffi_export_..._openssh`).
/// - `ptr` must not be used after calling this function.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_free_str(ptr: *mut c_char) {
    let _ = panic::catch_unwind(|| {
        if !ptr.is_null() {
            // Safety: We are reclaiming ownership of the pointer originally transferred
            // via CString::into_raw and letting the CString drop, which frees the memory.
            let _ = unsafe { CString::from_raw(ptr) };
        }
    });
    // Note: If panic occurs during free, we just swallow it to avoid UB from unwinding across FFI
}

/// Frees a byte buffer (`unsigned char *` / `uint8_t *`) previously returned
/// by an FFI function in this library (which allocated it using `libc::malloc`).
/// Does nothing if `ptr` is null. The `len` argument is ignored but kept for
/// potential C-side compatibility if callers expect it.
///
/// # Safety
/// - `ptr` must be null or must have been previously allocated by a function
///   in this library that returns `*mut u8` (eg, `ffi_agent_sign`, `ffi_export_encrypted_key`).
/// - `ptr` must not be used after calling this function.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_free_bytes(ptr: *mut u8, _len: usize) {
    let _ = panic::catch_unwind(|| {
        if !ptr.is_null() {
            unsafe { libc::free(ptr as *mut libc::c_void) };
        }
    });
    // Note: If panic occurs during free, we just swallow it to avoid UB from unwinding across FFI
}

/// Sets the global encryption algorithm level used by `encrypt_keypair`.
/// (1 = AES-GCM-256, 2 = ChaCha20Poly1305). Defaults to AES if level is unknown.
///
/// # Safety
/// This function modifies global state. It should not be called concurrently
/// from multiple threads.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ffi_set_encryption_algorithm(level: c_int) {
    let _ = panic::catch_unwind(|| {
        let algo = match level {
            1 => EncryptionAlgorithm::AesGcm256,
            2 => EncryptionAlgorithm::ChaCha20Poly1305,
            _ => {
                warn!(
                    "FFI: Unknown encryption level {}, defaulting to AES-GCM.",
                    level
                );
                EncryptionAlgorithm::AesGcm256
            }
        };
        info!("FFI: Setting global encryption algorithm to {:?}", algo);
        set_encryption_algorithm(algo);
    });
    // Note: If panic occurs, we just swallow it to avoid UB from unwinding across FFI
}

// --- Deprecated / Removed Functions ---

// `ffi_init_identity` removed - requires more complex setup (metadata file) now.
// `ffi_start_agent` removed - agent startup is separate from key loading now.
// `ffi_get_public_key` removed - use `ffi_export_public_key_openssh`.
// `ffi_sign_ssh_agent_request` removed - use `ffi_agent_sign`.
// `ffi_sign_ssh_agent_request_with_passphrase` removed - use `ffi_agent_sign`.
// Internal `sign_ssh_agent_request` removed.