oxirs 0.3.1

Command-line interface for OxiRS - import, export, migration, and benchmarking tools
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
//! Secret management for sensitive configuration data
//!
//! Provides secure storage and retrieval of sensitive information like
//! API keys, passwords, and authentication tokens.

use crate::cli::error::{CliError, CliResult};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;

/// Secret manager for handling sensitive data
pub struct SecretManager {
    /// Secrets directory
    secrets_dir: PathBuf,
    /// In-memory cache of decrypted secrets
    cache: HashMap<String, SecretValue>,
    /// Encryption key (derived from master password or system keyring)
    key: Option<Vec<u8>>,
}

/// A secret value with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretValue {
    /// The actual secret value (encrypted when stored)
    pub value: String,
    /// Description of the secret
    pub description: Option<String>,
    /// Creation timestamp
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Last modified timestamp
    pub updated_at: chrono::DateTime<chrono::Utc>,
    /// Expiration time (if any)
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Secret storage backend
#[derive(Debug, Clone, Copy)]
pub enum SecretBackend {
    /// File-based storage (encrypted)
    File,
    /// System keyring (macOS Keychain, Windows Credential Manager, Linux Secret Service)
    SystemKeyring,
    /// Environment variables
    Environment,
    /// HashiCorp Vault
    Vault,
}

impl SecretManager {
    /// Create a new secret manager
    pub fn new(_backend: SecretBackend) -> CliResult<Self> {
        let secrets_dir = Self::get_secrets_dir()?;
        Self::with_dir(secrets_dir)
    }

    /// Create a new secret manager with a specific directory
    ///
    /// This is useful for testing and custom configurations where the
    /// default directory is not suitable.
    pub fn with_dir(secrets_dir: PathBuf) -> CliResult<Self> {
        // Ensure secrets directory exists with restricted permissions
        if !secrets_dir.exists() {
            fs::create_dir_all(&secrets_dir).map_err(|e| {
                CliError::config_error(format!("Cannot create secrets directory: {e}"))
            })?;

            // Set restrictive permissions (700 - owner only)
            #[cfg(unix)]
            {
                let metadata = fs::metadata(&secrets_dir)?;
                let mut permissions = metadata.permissions();
                permissions.set_mode(0o700);
                fs::set_permissions(&secrets_dir, permissions)?;
            }
        }

        Ok(Self {
            secrets_dir,
            cache: HashMap::new(),
            key: None,
        })
    }

    /// Get the secrets directory
    fn get_secrets_dir() -> CliResult<PathBuf> {
        // Check environment variable first
        if let Ok(dir) = std::env::var("OXIRS_SECRETS_DIR") {
            return Ok(PathBuf::from(dir));
        }

        // Use platform-specific secure directory
        #[cfg(target_os = "macos")]
        let base_dir = dirs::home_dir().map(|h| h.join("Library/Application Support"));

        #[cfg(target_os = "linux")]
        let base_dir = dirs::config_dir();

        #[cfg(target_os = "windows")]
        let base_dir = dirs::data_local_dir();

        base_dir
            .map(|p| p.join("oxirs/secrets"))
            .ok_or_else(|| CliError::config_error("Cannot determine secrets directory"))
    }

    /// Initialize with master password
    pub fn unlock(&mut self, password: &str) -> CliResult<()> {
        // Derive encryption key from password using a key derivation function
        self.key = Some(self.derive_key(password)?);

        // Try to decrypt a test secret to verify the password
        if self.secrets_dir.join(".test").exists() {
            self.get_secret(".test")?;
        }

        Ok(())
    }

    /// Check if the secret manager is unlocked
    pub fn is_unlocked(&self) -> bool {
        self.key.is_some()
    }

    /// Store a secret
    pub fn set_secret(
        &mut self,
        name: &str,
        value: &str,
        description: Option<String>,
    ) -> CliResult<()> {
        if !self.is_unlocked() {
            return Err(CliError::config_error("Secret manager is locked"));
        }

        let secret = SecretValue {
            value: value.to_string(),
            description,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            expires_at: None,
        };

        // Encrypt and store
        self.store_encrypted_secret(name, &secret)?;

        // Update cache
        self.cache.insert(name.to_string(), secret);

        Ok(())
    }

    /// Retrieve a secret
    pub fn get_secret(&mut self, name: &str) -> CliResult<String> {
        // Check cache first
        if let Some(secret) = self.cache.get(name) {
            // Check expiration
            if let Some(expires) = secret.expires_at {
                if expires < chrono::Utc::now() {
                    self.cache.remove(name);
                    return Err(CliError::config_error("Secret has expired"));
                }
            }
            return Ok(secret.value.clone());
        }

        // Try environment variable
        let env_name = format!("OXIRS_SECRET_{}", name.to_uppercase().replace('-', "_"));
        if let Ok(value) = std::env::var(&env_name) {
            return Ok(value);
        }

        // Load from encrypted storage
        if !self.is_unlocked() {
            return Err(CliError::config_error("Secret manager is locked"));
        }

        let secret = self.load_encrypted_secret(name)?;

        // Check expiration
        if let Some(expires) = secret.expires_at {
            if expires < chrono::Utc::now() {
                return Err(CliError::config_error("Secret has expired"));
            }
        }

        let value = secret.value.clone();
        self.cache.insert(name.to_string(), secret);

        Ok(value)
    }

    /// Delete a secret
    pub fn delete_secret(&mut self, name: &str) -> CliResult<()> {
        self.cache.remove(name);

        let path = self.secrets_dir.join(format!("{name}.secret"));
        if path.exists() {
            fs::remove_file(path)
                .map_err(|e| CliError::config_error(format!("Cannot delete secret: {e}")))?;
        }

        Ok(())
    }

    /// List all secrets (names only, not values)
    pub fn list_secrets(&self) -> CliResult<Vec<SecretInfo>> {
        let mut secrets = Vec::new();

        if self.secrets_dir.exists() {
            for entry in fs::read_dir(&self.secrets_dir)? {
                let entry = entry?;
                let path = entry.path();

                if let Some(name) = path.file_stem().and_then(|n| n.to_str()) {
                    if path.extension().and_then(|e| e.to_str()) == Some("secret")
                        && name != ".test"
                    {
                        // Try to load metadata without decrypting value
                        if let Ok(metadata) = self.load_secret_metadata(name) {
                            secrets.push(metadata);
                        }
                    }
                }
            }
        }

        // Also list environment variable secrets
        for (key, _) in std::env::vars() {
            if key.starts_with("OXIRS_SECRET_") {
                let name = key
                    .strip_prefix("OXIRS_SECRET_")
                    .expect("prefix should match after starts_with check")
                    .to_lowercase()
                    .replace('_', "-");

                secrets.push(SecretInfo {
                    name,
                    description: Some("Environment variable".to_string()),
                    created_at: None,
                    expires_at: None,
                    source: SecretSource::Environment,
                });
            }
        }

        secrets.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(secrets)
    }

    /// Derive encryption key from password
    ///
    /// Uses PBKDF2-HMAC-SHA256 with 100,000 iterations and a fixed salt. These
    /// parameters (algorithm, iteration count, salt, and 32-byte output length)
    /// are kept identical to the previous `ring::pbkdf2` implementation so that
    /// keys derived before the OxiCrypto migration still decrypt existing
    /// on-disk secrets.
    fn derive_key(&self, password: &str) -> CliResult<Vec<u8>> {
        let salt = b"oxirs-secret-salt"; // In production, use a random salt stored separately
        let mut key = vec![0u8; 32];

        oxicrypto_kdf::pbkdf2_sha256(password.as_bytes(), salt, 100_000, &mut key)
            .map_err(|e| CliError::config_error(format!("Key derivation failed: {e}")))?;

        Ok(key)
    }

    /// Encrypt and store a secret
    fn store_encrypted_secret(&self, name: &str, secret: &SecretValue) -> CliResult<()> {
        use oxicrypto_core::Aead;

        let key = self
            .key
            .as_ref()
            .ok_or_else(|| CliError::config_error("No encryption key available"))?;

        // Serialize secret
        let plaintext = serde_json::to_vec(secret)
            .map_err(|e| CliError::config_error(format!("Cannot serialize secret: {e}")))?;

        // Encrypt using AES-256-GCM (OxiCrypto, Pure Rust).
        //
        // On-disk layout is unchanged from the previous `ring` implementation:
        // `seal_to_vec` returns `ciphertext || tag` (16-byte GCM tag appended),
        // a fixed all-zero 12-byte nonce is used, and the AAD is empty.
        let nonce = [0u8; 12]; // In production, use random nonce
        let ciphertext = oxicrypto_aead::Aes256Gcm
            .seal_to_vec(key, &nonce, &[], &plaintext)
            .map_err(|_| CliError::config_error("Encryption failed"))?;

        // Write to file
        let path = self.secrets_dir.join(format!("{name}.secret"));
        let mut file = File::create(&path)
            .map_err(|e| CliError::config_error(format!("Cannot create secret file: {e}")))?;

        // Set restrictive permissions
        #[cfg(unix)]
        {
            let metadata = file.metadata()?;
            let mut permissions = metadata.permissions();
            permissions.set_mode(0o600);
            file.set_permissions(permissions)?;
        }

        file.write_all(&ciphertext)
            .map_err(|e| CliError::config_error(format!("Cannot write secret: {e}")))?;

        Ok(())
    }

    /// Load and decrypt a secret
    fn load_encrypted_secret(&self, name: &str) -> CliResult<SecretValue> {
        use oxicrypto_core::Aead;

        let key = self
            .key
            .as_ref()
            .ok_or_else(|| CliError::config_error("No decryption key available"))?;

        // Read encrypted data
        let path = self.secrets_dir.join(format!("{name}.secret"));
        let mut file = File::open(&path)
            .map_err(|_| CliError::config_error(format!("Secret '{name}' not found")))?;

        let mut ciphertext = Vec::new();
        file.read_to_end(&mut ciphertext)
            .map_err(|e| CliError::config_error(format!("Cannot read secret: {e}")))?;

        // Decrypt using AES-256-GCM (OxiCrypto, Pure Rust).
        //
        // The file holds `ciphertext || tag`; `open_to_vec` verifies the
        // appended 16-byte GCM tag and returns the plaintext. The fixed all-zero
        // 12-byte nonce and empty AAD mirror `store_encrypted_secret`.
        let nonce = [0u8; 12];
        let plaintext = oxicrypto_aead::Aes256Gcm
            .open_to_vec(key, &nonce, &[], &ciphertext)
            .map_err(|_| CliError::config_error("Decryption failed - wrong password?"))?;

        // Deserialize secret
        serde_json::from_slice(&plaintext)
            .map_err(|e| CliError::config_error(format!("Cannot deserialize secret: {e}")))
    }

    /// Load secret metadata without decrypting the value
    fn load_secret_metadata(&self, name: &str) -> CliResult<SecretInfo> {
        // For now, return basic info
        // In a real implementation, we'd store metadata separately
        Ok(SecretInfo {
            name: name.to_string(),
            description: None,
            created_at: None,
            expires_at: None,
            source: SecretSource::File,
        })
    }
}

/// Information about a secret (without the actual value)
#[derive(Debug, Clone)]
pub struct SecretInfo {
    pub name: String,
    pub description: Option<String>,
    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
    pub source: SecretSource,
}

/// Source of a secret
#[derive(Debug, Clone, Copy)]
pub enum SecretSource {
    File,
    Environment,
    SystemKeyring,
}

/// Integration with system keyring.
///
/// Requires the `system-keyring` Cargo feature:
/// ```text
/// cargo build --features system-keyring
/// ```
///
/// The underlying [`keyring`](https://docs.rs/keyring) crate delegates to the
/// platform's native credential store:
/// - **macOS** — Security framework (Keychain)
/// - **Windows** — Credential Manager
/// - **Linux** — Secret Service API (e.g. GNOME Keyring / KWallet)
pub mod keyring {
    use super::*;

    /// Store a secret in the system keyring.
    ///
    /// On macOS this uses the Keychain Services API via `apple-native-keyring-store`.
    /// The default credential store is initialised lazily on first call.
    ///
    /// # Errors
    ///
    /// Returns an error if the `system-keyring` feature is not enabled or if
    /// the OS credential store rejects the operation.
    #[cfg(feature = "system-keyring")]
    pub fn store_in_keyring(service: &str, name: &str, value: &str) -> CliResult<()> {
        init_default_store()?;
        let entry = keyring_core::Entry::new(service, name).map_err(|e| {
            CliError::config_error(format!(
                "System keyring error creating entry '{name}' for service '{service}': {e}"
            ))
        })?;
        entry.set_password(value).map_err(|e| {
            CliError::config_error(format!(
                "System keyring error storing secret '{name}' for service '{service}': {e}"
            ))
        })
    }

    #[cfg(not(feature = "system-keyring"))]
    pub fn store_in_keyring(_service: &str, _name: &str, _value: &str) -> CliResult<()> {
        Err(CliError::config_error(
            "System keyring requires the 'system-keyring' feature flag. \
             Rebuild with: cargo build --features system-keyring",
        ))
    }

    /// Retrieve a secret from the system keyring.
    ///
    /// # Errors
    ///
    /// Returns an error if the `system-keyring` feature is not enabled, if the
    /// secret is not found, or if the OS credential store returns an error.
    #[cfg(feature = "system-keyring")]
    pub fn get_from_keyring(service: &str, name: &str) -> CliResult<String> {
        init_default_store()?;
        let entry = keyring_core::Entry::new(service, name).map_err(|e| {
            CliError::config_error(format!(
                "System keyring error creating entry '{name}' for service '{service}': {e}"
            ))
        })?;
        entry.get_password().map_err(|e| {
            CliError::config_error(format!(
                "System keyring error retrieving secret '{name}' for service '{service}': {e}"
            ))
        })
    }

    #[cfg(not(feature = "system-keyring"))]
    pub fn get_from_keyring(_service: &str, _name: &str) -> CliResult<String> {
        Err(CliError::config_error(
            "System keyring requires the 'system-keyring' feature flag. \
             Rebuild with: cargo build --features system-keyring",
        ))
    }

    /// Initialise the default keyring-core credential store.
    ///
    /// Uses the macOS Keychain on macOS and the `keyring-core` sample store
    /// (in-memory, non-persistent) on other platforms for testing purposes.
    ///
    /// Safe to call multiple times — the store is only set once.
    #[cfg(feature = "system-keyring")]
    fn init_default_store() -> CliResult<()> {
        use std::sync::{Mutex, Once};
        static INIT: Once = Once::new();
        static INIT_ERR: Mutex<Option<String>> = Mutex::new(None);

        INIT.call_once(|| {
            let result: CliResult<()> = (|| {
                #[cfg(target_os = "macos")]
                {
                    use apple_native_keyring_store::keychain::Store;
                    let store = Store::new_with_configuration(&std::collections::HashMap::new())
                        .map_err(|e| {
                            CliError::config_error(format!(
                                "Failed to initialise macOS Keychain store: {e}"
                            ))
                        })?;
                    keyring_core::set_default_store(store);
                }
                #[cfg(not(target_os = "macos"))]
                {
                    // Fall back to the in-memory sample store on non-macOS platforms
                    // (useful for CI/testing; not persistent across processes)
                    use keyring_core::sample::Store;
                    let store =
                        Store::new_with_configuration(&std::collections::HashMap::from([(
                            "persist", "true",
                        )]))
                        .map_err(|e| {
                            CliError::config_error(format!(
                                "Failed to initialise keyring sample store: {e}"
                            ))
                        })?;
                    keyring_core::set_default_store(store);
                }
                Ok(())
            })();
            if let Err(e) = result {
                if let Ok(mut guard) = INIT_ERR.lock() {
                    *guard = Some(e.to_string());
                }
            }
        });

        // Surface any initialisation error that was captured inside call_once
        match INIT_ERR.lock() {
            Ok(guard) => match guard.as_ref() {
                Some(msg) => Err(CliError::config_error(format!(
                    "System keyring initialisation failed: {msg}"
                ))),
                None => Ok(()),
            },
            Err(_) => Err(CliError::config_error(
                "Internal error: keyring init mutex poisoned",
            )),
        }
    }
}

/// Secure credential helpers
pub mod credentials {
    use super::*;

    /// SPARQL endpoint credentials
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct EndpointCredentials {
        pub url: String,
        pub username: Option<String>,
        pub password: Option<String>,
        pub auth_type: AuthType,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub enum AuthType {
        None,
        Basic,
        Bearer,
        OAuth2,
    }

    /// Get credentials for a SPARQL endpoint
    pub fn get_endpoint_credentials(
        manager: &mut SecretManager,
        url: &str,
    ) -> CliResult<EndpointCredentials> {
        let secret_name = format!("endpoint_{}", url.replace(['/', ':'], "_"));

        if let Ok(creds_json) = manager.get_secret(&secret_name) {
            serde_json::from_str(&creds_json)
                .map_err(|e| CliError::config_error(format!("Invalid credentials format: {e}")))
        } else {
            Ok(EndpointCredentials {
                url: url.to_string(),
                username: None,
                password: None,
                auth_type: AuthType::None,
            })
        }
    }

    /// Store credentials for a SPARQL endpoint
    pub fn store_endpoint_credentials(
        manager: &mut SecretManager,
        creds: &EndpointCredentials,
    ) -> CliResult<()> {
        let secret_name = format!("endpoint_{}", creds.url.replace(['/', ':'], "_"));
        let creds_json = serde_json::to_string(creds)
            .map_err(|e| CliError::config_error(format!("Cannot serialize credentials: {e}")))?;

        manager.set_secret(
            &secret_name,
            &creds_json,
            Some(format!("Credentials for {}", creds.url)),
        )
    }
}

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

    #[test]
    fn test_secret_manager_creation() {
        let dir = tempdir().expect("failed to create temp dir");
        let manager = SecretManager::with_dir(dir.path().to_path_buf())
            .expect("failed to create SecretManager");
        assert!(!manager.is_unlocked());
    }

    #[test]
    fn test_secret_storage_and_retrieval() {
        let dir = tempdir().expect("failed to create temp dir");
        let mut manager = SecretManager::with_dir(dir.path().to_path_buf())
            .expect("failed to create SecretManager");
        manager.unlock("test-password").expect("failed to unlock");

        // Store a secret
        manager
            .set_secret("test-key", "test-value", Some("Test secret".to_string()))
            .expect("failed to set secret");

        // Retrieve it
        let value = manager
            .get_secret("test-key")
            .expect("failed to get secret");
        assert_eq!(value, "test-value");

        // List secrets
        let secrets = manager.list_secrets().expect("failed to list secrets");
        assert!(secrets.iter().any(|s| s.name == "test-key"));
    }

    #[test]
    fn test_pbkdf2_derive_is_deterministic_and_correct_length() {
        // The migrated PBKDF2-SHA256 derivation must be stable for a given
        // password (same salt/iterations) and produce a 32-byte key, matching
        // the legacy `ring::pbkdf2` parameters so old secrets still decrypt.
        let dir = tempdir().expect("failed to create temp dir");
        let manager = SecretManager::with_dir(dir.path().to_path_buf())
            .expect("failed to create SecretManager");

        let key_a = manager
            .derive_key("correct horse battery staple")
            .expect("derive_key failed");
        let key_b = manager
            .derive_key("correct horse battery staple")
            .expect("derive_key failed");
        let key_other = manager
            .derive_key("a different password")
            .expect("derive_key failed");

        assert_eq!(key_a.len(), 32, "derived key must be 32 bytes for AES-256");
        assert_eq!(key_a, key_b, "PBKDF2 derivation must be deterministic");
        assert_ne!(
            key_a, key_other,
            "different passwords must derive different keys"
        );

        // Cross-check against the leaf crate directly with identical parameters.
        let mut expected = vec![0u8; 32];
        oxicrypto_kdf::pbkdf2_sha256(
            b"correct horse battery staple",
            b"oxirs-secret-salt",
            100_000,
            &mut expected,
        )
        .expect("pbkdf2_sha256 failed");
        assert_eq!(
            key_a, expected,
            "derive_key must match raw pbkdf2_sha256 output"
        );
    }

    #[test]
    fn test_encrypt_decrypt_round_trip_on_disk() {
        // Prove the migrated AES-256-GCM seal/open paths produce and consume the
        // same on-disk format (nonce-implicit, ciphertext || 16-byte tag).
        let dir = tempdir().expect("failed to create temp dir");
        let mut manager = SecretManager::with_dir(dir.path().to_path_buf())
            .expect("failed to create SecretManager");
        manager
            .unlock("round-trip-password")
            .expect("unlock failed");

        manager
            .set_secret(
                "db-password",
                "s3cr3t-value-with-unicode-\u{1F600}",
                Some("integration secret".to_string()),
            )
            .expect("set_secret failed");

        // The encrypted file must contain at least the GCM tag (16 bytes) more
        // than the empty payload and must not contain the plaintext.
        let secret_path = dir.path().join("db-password.secret");
        let raw = std::fs::read(&secret_path).expect("failed to read secret file");
        assert!(
            raw.len() >= 16,
            "ciphertext must include the 16-byte GCM tag"
        );
        assert!(
            !raw.windows(7).any(|w| w == b"s3cr3t-"),
            "plaintext must not appear in the encrypted file"
        );

        // Drop the in-memory cache to force a real decrypt-from-disk on read.
        manager.cache.clear();
        let value = manager
            .get_secret("db-password")
            .expect("get_secret failed");
        assert_eq!(value, "s3cr3t-value-with-unicode-\u{1F600}");
    }

    #[test]
    fn test_decrypt_with_wrong_password_fails() {
        // A secret written under one password must fail to decrypt under
        // another (GCM tag verification rejects the tampered/derived key).
        let dir = tempdir().expect("failed to create temp dir");

        {
            let mut manager = SecretManager::with_dir(dir.path().to_path_buf())
                .expect("failed to create SecretManager");
            manager.unlock("first-password").expect("unlock failed");
            manager
                .set_secret("token", "abc123", None)
                .expect("set_secret failed");
        }

        let mut manager = SecretManager::with_dir(dir.path().to_path_buf())
            .expect("failed to create SecretManager");
        manager.unlock("wrong-password").expect("unlock failed");
        let result = manager.get_secret("token");
        assert!(
            result.is_err(),
            "decryption with the wrong password must fail"
        );
    }

    #[test]
    fn test_environment_secret() {
        // Note: This test uses unsafe env::set_var/remove_var because it specifically
        // tests the environment variable fallback behavior. This is safe in test mode
        // as cargo test runs tests in separate threads with proper synchronization.
        // SAFETY: Tests are run with --test-threads=1 by default or isolated by cargo.
        unsafe { std::env::set_var("OXIRS_SECRET_API_KEY", "secret-api-key") };

        let dir = tempdir().expect("failed to create temp dir");
        let mut manager = SecretManager::with_dir(dir.path().to_path_buf())
            .expect("failed to create SecretManager");
        let value = manager.get_secret("api-key").expect("failed to get secret");
        assert_eq!(value, "secret-api-key");

        // SAFETY: Cleaning up test environment
        unsafe { std::env::remove_var("OXIRS_SECRET_API_KEY") };
    }

    // ------------------------------------------------------------------
    // System keyring tests
    // ------------------------------------------------------------------

    /// Without the `system-keyring` feature the functions must return a
    /// descriptive error mentioning the flag to enable.
    #[cfg(not(feature = "system-keyring"))]
    #[test]
    fn test_keyring_store_requires_feature_flag() {
        let result = keyring::store_in_keyring("oxirs-test", "test-key", "test-value");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("system-keyring"),
            "error should mention the feature flag, got: {msg}"
        );
    }

    #[cfg(not(feature = "system-keyring"))]
    #[test]
    fn test_keyring_get_requires_feature_flag() {
        let result = keyring::get_from_keyring("oxirs-test", "test-key");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("system-keyring"),
            "error should mention the feature flag, got: {msg}"
        );
    }

    /// With the `system-keyring` feature a round-trip store → retrieve must
    /// succeed. The test deletes the credential afterwards to leave the OS
    /// keyring clean.
    #[cfg(feature = "system-keyring")]
    #[test]
    fn test_keyring_round_trip() {
        let service = "oxirs-test-service";
        let key = "oxirs-test-round-trip-key";
        let value = "super-secret-value-42";

        keyring::store_in_keyring(service, key, value).expect("keyring store failed");

        let retrieved = keyring::get_from_keyring(service, key).expect("keyring retrieve failed");
        assert_eq!(retrieved, value, "retrieved value must equal stored value");

        // Clean up: delete the test credential from the OS keyring
        if let Ok(entry) = keyring_core::Entry::new(service, key) {
            let _ = entry.delete_credential();
        }
    }
}