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
//! Keychain abstraction.

use crate::config::EnvironmentConfig;
use crate::error::AgentError;
use crate::paths::auths_home_with_config;
use log::{info, warn};
use std::sync::Arc;

#[cfg(target_os = "ios")]
use super::ios_keychain::IOSKeychain;

#[cfg(target_os = "macos")]
use super::macos_keychain::MacOSKeychain;

#[cfg(all(target_os = "linux", feature = "keychain-linux-secretservice"))]
use super::linux_secret_service::LinuxSecretServiceStorage;

#[cfg(all(target_os = "windows", feature = "keychain-windows"))]
use super::windows_credential::WindowsCredentialStorage;

#[cfg(target_os = "android")]
use super::android_keystore::AndroidKeystoreStorage;

use super::encrypted_file::EncryptedFileStorage;
use super::memory::MemoryKeychainHandle;
use std::borrow::Borrow;
use std::fmt;
use std::ops::Deref;
use zeroize::Zeroizing;

/// Service name used for all platform keychains.
/// Used inside cfg-gated blocks (macOS, iOS, Linux, Windows, Android).
#[cfg_attr(
    not(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "android",
        all(target_os = "linux", feature = "keychain-linux-secretservice"),
        all(target_os = "windows", feature = "keychain-windows"),
        test,
    )),
    allow(dead_code)
)]
const SERVICE_NAME: &str = "dev.auths.agent";

// Re-exported from auths-verifier (the leaf dependency shared by all crates).
pub use auths_verifier::IdentityDID;

/// The role a stored key serves within its identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum KeyRole {
    /// The identity's current active signing key.
    Primary,
    /// A pre-committed rotation key (not yet active).
    NextRotation,
    /// A key delegated to an autonomous agent.
    DelegatedAgent,
}

impl std::fmt::Display for KeyRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            KeyRole::Primary => write!(f, "primary"),
            KeyRole::NextRotation => write!(f, "next_rotation"),
            KeyRole::DelegatedAgent => write!(f, "delegated_agent"),
        }
    }
}

impl std::str::FromStr for KeyRole {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "primary" => Ok(KeyRole::Primary),
            "next_rotation" => Ok(KeyRole::NextRotation),
            "delegated_agent" => Ok(KeyRole::DelegatedAgent),
            other => Err(format!("unknown key role: {other}")),
        }
    }
}

/// Validated alias for a stored key.
///
/// Invariants: non-empty and contains no null bytes.
///
/// Usage:
/// ```ignore
/// let alias = KeyAlias::new("my-signing-key")?;
/// keychain.store_key(&alias, &did, &encrypted)?;
/// ```
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(transparent)]
#[repr(transparent)]
pub struct KeyAlias(String);

impl KeyAlias {
    /// Creates a validated `KeyAlias`.
    ///
    /// Rejects empty strings and strings containing null bytes.
    pub fn new<S: Into<String>>(s: S) -> Result<Self, AgentError> {
        let s = s.into();
        if s.is_empty() {
            return Err(AgentError::InvalidInput(
                "key alias must not be empty".into(),
            ));
        }
        if s.contains('\0') {
            return Err(AgentError::InvalidInput(
                "key alias must not contain null bytes".into(),
            ));
        }
        Ok(Self(s))
    }

    /// Wraps a string without validation (for trusted internal paths).
    pub fn new_unchecked<S: Into<String>>(s: S) -> Self {
        Self(s.into())
    }

    /// Returns the alias as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes self and returns the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl fmt::Display for KeyAlias {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Deref for KeyAlias {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<str> for KeyAlias {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for KeyAlias {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl From<KeyAlias> for String {
    fn from(alias: KeyAlias) -> String {
        alias.0
    }
}

impl PartialEq<str> for KeyAlias {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for KeyAlias {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

impl PartialEq<String> for KeyAlias {
    fn eq(&self, other: &String) -> bool {
        self.0 == *other
    }
}

/// Migrate a legacy single-key alias `{alias}` to the multi-key form
/// `{alias}--0`.
///
/// Idempotent: safe to call whether or not the migration has already
/// happened. Reads the legacy slot, writes to the new slot, deletes the
/// legacy slot. Returns the new alias form.
///
/// Behavior matrix:
/// - Both legacy and `--0` present: no-op, returns `{alias}--0` (assumes
///   `--0` is authoritative since it's the new convention).
/// - Only legacy present: copies to `--0`, deletes legacy, returns `--0`.
/// - Only `--0` present: no-op, returns `--0`.
/// - Neither present: returns `--0` anyway; the caller's next `load_key`
///   will surface the absence.
pub fn migrate_legacy_alias(
    keychain: &(dyn KeyStorage + Send + Sync),
    old_alias: &KeyAlias,
) -> Result<KeyAlias, AgentError> {
    let new_alias = KeyAlias::new_unchecked(format!("{}--0", old_alias));

    if keychain.load_key(&new_alias).is_ok() {
        // Already migrated (or a fresh multi-key identity was created without
        // ever touching the legacy alias). In either case, new form wins.
        return Ok(new_alias);
    }

    let (did, role, data) = match keychain.load_key(old_alias) {
        Ok(v) => v,
        Err(_) => {
            // Legacy absent too; nothing to migrate. Caller hits absence on
            // their next load_key call.
            return Ok(new_alias);
        }
    };

    keychain.store_key(&new_alias, &did, role, &data)?;
    // Best-effort legacy cleanup; failure here isn't fatal.
    let _ = keychain.delete_key(old_alias);
    Ok(new_alias)
}

/// Platform-agnostic interface for storing and loading private keys securely.
///
/// All implementors must be Send + Sync for thread-safe access.
pub trait KeyStorage: Send + Sync {
    /// Stores encrypted key data associated with an alias AND an identity DID.
    fn store_key(
        &self,
        alias: &KeyAlias,
        identity_did: &IdentityDID,
        role: KeyRole,
        encrypted_key_data: &[u8],
    ) -> Result<(), AgentError>;

    /// Loads the encrypted key data AND the associated identity DID for a given alias.
    fn load_key(&self, alias: &KeyAlias) -> Result<(IdentityDID, KeyRole, Vec<u8>), AgentError>;

    /// Deletes a key by its alias.
    fn delete_key(&self, alias: &KeyAlias) -> Result<(), AgentError>;

    /// Lists all aliases stored by this backend for the specific service.
    fn list_aliases(&self) -> Result<Vec<KeyAlias>, AgentError>;

    /// Lists aliases associated ONLY with the given identity DID.
    fn list_aliases_for_identity(
        &self,
        identity_did: &IdentityDID,
    ) -> Result<Vec<KeyAlias>, AgentError>;

    /// List aliases for an identity filtered by role.
    fn list_aliases_for_identity_with_role(
        &self,
        identity_did: &IdentityDID,
        role: KeyRole,
    ) -> Result<Vec<KeyAlias>, AgentError> {
        let all = self.list_aliases_for_identity(identity_did)?;
        let mut filtered = Vec::new();
        for alias in all {
            if let Ok((_, r, _)) = self.load_key(&alias)
                && r == role
            {
                filtered.push(alias);
            }
        }
        Ok(filtered)
    }

    /// Retrieves the identity DID associated with a given alias.
    fn get_identity_for_alias(&self, alias: &KeyAlias) -> Result<IdentityDID, AgentError>;

    /// Returns the name of the storage backend.
    fn backend_name(&self) -> &'static str;

    /// Returns true if this backend manages keys in hardware (SE, HSM).
    ///
    /// Hardware backends generate keys internally, don't need passphrases,
    /// and store opaque handles instead of encrypted PKCS8.
    fn is_hardware_backend(&self) -> bool {
        false
    }

    /// Re-associates an existing stored key with a different identity DID
    /// without touching the key material.
    ///
    /// Needed by KERI inception: the key must exist (so its public key can be
    /// read) before the identity prefix it belongs to can be derived. The
    /// default implementation round-trips the stored material through
    /// `store_key`, which is correct for software backends. Hardware backends
    /// MUST override this — their `store_key` generates a fresh key, which
    /// would orphan the original.
    ///
    /// Args:
    /// * `alias`: Alias of the already-stored key.
    /// * `identity_did`: The identity to associate the key with.
    ///
    /// Usage:
    /// ```ignore
    /// keychain.rebind_identity(&alias, &controller_did)?;
    /// ```
    fn rebind_identity(
        &self,
        alias: &KeyAlias,
        identity_did: &IdentityDID,
    ) -> Result<(), AgentError> {
        if self.is_hardware_backend() {
            return Err(AgentError::StorageError(format!(
                "hardware backend '{}' must override rebind_identity",
                self.backend_name()
            )));
        }
        let (_, role, material) = self.load_key(alias)?;
        self.store_key(alias, identity_did, role, &material)
    }

    /// Returns the raw public key bytes of a stored key without a passphrase.
    ///
    /// Hardware backends derive this from their opaque handle; software
    /// backends would need a passphrase to decrypt the stored PKCS8, so the
    /// default errors — use `extract_public_key_bytes` for those.
    fn export_public_key(&self, alias: &KeyAlias) -> Result<Vec<u8>, AgentError> {
        let _ = alias;
        Err(AgentError::StorageError(format!(
            "backend '{}' does not support passphrase-less public key export",
            self.backend_name()
        )))
    }

    /// Signs a message with a stored key without a passphrase.
    ///
    /// Hardware backends sign inside the hardware (may trigger a biometric
    /// prompt); software backends need a passphrase, so the default errors —
    /// use `SecureSigner::sign_with_alias` for those.
    fn sign_raw(&self, alias: &KeyAlias, message: &[u8]) -> Result<Vec<u8>, AgentError> {
        let _ = (alias, message);
        Err(AgentError::StorageError(format!(
            "backend '{}' does not support passphrase-less signing",
            self.backend_name()
        )))
    }
}

/// Decrypt a stored key and return its public key bytes and curve type.
///
/// Loads the encrypted key for `alias`, calls `passphrase_provider` to obtain
/// the decryption passphrase, decrypts the PKCS8 blob, and returns the raw
/// public key along with its curve type.
///
/// Args:
/// * `keychain`: The key storage backend holding the encrypted key.
/// * `alias`: Keychain alias of the stored key.
/// * `passphrase_provider`: Provider to obtain the decryption passphrase.
///
/// Usage:
/// ```ignore
/// let (pk, curve) = extract_public_key_bytes(keychain, "my-key", &provider)?;
/// ```
pub fn extract_public_key_bytes(
    keychain: &dyn KeyStorage,
    alias: &KeyAlias,
    passphrase_provider: &dyn crate::signing::PassphraseProvider,
) -> Result<(Vec<u8>, auths_crypto::CurveType), AgentError> {
    if keychain.is_hardware_backend() {
        // Hardware backends store opaque handles — get public key from hardware
        let (_, _role, _handle) = keychain.load_key(alias)?;
        #[cfg(all(target_os = "macos", feature = "keychain-secure-enclave"))]
        {
            let pubkey = super::secure_enclave::public_key_from_handle(&_handle)?;
            return Ok((pubkey, auths_crypto::CurveType::P256));
        }
        #[cfg(not(all(target_os = "macos", feature = "keychain-secure-enclave")))]
        {
            return Err(AgentError::BackendUnavailable {
                backend: keychain.backend_name(),
                reason: "hardware backend not available on this platform".into(),
            });
        }
    }

    use crate::crypto::signer::{decrypt_keypair, load_seed_and_pubkey};

    let (_, _role, encrypted) = keychain.load_key(alias)?;
    let passphrase = passphrase_provider
        .get_passphrase(&format!("Enter passphrase for key '{alias}':"))
        .map_err(|e| AgentError::SigningFailed(e.to_string()))?;
    let pkcs8 = decrypt_keypair(&encrypted, &passphrase)?;
    let (_, pubkey, curve) = load_seed_and_pubkey(&pkcs8)?;
    Ok((pubkey.to_vec(), curve))
}

/// Sign a message using the key for `alias`, handling both software and hardware backends.
///
/// - Software: prompts for passphrase, decrypts PKCS8, signs with `TypedSeed`
/// - Hardware (Secure Enclave): loads handle, signs via biometric (Touch ID)
///
/// Returns `(signature, public_key, curve)`. Callers never need to know the backend type.
///
/// Args:
/// * `keychain`: The key storage backend.
/// * `alias`: The key alias to sign with.
/// * `passphrase_provider`: Provider for passphrase prompts (ignored on hardware backends).
/// * `message`: The raw bytes to sign.
pub fn sign_with_key(
    keychain: &dyn KeyStorage,
    alias: &KeyAlias,
    passphrase_provider: &dyn crate::signing::PassphraseProvider,
    message: &[u8],
) -> Result<(Vec<u8>, Vec<u8>, auths_crypto::CurveType), AgentError> {
    if keychain.is_hardware_backend() {
        let (_, _role, _handle) = keychain.load_key(alias)?;
        #[cfg(all(target_os = "macos", feature = "keychain-secure-enclave"))]
        {
            let sig = super::secure_enclave::sign_with_handle(&_handle, message)?;
            let pubkey = super::secure_enclave::public_key_from_handle(&_handle)?;
            return Ok((sig, pubkey, auths_crypto::CurveType::P256));
        }
        #[cfg(not(all(target_os = "macos", feature = "keychain-secure-enclave")))]
        {
            return Err(AgentError::BackendUnavailable {
                backend: keychain.backend_name(),
                reason: "hardware signing not available on this platform".into(),
            });
        }
    }

    use crate::crypto::signer::{decrypt_keypair, load_seed_and_pubkey};

    let (_, _role, encrypted) = keychain.load_key(alias)?;
    let passphrase = passphrase_provider
        .get_passphrase(&format!("Enter passphrase for key '{}' to sign:", alias))
        .map_err(|e| AgentError::SigningFailed(e.to_string()))?;
    let pkcs8 = decrypt_keypair(&encrypted, &passphrase)?;
    let (seed, pubkey, curve) = load_seed_and_pubkey(&pkcs8)?;

    let typed_seed = match curve {
        auths_crypto::CurveType::Ed25519 => auths_crypto::TypedSeed::Ed25519(*seed.as_bytes()),
        auths_crypto::CurveType::P256 => auths_crypto::TypedSeed::P256(*seed.as_bytes()),
    };

    let sig = auths_crypto::typed_sign(&typed_seed, message)
        .map_err(|e| AgentError::SigningFailed(e.to_string()))?;

    Ok((sig, pubkey, curve))
}

/// Return a boxed `KeyStorage` implementation driven by the supplied `EnvironmentConfig`.
///
/// Uses `config.keychain.backend` to select the backend and `config.keychain.file_path`
/// / `config.keychain.passphrase` for the encrypted-file backend. Falls back to the
/// platform default when no override is specified.
///
/// Args:
/// * `config` - The environment configuration carrying keychain settings and home path.
///
/// Usage:
/// ```ignore
/// let env = EnvironmentConfig::from_env();
/// let keychain = get_platform_keychain_with_config(&env)?;
/// ```
pub fn get_platform_keychain_with_config(
    config: &EnvironmentConfig,
) -> Result<Box<dyn KeyStorage + Send + Sync>, AgentError> {
    if let Some(ref backend) = config.keychain.backend {
        return get_backend_by_name(backend, config);
    }
    get_platform_default(config)
}

/// Return a boxed KeyStorage implementation for the current platform.
///
/// Reads keychain configuration from environment variables via
/// `EnvironmentConfig::from_env()`. Prefer `get_platform_keychain_with_config`
/// for new code to keep env-var reads at the process boundary.
///
/// # Environment Variable Override
///
/// Set `AUTHS_KEYCHAIN_BACKEND` to override the platform default:
/// - `"file"` - Use encrypted file storage at `~/.auths/keys.enc`
/// - `"memory"` - Use in-memory storage (for testing only)
///
/// Invalid values will log a warning and use the platform default.
///
/// # Errors
/// Returns `AgentError` if the platform keychain fails to initialize.
pub fn get_platform_keychain() -> Result<Box<dyn KeyStorage + Send + Sync>, AgentError> {
    get_platform_keychain_with_config(&EnvironmentConfig::from_env())
}

/// Get the platform-default keychain backend.
#[allow(unused_variables, unreachable_code)]
fn get_platform_default(
    config: &EnvironmentConfig,
) -> Result<Box<dyn KeyStorage + Send + Sync>, AgentError> {
    #[cfg(target_os = "ios")]
    {
        return Ok(Box::new(IOSKeychain::new(SERVICE_NAME)));
    }

    #[cfg(target_os = "macos")]
    {
        // Try Secure Enclave first (fingerprint signing), fall back to macOS Keychain
        #[cfg(feature = "keychain-secure-enclave")]
        {
            if super::secure_enclave::is_available()
                && let Ok(home) = auths_home_with_config(config)
            {
                match super::secure_enclave::SecureEnclaveKeyStorage::new(&home) {
                    Ok(storage) => {
                        log::info!("Using Secure Enclave (Touch ID signing)");
                        return Ok(Box::new(storage));
                    }
                    Err(e) => {
                        log::warn!(
                            "Secure Enclave available but init failed ({}), using macOS Keychain",
                            e
                        );
                    }
                }
            }
        }
        return Ok(Box::new(MacOSKeychain::new(SERVICE_NAME)));
    }

    #[cfg(all(target_os = "linux", feature = "keychain-linux-secretservice"))]
    {
        // Try Secret Service first, fall back to encrypted file storage
        match LinuxSecretServiceStorage::new(SERVICE_NAME) {
            Ok(storage) => return Ok(Box::new(storage)),
            Err(e) => {
                warn!("Secret Service unavailable ({}), trying file fallback", e);
                #[cfg(feature = "keychain-file-fallback")]
                {
                    return new_encrypted_file_storage(config).map(|s| {
                        let b: Box<dyn KeyStorage + Send + Sync> = Box::new(s);
                        b
                    });
                }
                #[cfg(not(feature = "keychain-file-fallback"))]
                {
                    return Err(e);
                }
            }
        }
    }

    #[cfg(all(target_os = "linux", not(feature = "keychain-linux-secretservice")))]
    {
        // No Secret Service feature, check for file fallback
        #[cfg(feature = "keychain-file-fallback")]
        {
            return new_encrypted_file_storage(config).map(|s| {
                let b: Box<dyn KeyStorage + Send + Sync> = Box::new(s);
                b
            });
        }
    }

    #[cfg(all(target_os = "windows", feature = "keychain-windows"))]
    {
        return Ok(Box::new(WindowsCredentialStorage::new(SERVICE_NAME)?));
    }

    #[cfg(target_os = "android")]
    {
        return Ok(Box::new(AndroidKeystoreStorage::new(SERVICE_NAME)?));
    }

    // Fallback for unsupported platforms or missing features
    #[allow(unused_variables)]
    let _ = config;
    #[allow(unreachable_code)]
    {
        warn!("Using in-memory keychain (not recommended for production)");
        Ok(Box::new(MemoryKeychainHandle))
    }
}

/// Get a keychain backend by name (for environment variable override).
fn get_backend_by_name(
    name: &str,
    config: &EnvironmentConfig,
) -> Result<Box<dyn KeyStorage + Send + Sync>, AgentError> {
    match name.to_lowercase().as_str() {
        "memory" => {
            info!("Using in-memory keychain (AUTHS_KEYCHAIN_BACKEND=memory)");
            Ok(Box::new(MemoryKeychainHandle))
        }
        "file" => {
            info!("Using encrypted file storage (AUTHS_KEYCHAIN_BACKEND=file)");
            let storage = new_encrypted_file_storage(config)?;
            Ok(Box::new(storage))
        }
        #[cfg(feature = "keychain-pkcs11")]
        "hsm" | "pkcs11" => {
            info!("Using PKCS#11 HSM backend (AUTHS_KEYCHAIN_BACKEND={name})");
            let pkcs11_config =
                config
                    .pkcs11
                    .as_ref()
                    .ok_or_else(|| AgentError::BackendInitFailed {
                        backend: "pkcs11",
                        error: "PKCS#11 configuration required (set AUTHS_PKCS11_LIBRARY)".into(),
                    })?;
            let storage = super::pkcs11::Pkcs11KeyRef::new(pkcs11_config)?;
            Ok(Box::new(storage))
        }
        #[cfg(all(target_os = "macos", feature = "keychain-secure-enclave"))]
        "secure-enclave" => {
            info!("Using Secure Enclave backend (AUTHS_KEYCHAIN_BACKEND=secure-enclave)");
            let home =
                auths_home_with_config(config).map_err(|e| AgentError::BackendInitFailed {
                    backend: "secure-enclave",
                    error: format!("failed to resolve auths home: {e}"),
                })?;
            let storage = super::secure_enclave::SecureEnclaveKeyStorage::new(&home)?;
            Ok(Box::new(storage))
        }
        _ => {
            warn!(
                "Unknown keychain backend '{}', using platform default",
                name
            );
            get_platform_default(config)
        }
    }
}

/// Construct an `EncryptedFileStorage` from the provided config.
///
/// Uses `config.keychain.file_path` when set; otherwise resolves the default
/// path from `config.auths_home` (or `~/.auths/keys.enc`).
/// Sets the password from `config.keychain.passphrase` when present.
fn new_encrypted_file_storage(
    config: &EnvironmentConfig,
) -> Result<EncryptedFileStorage, AgentError> {
    let storage = if let Some(ref path) = config.keychain.file_path {
        EncryptedFileStorage::with_path(path.clone())?
    } else {
        let home =
            auths_home_with_config(config).map_err(|e| AgentError::StorageError(e.to_string()))?;
        EncryptedFileStorage::new(&home)?
    };

    if let Some(ref passphrase) = config.keychain.passphrase {
        storage.set_password(Zeroizing::new(passphrase.clone()));
    }

    Ok(storage)
}

/// Creates a PKCS#11-backed [`SecureSigner`](crate::signing::SecureSigner) from the
/// environment config, if the backend is set to `"pkcs11"` or `"hsm"`.
///
/// Returns `None` if the keychain backend is not PKCS#11.
///
/// Args:
/// * `config`: Environment configuration.
///
/// Usage:
/// ```ignore
/// if let Some(signer) = get_pkcs11_signer(&env)? {
///     signer.sign_with_alias(&alias, &provider, message)?;
/// }
/// ```
#[cfg(feature = "keychain-pkcs11")]
pub fn get_pkcs11_signer(
    config: &EnvironmentConfig,
) -> Result<Option<Box<dyn crate::signing::SecureSigner>>, AgentError> {
    let is_pkcs11 = config
        .keychain
        .backend
        .as_deref()
        .map(|b| matches!(b.to_lowercase().as_str(), "hsm" | "pkcs11"))
        .unwrap_or(false);

    if !is_pkcs11 {
        return Ok(None);
    }

    let pkcs11_config = config
        .pkcs11
        .as_ref()
        .ok_or_else(|| AgentError::BackendInitFailed {
            backend: "pkcs11",
            error: "PKCS#11 configuration required (set AUTHS_PKCS11_LIBRARY)".into(),
        })?;

    let signer = super::pkcs11::Pkcs11Signer::new(pkcs11_config)?;
    Ok(Some(Box::new(signer)))
}

impl KeyStorage for Arc<dyn KeyStorage + Send + Sync> {
    fn store_key(
        &self,
        alias: &KeyAlias,
        identity_did: &IdentityDID,
        role: KeyRole,
        encrypted_key_data: &[u8],
    ) -> Result<(), AgentError> {
        self.as_ref()
            .store_key(alias, identity_did, role, encrypted_key_data)
    }
    fn load_key(&self, alias: &KeyAlias) -> Result<(IdentityDID, KeyRole, Vec<u8>), AgentError> {
        self.as_ref().load_key(alias)
    }
    fn delete_key(&self, alias: &KeyAlias) -> Result<(), AgentError> {
        self.as_ref().delete_key(alias)
    }
    fn list_aliases(&self) -> Result<Vec<KeyAlias>, AgentError> {
        self.as_ref().list_aliases()
    }
    fn list_aliases_for_identity(
        &self,
        identity_did: &IdentityDID,
    ) -> Result<Vec<KeyAlias>, AgentError> {
        self.as_ref().list_aliases_for_identity(identity_did)
    }
    fn list_aliases_for_identity_with_role(
        &self,
        identity_did: &IdentityDID,
        role: KeyRole,
    ) -> Result<Vec<KeyAlias>, AgentError> {
        self.as_ref()
            .list_aliases_for_identity_with_role(identity_did, role)
    }
    fn get_identity_for_alias(&self, alias: &KeyAlias) -> Result<IdentityDID, AgentError> {
        self.as_ref().get_identity_for_alias(alias)
    }
    fn backend_name(&self) -> &'static str {
        self.as_ref().backend_name()
    }
    fn is_hardware_backend(&self) -> bool {
        self.as_ref().is_hardware_backend()
    }
}

impl KeyStorage for Box<dyn KeyStorage + Send + Sync> {
    fn store_key(
        &self,
        alias: &KeyAlias,
        identity_did: &IdentityDID,
        role: KeyRole,
        encrypted_key_data: &[u8],
    ) -> Result<(), AgentError> {
        self.as_ref()
            .store_key(alias, identity_did, role, encrypted_key_data)
    }
    fn load_key(&self, alias: &KeyAlias) -> Result<(IdentityDID, KeyRole, Vec<u8>), AgentError> {
        self.as_ref().load_key(alias)
    }
    fn delete_key(&self, alias: &KeyAlias) -> Result<(), AgentError> {
        self.as_ref().delete_key(alias)
    }
    fn list_aliases(&self) -> Result<Vec<KeyAlias>, AgentError> {
        self.as_ref().list_aliases()
    }
    fn list_aliases_for_identity(
        &self,
        identity_did: &IdentityDID,
    ) -> Result<Vec<KeyAlias>, AgentError> {
        self.as_ref().list_aliases_for_identity(identity_did)
    }
    fn list_aliases_for_identity_with_role(
        &self,
        identity_did: &IdentityDID,
        role: KeyRole,
    ) -> Result<Vec<KeyAlias>, AgentError> {
        self.as_ref()
            .list_aliases_for_identity_with_role(identity_did, role)
    }
    fn get_identity_for_alias(&self, alias: &KeyAlias) -> Result<IdentityDID, AgentError> {
        self.as_ref().get_identity_for_alias(alias)
    }
    fn backend_name(&self) -> &'static str {
        self.as_ref().backend_name()
    }
    fn is_hardware_backend(&self) -> bool {
        self.as_ref().is_hardware_backend()
    }
}

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

    #[test]
    fn test_service_name_constant() {
        assert_eq!(SERVICE_NAME, "dev.auths.agent");
    }

    #[test]
    fn test_get_backend_by_name_memory() {
        let env = EnvironmentConfig::default();
        let backend = get_backend_by_name("memory", &env).unwrap();
        assert_eq!(backend.backend_name(), "Memory");
    }

    #[test]
    fn test_get_backend_by_name_case_insensitive() {
        let env = EnvironmentConfig::default();
        let backend = get_backend_by_name("MEMORY", &env).unwrap();
        assert_eq!(backend.backend_name(), "Memory");
    }

    #[test]
    fn test_key_role_serde_roundtrip() {
        let roles = [
            KeyRole::Primary,
            KeyRole::NextRotation,
            KeyRole::DelegatedAgent,
        ];
        for role in &roles {
            let json = serde_json::to_string(role).unwrap();
            let parsed: KeyRole = serde_json::from_str(&json).unwrap();
            assert_eq!(*role, parsed);
        }
    }

    #[test]
    fn test_key_role_display_and_parse() {
        assert_eq!(KeyRole::Primary.to_string(), "primary");
        assert_eq!(KeyRole::NextRotation.to_string(), "next_rotation");
        assert_eq!(KeyRole::DelegatedAgent.to_string(), "delegated_agent");
        assert_eq!("primary".parse::<KeyRole>().unwrap(), KeyRole::Primary);
        assert_eq!(
            "delegated_agent".parse::<KeyRole>().unwrap(),
            KeyRole::DelegatedAgent
        );
        assert!("unknown".parse::<KeyRole>().is_err());
    }

    #[test]
    fn test_list_aliases_with_role_filter() {
        use super::super::memory::IsolatedKeychainHandle;

        let keychain = IsolatedKeychainHandle::new();
        #[allow(clippy::disallowed_methods)]
        // INVARIANT: test-only literal with valid did:keri: prefix
        let did = IdentityDID::new_unchecked("did:keri:Etest".to_string());

        keychain
            .store_key(
                &KeyAlias::new_unchecked("operator"),
                &did,
                KeyRole::Primary,
                b"key1",
            )
            .unwrap();
        keychain
            .store_key(
                &KeyAlias::new_unchecked("operator--next-0"),
                &did,
                KeyRole::NextRotation,
                b"key2",
            )
            .unwrap();
        keychain
            .store_key(
                &KeyAlias::new_unchecked("deploy-agent"),
                &did,
                KeyRole::DelegatedAgent,
                b"key3",
            )
            .unwrap();

        let primary = keychain
            .list_aliases_for_identity_with_role(&did, KeyRole::Primary)
            .unwrap();
        assert_eq!(primary.len(), 1);
        assert_eq!(primary[0].as_str(), "operator");

        let agents = keychain
            .list_aliases_for_identity_with_role(&did, KeyRole::DelegatedAgent)
            .unwrap();
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0].as_str(), "deploy-agent");
    }
}