nika-core 0.58.1

Lightweight AST and analysis core for Nika workflows
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
1072
//! NikaVault — encrypted local file store for API secrets.
//!
//! Uses XChaCha20Poly1305 (AEAD) for encryption with Argon2i KDF for key derivation.
//! The key is derived from a machine fingerprint (machine-id + username) or an explicit
//! passphrase set via `NIKA_VAULT_PASSPHRASE` (for CI/Docker).
//!
//! Layout:
//! - `<secrets_dir>/vault.enc` — encrypted JSON payload
//! - `<secrets_dir>/vault.salt` — 16-byte random salt (plaintext)

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use orion::aead;
use orion::kdf;
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use tracing::debug;

/// Vault-specific error type (lightweight — no nika-engine dependency).
#[derive(Debug, thiserror::Error)]
pub enum VaultError {
    #[error("vault I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("vault crypto error: {0}")]
    Crypto(String),
    #[error("vault JSON error: {0}")]
    Json(#[from] serde_json::Error),
}

/// A single vault entry — either a simple API key string (v1 compat)
/// or a multi-field credential (v2).
///
/// Uses `#[serde(untagged)]` so a plain JSON string deserializes as `Key`
/// and a JSON object deserializes as `Credential`. This gives seamless
/// v1 → v2 migration: existing vault files with string values just work.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(untagged)]
pub enum VaultEntry {
    /// Simple API key (v1 backward compat)
    Key(String),
    /// Multi-field credential (v2)
    Credential {
        /// Named fields (e.g., "api_key", "secret", "org_id")
        fields: BTreeMap<String, String>,
        /// Optional service URL (e.g., `https://api.stripe.com`)
        #[serde(skip_serializing_if = "Option::is_none")]
        service_url: Option<String>,
        /// Optional category (e.g., "payment", "llm", "storage")
        #[serde(skip_serializing_if = "Option::is_none")]
        category: Option<String>,
        /// ISO 8601 timestamp when the credential was stored
        #[serde(skip_serializing_if = "Option::is_none")]
        created_at: Option<String>,
        /// ISO 8601 timestamp when the credential expires
        #[serde(skip_serializing_if = "Option::is_none")]
        expires_at: Option<String>,
    },
}

impl VaultEntry {
    /// Get the primary key value (for backward compat).
    ///
    /// - `Key(s)` → returns `s`
    /// - `Credential { fields, .. }` → returns the first field value (alphabetical)
    fn primary_value(&self) -> Option<&str> {
        match self {
            VaultEntry::Key(s) => Some(s.as_str()),
            VaultEntry::Credential { fields, .. } => fields.values().next().map(|s| s.as_str()),
        }
    }
}

/// Which backend to use for secret storage/retrieval at runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VaultBackend {
    /// Local encrypted vault (default).
    Local,
    /// Doppler CLI-based secret management.
    Doppler,
}

impl VaultBackend {
    /// Select backend from `NIKA_VAULT_BACKEND` env var.
    ///
    /// Returns `Doppler` if `NIKA_VAULT_BACKEND=doppler`, otherwise `Local`.
    pub fn from_env() -> Self {
        match std::env::var("NIKA_VAULT_BACKEND").as_deref() {
            Ok("doppler") => Self::Doppler,
            _ => Self::Local,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// AUDIT LOG
// ═══════════════════════════════════════════════════════════════════════════

/// Audit log entry for vault operations.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct AuditEntry {
    pub timestamp: String,
    pub op: String,
    pub service: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    pub source: String,
}

/// Append-only audit log for credential access tracking.
///
/// Writes JSON lines to `<secrets_dir>/audit.jsonl`.
pub struct VaultAuditLog {
    log_path: PathBuf,
}

impl VaultAuditLog {
    /// Create audit log for the given secrets directory.
    pub fn new(secrets_dir: &Path) -> Self {
        Self {
            log_path: secrets_dir.join("audit.jsonl"),
        }
    }

    /// Log path for inspection in tests.
    pub fn path(&self) -> &Path {
        &self.log_path
    }

    /// Append a single audit entry.
    pub fn log(
        &self,
        op: &str,
        service: &str,
        field: Option<&str>,
        source: &str,
    ) -> Result<(), VaultError> {
        let entry = AuditEntry {
            timestamp: chrono::Utc::now().to_rfc3339(),
            op: op.to_string(),
            service: service.to_string(),
            field: field.map(|f| f.to_string()),
            source: source.to_string(),
        };

        let mut line = serde_json::to_string(&entry)?;
        line.push('\n');

        if let Some(parent) = self.log_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        use std::io::Write;
        let file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.log_path)?;
        let mut writer = std::io::BufWriter::new(file);
        writer.write_all(line.as_bytes())?;
        writer.flush()?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ =
                std::fs::set_permissions(&self.log_path, std::fs::Permissions::from_mode(0o600));
        }

        Ok(())
    }

    /// Read all audit entries from the log.
    pub fn read_all(&self) -> Result<Vec<AuditEntry>, VaultError> {
        if !self.log_path.exists() {
            return Ok(vec![]);
        }
        let content = std::fs::read_to_string(&self.log_path)?;
        let mut entries = Vec::new();
        for line in content.lines() {
            if line.trim().is_empty() {
                continue;
            }
            let entry: AuditEntry = serde_json::from_str(line)?;
            entries.push(entry);
        }
        Ok(entries)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// DOPPLER BACKEND
// ═══════════════════════════════════════════════════════════════════════════

/// Doppler CLI backend — delegates to `doppler secrets get/--json`.
pub struct DopplerBackend;

impl DopplerBackend {
    /// Get a single secret by key via `doppler secrets get KEY --plain`.
    pub fn get(key: &str) -> Result<Option<String>, VaultError> {
        let output = std::process::Command::new("doppler")
            .args(["secrets", "get", key, "--plain"])
            .output();

        match output {
            Ok(out) if out.status.success() => {
                let value = String::from_utf8_lossy(&out.stdout).trim().to_string();
                if value.is_empty() {
                    Ok(None)
                } else {
                    Ok(Some(value))
                }
            }
            Ok(out) => {
                let stderr = String::from_utf8_lossy(&out.stderr);
                tracing::debug!("doppler get failed for {key}: {stderr}");
                Ok(None)
            }
            Err(e) => {
                tracing::debug!("doppler CLI not available: {e}");
                Ok(None)
            }
        }
    }

    /// List all secret keys via `doppler secrets --json`.
    pub fn list() -> Result<Vec<String>, VaultError> {
        let output = std::process::Command::new("doppler")
            .args(["secrets", "--json"])
            .output();

        match output {
            Ok(out) if out.status.success() => {
                let parsed: serde_json::Value =
                    serde_json::from_slice(&out.stdout).map_err(VaultError::Json)?;
                if let serde_json::Value::Object(map) = parsed {
                    Ok(map.keys().cloned().collect())
                } else {
                    Ok(vec![])
                }
            }
            Ok(out) => {
                let stderr = String::from_utf8_lossy(&out.stderr);
                tracing::debug!("doppler list failed: {stderr}");
                Ok(vec![])
            }
            Err(e) => {
                tracing::debug!("doppler CLI not available: {e}");
                Ok(vec![])
            }
        }
    }

    /// Check if the doppler CLI is available on PATH.
    pub fn is_available() -> bool {
        std::process::Command::new("doppler")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }
}

/// Internal plaintext structure stored inside the encrypted vault.
///
/// v1: `secrets` contained `BTreeMap<String, String>` (plain keys).
/// v2: `secrets` contains `BTreeMap<String, VaultEntry>` (keys or credentials).
///
/// Thanks to `VaultEntry`'s `#[serde(untagged)]`, v1 payloads deserialize
/// transparently — each `String` becomes `VaultEntry::Key(s)`.
#[derive(Serialize, Deserialize, Default)]
struct VaultPayload {
    version: u32,
    secrets: BTreeMap<String, VaultEntry>,
}

/// Encrypted local file store for API secrets.
pub struct NikaVault {
    vault_path: PathBuf,
    salt_path: PathBuf,
}

impl NikaVault {
    /// Create a new vault pointed at the given secrets directory.
    ///
    /// Does NOT create files — they are created lazily on first `set()`.
    pub fn new(secrets_dir: &Path) -> Self {
        Self {
            vault_path: secrets_dir.join("vault.enc"),
            salt_path: secrets_dir.join("vault.salt"),
        }
    }

    /// Get a secret by provider name.
    ///
    /// For `VaultEntry::Key(s)`, returns the key string.
    /// For `VaultEntry::Credential { fields, .. }`, returns the first field value.
    pub fn get(&self, provider: &str) -> Result<Option<SecretString>, VaultError> {
        let payload = match self.read_payload()? {
            Some(p) => p,
            None => return Ok(None),
        };
        Ok(payload.secrets.get(provider).and_then(|entry| {
            entry
                .primary_value()
                .map(|s| SecretString::from(s.to_owned()))
        }))
    }

    /// Store a simple secret for a provider (creates or updates).
    pub fn set(&self, provider: &str, secret: &str) -> Result<(), VaultError> {
        let mut payload = self.read_payload()?.unwrap_or_default();
        payload.version = 2;
        payload
            .secrets
            .insert(provider.to_string(), VaultEntry::Key(secret.to_string()));
        self.write_payload(&payload)
    }

    /// Delete a secret. Returns true if it existed.
    pub fn delete(&self, provider: &str) -> Result<bool, VaultError> {
        let mut payload = match self.read_payload()? {
            Some(p) => p,
            None => return Ok(false),
        };
        let existed = payload.secrets.remove(provider).is_some();
        if existed {
            self.write_payload(&payload)?;
        }
        Ok(existed)
    }

    /// List all service/provider names that have stored secrets.
    pub fn list(&self) -> Result<Vec<String>, VaultError> {
        let payload = self.read_payload()?.unwrap_or_default();
        Ok(payload.secrets.keys().cloned().collect())
    }

    // ── Credential API (v2) ─────────────────────────────────────────

    /// Get a specific field from a credential.
    ///
    /// - For `VaultEntry::Key(s)`: the field "key" returns the value; all other
    ///   fields return `None`.
    /// - For `VaultEntry::Credential { fields, .. }`: looks up the field by name.
    pub fn get_credential(
        &self,
        service: &str,
        field: &str,
    ) -> Result<Option<SecretString>, VaultError> {
        let payload = match self.read_payload()? {
            Some(p) => p,
            None => return Ok(None),
        };
        let entry = match payload.secrets.get(service) {
            Some(e) => e,
            None => return Ok(None),
        };
        match entry {
            VaultEntry::Key(s) => {
                // Backward compat: simple keys expose themselves as "key"
                if field == "key" {
                    Ok(Some(SecretString::from(s.clone())))
                } else {
                    Ok(None)
                }
            }
            VaultEntry::Credential { fields, .. } => {
                Ok(fields.get(field).map(|s| SecretString::from(s.clone())))
            }
        }
    }

    /// Store a multi-field credential for a service.
    ///
    /// Replaces any existing entry (Key or Credential) for this service.
    pub fn set_credential(
        &self,
        service: &str,
        fields: BTreeMap<String, String>,
        service_url: Option<String>,
        category: Option<String>,
    ) -> Result<(), VaultError> {
        let mut payload = self.read_payload()?.unwrap_or_default();
        payload.version = 2;
        payload.secrets.insert(
            service.to_string(),
            VaultEntry::Credential {
                fields,
                service_url,
                category,
                created_at: Some(chrono::Utc::now().to_rfc3339()),
                expires_at: None,
            },
        );
        self.write_payload(&payload)
    }

    /// Get the raw `VaultEntry` for a service (for introspection).
    pub fn get_entry(&self, service: &str) -> Result<Option<VaultEntry>, VaultError> {
        let payload = match self.read_payload()? {
            Some(p) => p,
            None => return Ok(None),
        };
        Ok(payload.secrets.get(service).cloned())
    }

    // ── Internal ────────────────────────────────────────────────────────

    fn read_payload(&self) -> Result<Option<VaultPayload>, VaultError> {
        if !self.vault_path.exists() {
            return Ok(None);
        }
        let ciphertext = std::fs::read(&self.vault_path)?;
        let key = self.derive_key()?;
        let plaintext = aead::open(&key, &ciphertext)
            .map_err(|e| VaultError::Crypto(format!("decrypt failed: {e}")))?;
        let payload: VaultPayload = serde_json::from_slice(&plaintext)?;
        Ok(Some(payload))
    }

    fn write_payload(&self, payload: &VaultPayload) -> Result<(), VaultError> {
        if let Some(parent) = self.vault_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let plaintext = serde_json::to_vec(payload)?;
        let key = self.derive_key()?;
        let ciphertext = aead::seal(&key, &plaintext)
            .map_err(|e| VaultError::Crypto(format!("encrypt failed: {e}")))?;

        std::fs::write(&self.vault_path, &ciphertext)?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o600);
            std::fs::set_permissions(&self.vault_path, perms.clone())?;
            if self.salt_path.exists() {
                std::fs::set_permissions(&self.salt_path, perms)?;
            }
        }

        debug!("vault written: {} providers", payload.secrets.len());
        Ok(())
    }

    fn derive_key(&self) -> Result<orion::aead::SecretKey, VaultError> {
        let salt = self.load_or_create_salt()?;
        let fingerprint = machine_fingerprint()?;

        let password = kdf::Password::from_slice(fingerprint.as_bytes())
            .map_err(|e| VaultError::Crypto(format!("KDF password: {e}")))?;
        let kdf_salt = kdf::Salt::from_slice(&salt)
            .map_err(|e| VaultError::Crypto(format!("KDF salt: {e}")))?;

        let derived = kdf::derive_key(&password, &kdf_salt, 3, 1 << 16, 32)
            .map_err(|e| VaultError::Crypto(format!("KDF derive: {e}")))?;

        orion::aead::SecretKey::from_slice(derived.unprotected_as_bytes())
            .map_err(|e| VaultError::Crypto(format!("AEAD key: {e}")))
    }

    fn load_or_create_salt(&self) -> Result<Vec<u8>, VaultError> {
        if self.salt_path.exists() {
            let salt = std::fs::read(&self.salt_path)?;
            if salt.len() >= 16 {
                return Ok(salt);
            }
            debug!("vault salt too short ({} bytes), regenerating", salt.len());
        }
        if let Some(parent) = self.salt_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut salt = vec![0u8; 16];
        orion::util::secure_rand_bytes(&mut salt)
            .map_err(|e| VaultError::Crypto(format!("CSPRNG: {e}")))?;
        std::fs::write(&self.salt_path, &salt)?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&self.salt_path, std::fs::Permissions::from_mode(0o600))?;
        }

        debug!("vault salt created");
        Ok(salt)
    }
}

fn machine_fingerprint() -> Result<String, VaultError> {
    if let Ok(pass) = std::env::var("NIKA_VAULT_PASSPHRASE") {
        if !pass.is_empty() {
            return Ok(format!("nika-vault-v1:passphrase:{pass}"));
        }
    }
    let machine_id = get_machine_id()?;
    let username = whoami::username();
    Ok(format!("nika-vault-v1:{machine_id}:{username}"))
}

#[cfg(target_os = "linux")]
fn get_machine_id() -> Result<String, VaultError> {
    std::fs::read_to_string("/etc/machine-id")
        .map(|s| s.trim().to_string())
        .map_err(|e| {
            VaultError::Io(std::io::Error::new(
                e.kind(),
                format!("Cannot read /etc/machine-id: {e}. Set NIKA_VAULT_PASSPHRASE."),
            ))
        })
}

#[cfg(target_os = "macos")]
fn get_machine_id() -> Result<String, VaultError> {
    let output = std::process::Command::new("ioreg")
        .args(["-rd1", "-c", "IOPlatformExpertDevice"])
        .output()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines() {
        if line.contains("IOPlatformUUID") {
            if let Some(uuid) = line.split('"').nth(3) {
                return Ok(uuid.to_string());
            }
        }
    }
    Err(VaultError::Crypto("IOPlatformUUID not found".into()))
}

#[cfg(target_os = "windows")]
fn get_machine_id() -> Result<String, VaultError> {
    let output = std::process::Command::new("reg")
        .args([
            "query",
            r"HKLM\SOFTWARE\Microsoft\Cryptography",
            "/v",
            "MachineGuid",
        ])
        .output()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines() {
        if line.contains("MachineGuid") {
            if let Some(guid) = line.split_whitespace().last() {
                return Ok(guid.to_string());
            }
        }
    }
    Err(VaultError::Crypto("MachineGuid not found".into()))
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn get_machine_id() -> Result<String, VaultError> {
    Err(VaultError::Crypto(
        "No machine-id on this platform. Set NIKA_VAULT_PASSPHRASE.".into(),
    ))
}

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

    fn test_vault() -> (TempDir, NikaVault) {
        let dir = TempDir::new().unwrap();
        std::env::set_var("NIKA_VAULT_PASSPHRASE", "test-only");
        let vault = NikaVault::new(dir.path());
        (dir, vault)
    }

    #[test]
    #[serial]
    fn set_and_get() {
        let (_dir, vault) = test_vault();
        vault.set("anthropic", "sk-ant-test").unwrap();
        let s = vault.get("anthropic").unwrap().unwrap();
        assert_eq!(s.expose_secret(), "sk-ant-test");
    }

    #[test]
    #[serial]
    fn get_nonexistent() {
        let (_dir, vault) = test_vault();
        assert!(vault.get("nope").unwrap().is_none());
    }

    #[test]
    #[serial]
    fn overwrite() {
        let (_dir, vault) = test_vault();
        vault.set("k", "old").unwrap();
        vault.set("k", "new").unwrap();
        assert_eq!(vault.get("k").unwrap().unwrap().expose_secret(), "new");
    }

    #[test]
    #[serial]
    fn delete_existing() {
        let (_dir, vault) = test_vault();
        vault.set("x", "val").unwrap();
        assert!(vault.delete("x").unwrap());
        assert!(vault.get("x").unwrap().is_none());
    }

    #[test]
    #[serial]
    fn delete_nonexistent() {
        let (_dir, vault) = test_vault();
        assert!(!vault.delete("nope").unwrap());
    }

    #[test]
    #[serial]
    fn list_providers() {
        let (_dir, vault) = test_vault();
        vault.set("a", "1").unwrap();
        vault.set("b", "2").unwrap();
        let mut list = vault.list().unwrap();
        list.sort();
        assert_eq!(list, vec!["a", "b"]);
    }

    #[test]
    #[serial]
    fn corrupted_file_errors() {
        let (dir, vault) = test_vault();
        vault.set("dummy", "x").unwrap();
        std::fs::write(dir.path().join("vault.enc"), b"garbage").unwrap();
        assert!(vault.get("any").is_err());
    }

    #[test]
    #[serial]
    #[cfg(unix)]
    fn file_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let (dir, vault) = test_vault();
        vault.set("test", "secret").unwrap();
        let perms = std::fs::metadata(dir.path().join("vault.enc"))
            .unwrap()
            .permissions();
        assert_eq!(perms.mode() & 0o777, 0o600);
    }

    #[test]
    #[serial]
    fn multiple_providers_persist() {
        let (_dir, vault) = test_vault();
        vault.set("anthropic", "sk-1").unwrap();
        vault.set("openai", "sk-2").unwrap();
        vault.set("gemini", "sk-3").unwrap();
        assert_eq!(
            vault.get("anthropic").unwrap().unwrap().expose_secret(),
            "sk-1"
        );
        assert_eq!(
            vault.get("openai").unwrap().unwrap().expose_secret(),
            "sk-2"
        );
        assert_eq!(
            vault.get("gemini").unwrap().unwrap().expose_secret(),
            "sk-3"
        );
    }

    // ═══════════════════════════════════════════════════════════════
    // v2: VaultEntry + Credential API
    // ═══════════════════════════════════════════════════════════════

    #[test]
    #[serial]
    fn backward_compat_key_still_works() {
        // v2 must still handle simple Key entries identically to v1
        let (_dir, vault) = test_vault();
        vault.set("anthropic", "sk-ant-test").unwrap();

        // get() returns the key value
        let s = vault.get("anthropic").unwrap().unwrap();
        assert_eq!(s.expose_secret(), "sk-ant-test");

        // get_credential with "key" field returns the value
        let s2 = vault.get_credential("anthropic", "key").unwrap().unwrap();
        assert_eq!(s2.expose_secret(), "sk-ant-test");

        // get_credential with any other field returns None
        assert!(vault
            .get_credential("anthropic", "secret")
            .unwrap()
            .is_none());

        // get_entry returns Key variant
        let entry = vault.get_entry("anthropic").unwrap().unwrap();
        assert!(matches!(entry, VaultEntry::Key(ref s) if s == "sk-ant-test"));
    }

    #[test]
    #[serial]
    fn credential_set_and_get() {
        let (_dir, vault) = test_vault();

        let mut fields = BTreeMap::new();
        fields.insert("api_key".to_string(), "sk_live_123".to_string());
        fields.insert("secret".to_string(), "whsec_456".to_string());
        fields.insert("org_id".to_string(), "org_789".to_string());

        vault
            .set_credential(
                "stripe",
                fields,
                Some("https://api.stripe.com".to_string()),
                Some("payment".to_string()),
            )
            .unwrap();

        // get_credential retrieves individual fields
        let api_key = vault.get_credential("stripe", "api_key").unwrap().unwrap();
        assert_eq!(api_key.expose_secret(), "sk_live_123");

        let secret = vault.get_credential("stripe", "secret").unwrap().unwrap();
        assert_eq!(secret.expose_secret(), "whsec_456");

        let org_id = vault.get_credential("stripe", "org_id").unwrap().unwrap();
        assert_eq!(org_id.expose_secret(), "org_789");

        // Missing field returns None
        assert!(vault
            .get_credential("stripe", "nonexistent")
            .unwrap()
            .is_none());

        // get_entry returns Credential variant with metadata
        let entry = vault.get_entry("stripe").unwrap().unwrap();
        match entry {
            VaultEntry::Credential {
                fields,
                service_url,
                category,
                created_at,
                ..
            } => {
                assert_eq!(fields.len(), 3);
                assert_eq!(service_url.as_deref(), Some("https://api.stripe.com"));
                assert_eq!(category.as_deref(), Some("payment"));
                assert!(created_at.is_some(), "created_at should be auto-set");
            }
            VaultEntry::Key(_) => panic!("Expected Credential, got Key"),
        }
    }

    #[test]
    #[serial]
    fn credential_get_returns_primary_for_simple_get() {
        // get() on a Credential returns the first field value (alphabetical)
        let (_dir, vault) = test_vault();

        let mut fields = BTreeMap::new();
        fields.insert("api_key".to_string(), "sk_live_first".to_string());
        fields.insert("secret".to_string(), "whsec_second".to_string());

        vault.set_credential("stripe", fields, None, None).unwrap();

        // get() returns the first field (alphabetical: "api_key")
        let s = vault.get("stripe").unwrap().unwrap();
        assert_eq!(s.expose_secret(), "sk_live_first");
    }

    #[test]
    #[serial]
    fn credential_list_services() {
        let (_dir, vault) = test_vault();

        // Mix of Key and Credential entries
        vault.set("anthropic", "sk-ant").unwrap();

        let mut fields = BTreeMap::new();
        fields.insert("api_key".to_string(), "sk_live".to_string());
        vault.set_credential("stripe", fields, None, None).unwrap();

        let mut list = vault.list().unwrap();
        list.sort();
        assert_eq!(list, vec!["anthropic", "stripe"]);
    }

    #[test]
    #[serial]
    fn credential_delete() {
        let (_dir, vault) = test_vault();

        let mut fields = BTreeMap::new();
        fields.insert("api_key".to_string(), "sk_live".to_string());
        vault.set_credential("stripe", fields, None, None).unwrap();

        // Credential exists
        assert!(vault.get_credential("stripe", "api_key").unwrap().is_some());

        // Delete it
        assert!(vault.delete("stripe").unwrap());

        // Gone
        assert!(vault.get_credential("stripe", "api_key").unwrap().is_none());
        assert!(vault.get("stripe").unwrap().is_none());

        // Double delete returns false
        assert!(!vault.delete("stripe").unwrap());
    }

    #[test]
    #[serial]
    fn credential_overwrite_key_with_credential() {
        let (_dir, vault) = test_vault();

        // Start with a simple Key
        vault.set("stripe", "old-key").unwrap();
        assert_eq!(
            vault.get("stripe").unwrap().unwrap().expose_secret(),
            "old-key"
        );

        // Overwrite with a Credential
        let mut fields = BTreeMap::new();
        fields.insert("api_key".to_string(), "sk_live_new".to_string());
        vault.set_credential("stripe", fields, None, None).unwrap();

        // Old key is gone; credential fields accessible
        let val = vault.get_credential("stripe", "api_key").unwrap().unwrap();
        assert_eq!(val.expose_secret(), "sk_live_new");
    }

    #[test]
    #[serial]
    fn credential_overwrite_credential_with_key() {
        let (_dir, vault) = test_vault();

        // Start with a Credential
        let mut fields = BTreeMap::new();
        fields.insert("api_key".to_string(), "sk_live".to_string());
        vault.set_credential("stripe", fields, None, None).unwrap();

        // Overwrite with a simple Key
        vault.set("stripe", "simple-key").unwrap();

        // Credential fields gone; simple key accessible
        assert_eq!(
            vault.get("stripe").unwrap().unwrap().expose_secret(),
            "simple-key"
        );
        assert!(vault.get_credential("stripe", "api_key").unwrap().is_none());
    }

    #[test]
    fn vault_entry_serde_roundtrip_key() {
        let entry = VaultEntry::Key("sk-test".to_string());
        let json = serde_json::to_string(&entry).unwrap();
        let deserialized: VaultEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(entry, deserialized);
    }

    #[test]
    fn vault_entry_serde_roundtrip_credential() {
        let mut fields = BTreeMap::new();
        fields.insert("api_key".to_string(), "sk_live".to_string());
        fields.insert("secret".to_string(), "whsec_456".to_string());

        let entry = VaultEntry::Credential {
            fields,
            service_url: Some("https://api.stripe.com".to_string()),
            category: Some("payment".to_string()),
            created_at: Some("2026-03-31T12:00:00Z".to_string()),
            expires_at: None,
        };
        let json = serde_json::to_string(&entry).unwrap();
        let deserialized: VaultEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(entry, deserialized);
    }

    #[test]
    fn vault_entry_deserialize_plain_string_as_key() {
        // Crucial for v1 compat: a bare JSON string becomes VaultEntry::Key
        let deserialized: VaultEntry = serde_json::from_str(r#""sk-ant-test""#).unwrap();
        assert_eq!(deserialized, VaultEntry::Key("sk-ant-test".to_string()));
    }

    #[test]
    #[serial]
    fn credential_nonexistent_service() {
        let (_dir, vault) = test_vault();
        assert!(vault
            .get_credential("nonexistent", "key")
            .unwrap()
            .is_none());
    }

    // ── VaultBackend tests ──────────────────────────────────────────────

    #[test]
    #[serial]
    fn local_backend_is_default() {
        // Ensure env var is unset
        unsafe { std::env::remove_var("NIKA_VAULT_BACKEND") };
        assert_eq!(VaultBackend::from_env(), VaultBackend::Local);
    }

    #[test]
    #[serial]
    fn doppler_backend_selected_from_env() {
        std::env::set_var("NIKA_VAULT_BACKEND", "doppler");
        assert_eq!(VaultBackend::from_env(), VaultBackend::Doppler);
        unsafe { std::env::remove_var("NIKA_VAULT_BACKEND") };
    }

    #[test]
    #[serial]
    fn unknown_backend_defaults_to_local() {
        std::env::set_var("NIKA_VAULT_BACKEND", "unknown-backend");
        assert_eq!(VaultBackend::from_env(), VaultBackend::Local);
        unsafe { std::env::remove_var("NIKA_VAULT_BACKEND") };
    }

    #[test]
    #[serial]
    fn empty_backend_defaults_to_local() {
        std::env::set_var("NIKA_VAULT_BACKEND", "");
        assert_eq!(VaultBackend::from_env(), VaultBackend::Local);
        unsafe { std::env::remove_var("NIKA_VAULT_BACKEND") };
    }

    #[test]
    fn doppler_get_returns_none_when_cli_unavailable() {
        // On most CI/test envs, doppler is not installed, so this tests the fallback
        // If doppler IS installed, this still works — it returns whatever doppler has
        let result = DopplerBackend::get("NONEXISTENT_KEY_12345");
        assert!(result.is_ok(), "get should not error even without doppler");
    }

    #[test]
    fn doppler_list_returns_empty_when_cli_unavailable() {
        // If doppler is not on PATH, should gracefully return empty
        // If it IS installed, returns actual keys (still valid)
        let result = DopplerBackend::list();
        assert!(result.is_ok(), "list should not error even without doppler");
    }

    // ── Audit log tests ───────────────────────────────────────────────

    #[test]
    fn audit_log_writes_and_reads() {
        let dir = TempDir::new().unwrap();
        let audit = VaultAuditLog::new(dir.path());

        audit
            .log("get", "stripe", Some("secret"), "workflow")
            .unwrap();
        audit.log("set", "twilio", Some("sid"), "cli").unwrap();
        audit.log("delete", "old-service", None, "cli").unwrap();

        let entries = audit.read_all().unwrap();
        assert_eq!(entries.len(), 3);

        assert_eq!(entries[0].op, "get");
        assert_eq!(entries[0].service, "stripe");
        assert_eq!(entries[0].field.as_deref(), Some("secret"));
        assert_eq!(entries[0].source, "workflow");

        assert_eq!(entries[1].op, "set");
        assert_eq!(entries[1].service, "twilio");
        assert_eq!(entries[1].field.as_deref(), Some("sid"));

        assert_eq!(entries[2].op, "delete");
        assert_eq!(entries[2].service, "old-service");
        assert!(entries[2].field.is_none());
    }

    #[test]
    fn audit_log_timestamp_is_rfc3339() {
        let dir = TempDir::new().unwrap();
        let audit = VaultAuditLog::new(dir.path());

        audit.log("get", "test", None, "test").unwrap();

        let entries = audit.read_all().unwrap();
        assert_eq!(entries.len(), 1);
        // Verify it parses as RFC 3339
        assert!(
            chrono::DateTime::parse_from_rfc3339(&entries[0].timestamp).is_ok(),
            "timestamp should be valid RFC 3339: {}",
            entries[0].timestamp
        );
    }

    #[test]
    fn audit_log_empty_file() {
        let dir = TempDir::new().unwrap();
        let audit = VaultAuditLog::new(dir.path());

        // No file yet — should return empty vec
        let entries = audit.read_all().unwrap();
        assert!(entries.is_empty());
    }

    #[test]
    fn audit_log_append_mode() {
        let dir = TempDir::new().unwrap();
        let audit = VaultAuditLog::new(dir.path());

        audit.log("get", "s1", None, "src1").unwrap();
        audit.log("set", "s2", None, "src2").unwrap();

        // Create a new audit log instance pointing to the same file
        let audit2 = VaultAuditLog::new(dir.path());
        audit2.log("delete", "s3", None, "src3").unwrap();

        // All 3 entries should be present
        let entries = audit2.read_all().unwrap();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].service, "s1");
        assert_eq!(entries[1].service, "s2");
        assert_eq!(entries[2].service, "s3");
    }

    #[test]
    fn audit_entry_json_roundtrip() {
        let entry = AuditEntry {
            timestamp: "2026-04-01T00:00:00+00:00".to_string(),
            op: "get".to_string(),
            service: "stripe".to_string(),
            field: Some("secret".to_string()),
            source: "workflow".to_string(),
        };

        let json = serde_json::to_string(&entry).unwrap();
        let parsed: AuditEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(entry, parsed);
    }

    #[test]
    fn audit_entry_skips_none_field() {
        let entry = AuditEntry {
            timestamp: "2026-04-01T00:00:00+00:00".to_string(),
            op: "list".to_string(),
            service: "all".to_string(),
            field: None,
            source: "cli".to_string(),
        };

        let json = serde_json::to_string(&entry).unwrap();
        assert!(
            !json.contains("field"),
            "field should be skipped when None: {json}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn audit_log_file_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let dir = TempDir::new().unwrap();
        let audit = VaultAuditLog::new(dir.path());

        audit.log("get", "test", None, "test").unwrap();

        let perms = std::fs::metadata(audit.path()).unwrap().permissions();
        assert_eq!(perms.mode() & 0o777, 0o600);
    }

    #[test]
    fn vault_backend_clone_and_debug() {
        let b = VaultBackend::Local;
        let b2 = b.clone();
        assert_eq!(b, b2);
        assert_eq!(format!("{:?}", b), "Local");
        assert_eq!(format!("{:?}", VaultBackend::Doppler), "Doppler");
    }
}