prodex 0.9.0

OpenAI profile pooling and safe auto-rotate for Codex CLI and Claude Code
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
#![allow(dead_code)]

use std::error::Error as StdError;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SecretLocation {
    File(PathBuf),
    Keyring { service: String, account: String },
}

impl SecretLocation {
    pub fn file(path: impl Into<PathBuf>) -> Self {
        Self::File(path.into())
    }

    pub fn auth_json(codex_home: impl AsRef<Path>) -> Self {
        Self::File(codex_home.as_ref().join("auth.json"))
    }

    pub fn keyring(service: impl Into<String>, account: impl Into<String>) -> Self {
        Self::Keyring {
            service: service.into(),
            account: account.into(),
        }
    }

    pub fn is_file(&self) -> bool {
        matches!(self, Self::File(_))
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SecretValue {
    Text(String),
    Bytes(Vec<u8>),
}

impl SecretValue {
    pub fn text(value: impl Into<String>) -> Self {
        Self::Text(value.into())
    }

    pub fn bytes(value: impl Into<Vec<u8>>) -> Self {
        Self::Bytes(value.into())
    }

    pub fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(value) => Some(value.as_str()),
            Self::Bytes(_) => None,
        }
    }

    pub fn into_bytes(self) -> Vec<u8> {
        match self {
            Self::Text(value) => value.into_bytes(),
            Self::Bytes(value) => value,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SecretError {
    UnsupportedLocation { location: String },
    InvalidLocation { reason: String },
    Io { path: PathBuf, reason: String },
}

impl SecretError {
    pub fn unsupported(location: impl Into<String>) -> Self {
        Self::UnsupportedLocation {
            location: location.into(),
        }
    }

    pub fn invalid_location(reason: impl Into<String>) -> Self {
        Self::InvalidLocation {
            reason: reason.into(),
        }
    }

    pub fn io(path: impl Into<PathBuf>, error: io::Error) -> Self {
        Self::Io {
            path: path.into(),
            reason: error.to_string(),
        }
    }
}

impl fmt::Display for SecretError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedLocation { location } => {
                write!(f, "unsupported secret location: {location}")
            }
            Self::InvalidLocation { reason } => write!(f, "invalid secret location: {reason}"),
            Self::Io { path, reason } => write!(f, "I/O error for {}: {reason}", path.display()),
        }
    }
}

impl StdError for SecretError {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretBackendKind {
    File,
    Keyring,
}

impl SecretBackendKind {
    pub fn file() -> Self {
        Self::File
    }

    pub fn keyring() -> Self {
        Self::Keyring
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::File => "file",
            Self::Keyring => "keyring",
        }
    }
}

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

impl std::str::FromStr for SecretBackendKind {
    type Err = SecretError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.trim().to_ascii_lowercase().as_str() {
            "file" => Ok(Self::File),
            "keyring" => Ok(Self::Keyring),
            _ => Err(SecretError::invalid_location(format!(
                "unknown secret backend '{value}'"
            ))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretRevision {
    size_bytes: u64,
    modified_at: Option<SystemTime>,
}

impl SecretRevision {
    pub fn new(size_bytes: u64, modified_at: Option<SystemTime>) -> Self {
        Self {
            size_bytes,
            modified_at,
        }
    }

    pub fn from_metadata(metadata: &fs::Metadata) -> Self {
        Self::new(metadata.len(), metadata.modified().ok())
    }

    pub fn size_bytes(&self) -> u64 {
        self.size_bytes
    }

    pub fn modified_at(&self) -> Option<SystemTime> {
        self.modified_at
    }
}

impl fmt::Display for SecretRevision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.modified_at.as_ref() {
            Some(modified_at) => write!(
                f,
                "size_bytes={} modified_at={modified_at:?}",
                self.size_bytes
            ),
            None => write!(f, "size_bytes={} modified_at=none", self.size_bytes),
        }
    }
}

pub trait SecretBackend {
    fn read(&self, location: &SecretLocation) -> Result<Option<SecretValue>, SecretError>;
    fn write(&self, location: &SecretLocation, value: SecretValue) -> Result<(), SecretError>;
    fn delete(&self, location: &SecretLocation) -> Result<(), SecretError>;
}

pub trait SecretRevisionBackend: SecretBackend {
    fn probe_revision(
        &self,
        location: &SecretLocation,
    ) -> Result<Option<SecretRevision>, SecretError>;
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct FileSecretBackend;

impl FileSecretBackend {
    pub fn new() -> Self {
        Self
    }
}

impl SecretBackend for FileSecretBackend {
    fn read(&self, location: &SecretLocation) -> Result<Option<SecretValue>, SecretError> {
        let path = match location {
            SecretLocation::File(path) => path,
            SecretLocation::Keyring { service, account } => {
                return Err(SecretError::unsupported(format!(
                    "keyring://{service}/{account}"
                )));
            }
        };

        let bytes = match fs::read(path) {
            Ok(bytes) => bytes,
            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(err) => return Err(SecretError::io(path, err)),
        };

        match String::from_utf8(bytes.clone()) {
            Ok(text) => Ok(Some(SecretValue::Text(text))),
            Err(_) => Ok(Some(SecretValue::Bytes(bytes))),
        }
    }

    fn write(&self, location: &SecretLocation, value: SecretValue) -> Result<(), SecretError> {
        let path = match location {
            SecretLocation::File(path) => path,
            SecretLocation::Keyring { service, account } => {
                return Err(SecretError::unsupported(format!(
                    "keyring://{service}/{account}"
                )));
            }
        };

        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|err| SecretError::io(parent, err))?;
        }

        let bytes = value.into_bytes();
        let temp_path = unique_temp_path(path);
        fs::write(&temp_path, bytes).map_err(|err| SecretError::io(&temp_path, err))?;
        replace_file(&temp_path, path)?;
        secure_file(path)?;
        Ok(())
    }

    fn delete(&self, location: &SecretLocation) -> Result<(), SecretError> {
        let path = match location {
            SecretLocation::File(path) => path,
            SecretLocation::Keyring { service, account } => {
                return Err(SecretError::unsupported(format!(
                    "keyring://{service}/{account}"
                )));
            }
        };

        match fs::remove_file(path) {
            Ok(()) => Ok(()),
            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
            Err(err) => Err(SecretError::io(path, err)),
        }
    }
}

impl SecretRevisionBackend for FileSecretBackend {
    fn probe_revision(
        &self,
        location: &SecretLocation,
    ) -> Result<Option<SecretRevision>, SecretError> {
        let path = match location {
            SecretLocation::File(path) => path,
            SecretLocation::Keyring { service, account } => {
                return Err(SecretError::unsupported(format!(
                    "keyring://{service}/{account}"
                )));
            }
        };

        match fs::metadata(path) {
            Ok(metadata) => Ok(Some(SecretRevision::from_metadata(&metadata))),
            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(err) => Err(SecretError::io(path, err)),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyringSecretBackend {
    service: String,
}

impl KeyringSecretBackend {
    pub fn new(service: impl Into<String>) -> Result<Self, SecretError> {
        let service = service.into();
        if service.trim().is_empty() {
            return Err(SecretError::invalid_location(
                "keyring service name cannot be empty",
            ));
        }
        Ok(Self { service })
    }

    pub fn service(&self) -> &str {
        &self.service
    }
}

impl SecretBackend for KeyringSecretBackend {
    fn read(&self, location: &SecretLocation) -> Result<Option<SecretValue>, SecretError> {
        match location {
            SecretLocation::Keyring { service, account } => {
                if service != &self.service {
                    return Err(SecretError::invalid_location(format!(
                        "expected keyring service '{}' but got '{}'",
                        self.service, service
                    )));
                }
                Err(SecretError::unsupported(format!(
                    "keyring://{service}/{account}"
                )))
            }
            SecretLocation::File(path) => Err(SecretError::unsupported(format!(
                "file://{}",
                path.display()
            ))),
        }
    }

    fn write(&self, location: &SecretLocation, _value: SecretValue) -> Result<(), SecretError> {
        match location {
            SecretLocation::Keyring { service, account } => {
                if service != &self.service {
                    return Err(SecretError::invalid_location(format!(
                        "expected keyring service '{}' but got '{}'",
                        self.service, service
                    )));
                }
                Err(SecretError::unsupported(format!(
                    "keyring://{service}/{account}"
                )))
            }
            SecretLocation::File(path) => Err(SecretError::unsupported(format!(
                "file://{}",
                path.display()
            ))),
        }
    }

    fn delete(&self, location: &SecretLocation) -> Result<(), SecretError> {
        match location {
            SecretLocation::Keyring { service, account } => {
                if service != &self.service {
                    return Err(SecretError::invalid_location(format!(
                        "expected keyring service '{}' but got '{}'",
                        self.service, service
                    )));
                }
                Err(SecretError::unsupported(format!(
                    "keyring://{service}/{account}"
                )))
            }
            SecretLocation::File(path) => Err(SecretError::unsupported(format!(
                "file://{}",
                path.display()
            ))),
        }
    }
}

impl SecretRevisionBackend for KeyringSecretBackend {
    fn probe_revision(
        &self,
        location: &SecretLocation,
    ) -> Result<Option<SecretRevision>, SecretError> {
        match location {
            SecretLocation::Keyring { service, account } => {
                if service != &self.service {
                    return Err(SecretError::invalid_location(format!(
                        "expected keyring service '{}' but got '{}'",
                        self.service, service
                    )));
                }
                Err(SecretError::unsupported(format!(
                    "keyring://{service}/{account}"
                )))
            }
            SecretLocation::File(path) => Err(SecretError::unsupported(format!(
                "file://{}",
                path.display()
            ))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SecretBackendSelection {
    File(FileSecretBackend),
    Keyring(KeyringSecretBackend),
}

impl SecretBackendSelection {
    pub fn file() -> Self {
        Self::File(FileSecretBackend::new())
    }

    pub fn keyring(service: impl Into<String>) -> Result<Self, SecretError> {
        Ok(Self::Keyring(KeyringSecretBackend::new(service)?))
    }

    pub fn from_kind(
        kind: SecretBackendKind,
        keyring_service: Option<String>,
    ) -> Result<Self, SecretError> {
        match kind {
            SecretBackendKind::File => Ok(Self::file()),
            SecretBackendKind::Keyring => match keyring_service {
                Some(service) => Self::keyring(service),
                None => Err(SecretError::invalid_location(
                    "keyring backend requires a service name",
                )),
            },
        }
    }

    pub fn kind(&self) -> SecretBackendKind {
        match self {
            Self::File(_) => SecretBackendKind::File,
            Self::Keyring(_) => SecretBackendKind::Keyring,
        }
    }

    pub fn keyring_service(&self) -> Option<&str> {
        match self {
            Self::File(_) => None,
            Self::Keyring(backend) => Some(backend.service()),
        }
    }

    pub fn into_manager(self) -> SecretManager<Self> {
        SecretManager::new(self)
    }
}

impl Default for SecretBackendSelection {
    fn default() -> Self {
        Self::file()
    }
}

impl SecretBackend for SecretBackendSelection {
    fn read(&self, location: &SecretLocation) -> Result<Option<SecretValue>, SecretError> {
        match self {
            Self::File(backend) => backend.read(location),
            Self::Keyring(backend) => backend.read(location),
        }
    }

    fn write(&self, location: &SecretLocation, value: SecretValue) -> Result<(), SecretError> {
        match self {
            Self::File(backend) => backend.write(location, value),
            Self::Keyring(backend) => backend.write(location, value),
        }
    }

    fn delete(&self, location: &SecretLocation) -> Result<(), SecretError> {
        match self {
            Self::File(backend) => backend.delete(location),
            Self::Keyring(backend) => backend.delete(location),
        }
    }
}

impl SecretRevisionBackend for SecretBackendSelection {
    fn probe_revision(
        &self,
        location: &SecretLocation,
    ) -> Result<Option<SecretRevision>, SecretError> {
        match self {
            Self::File(backend) => backend.probe_revision(location),
            Self::Keyring(backend) => backend.probe_revision(location),
        }
    }
}

#[derive(Debug, Clone)]
pub struct SecretManager<B> {
    backend: B,
}

impl<B> SecretManager<B> {
    pub fn new(backend: B) -> Self {
        Self { backend }
    }

    pub fn backend(&self) -> &B {
        &self.backend
    }
}

impl<B: SecretBackend> SecretManager<B> {
    pub fn read(&self, location: &SecretLocation) -> Result<Option<SecretValue>, SecretError> {
        self.backend.read(location)
    }

    pub fn read_text(&self, location: &SecretLocation) -> Result<Option<String>, SecretError> {
        match self.backend.read(location)? {
            Some(SecretValue::Text(text)) => Ok(Some(text)),
            Some(SecretValue::Bytes(bytes)) => String::from_utf8(bytes)
                .map(Some)
                .map_err(|_| SecretError::invalid_location("secret payload is not valid UTF-8")),
            None => Ok(None),
        }
    }

    pub fn write(&self, location: &SecretLocation, value: SecretValue) -> Result<(), SecretError> {
        self.backend.write(location, value)
    }

    pub fn write_text(
        &self,
        location: &SecretLocation,
        value: impl Into<String>,
    ) -> Result<(), SecretError> {
        self.backend
            .write(location, SecretValue::Text(value.into()))
    }

    pub fn delete(&self, location: &SecretLocation) -> Result<(), SecretError> {
        self.backend.delete(location)
    }
}

impl<B: SecretRevisionBackend> SecretManager<B> {
    pub fn probe_revision(
        &self,
        location: &SecretLocation,
    ) -> Result<Option<SecretRevision>, SecretError> {
        self.backend.probe_revision(location)
    }
}

pub fn auth_json_path(codex_home: impl AsRef<Path>) -> PathBuf {
    codex_home.as_ref().join("auth.json")
}

pub fn auth_json_location(codex_home: impl AsRef<Path>) -> SecretLocation {
    SecretLocation::File(auth_json_path(codex_home))
}

pub fn auth_json_location_for_backend(
    codex_home: impl AsRef<Path>,
    selection: &SecretBackendSelection,
) -> SecretLocation {
    match selection {
        SecretBackendSelection::File(_) => auth_json_location(codex_home),
        SecretBackendSelection::Keyring(backend) => SecretLocation::keyring(
            backend.service().to_string(),
            auth_json_keyring_account(codex_home),
        ),
    }
}

pub fn auth_json_keyring_account(codex_home: impl AsRef<Path>) -> String {
    format!("auth-json:{}", codex_home.as_ref().display())
}

pub fn describe_secret_location(location: &SecretLocation) -> String {
    match location {
        SecretLocation::File(path) => path.display().to_string(),
        SecretLocation::Keyring { service, account } => format!("keyring://{service}/{account}"),
    }
}

fn unique_temp_path(path: &Path) -> PathBuf {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let pid = std::process::id();
    let temp_name = format!(
        "{}.{}.{}.tmp",
        path.file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("secret"),
        pid,
        nanos
    );
    path.with_file_name(temp_name)
}

fn replace_file(temp_path: &Path, path: &Path) -> Result<(), SecretError> {
    match fs::rename(temp_path, path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
            fs::remove_file(path).map_err(|err| SecretError::io(path, err))?;
            fs::rename(temp_path, path).map_err(|err| SecretError::io(path, err))
        }
        Err(err) => Err(SecretError::io(path, err)),
    }
}

fn secure_file(path: &Path) -> Result<(), SecretError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let permissions = fs::Permissions::from_mode(0o600);
        fs::set_permissions(path, permissions).map_err(|err| SecretError::io(path, err))?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_dir(name: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!(
            "prodex-secret-store-{name}-{}-{nanos:x}",
            std::process::id()
        ));
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn auth_json_location_maps_to_expected_path() {
        let home = PathBuf::from("/tmp/codex-home");
        assert_eq!(auth_json_path(&home), home.join("auth.json"));
        assert_eq!(
            auth_json_location(&home),
            SecretLocation::File(home.join("auth.json"))
        );
    }

    #[test]
    fn file_backend_round_trips_text_values() {
        let root = temp_dir("text");
        let path = root.join("nested/auth.json");
        let store = SecretManager::new(FileSecretBackend::new());
        let location = SecretLocation::file(&path);

        store
            .write_text(&location, "{\"access_token\":\"abc\"}")
            .unwrap();

        assert_eq!(
            store.read_text(&location).unwrap().as_deref(),
            Some("{\"access_token\":\"abc\"}")
        );
        assert_eq!(
            store.read(&location).unwrap(),
            Some(SecretValue::Text("{\"access_token\":\"abc\"}".to_string()))
        );

        store.delete(&location).unwrap();
        assert_eq!(store.read(&location).unwrap(), None);

        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn file_backend_preserves_binary_values() {
        let root = temp_dir("binary");
        let path = root.join("secret.bin");
        let store = SecretManager::new(FileSecretBackend::new());
        let location = SecretLocation::file(&path);
        let payload = SecretValue::bytes(vec![0xff, 0x00, 0x41]);

        store.write(&location, payload.clone()).unwrap();

        assert_eq!(store.read(&location).unwrap(), Some(payload));
        assert!(store.read_text(&location).is_err());

        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn file_backend_rejects_keyring_locations() {
        let store = SecretManager::new(FileSecretBackend::new());
        let location = SecretLocation::keyring("prodex", "auth");
        let err = store.write_text(&location, "value").unwrap_err();
        assert!(matches!(err, SecretError::UnsupportedLocation { .. }));
    }

    #[test]
    fn keyring_backend_validates_service_name() {
        let backend = KeyringSecretBackend::new("prodex").unwrap();
        assert_eq!(backend.service(), "prodex");

        let err = KeyringSecretBackend::new("   ").unwrap_err();
        assert!(matches!(err, SecretError::InvalidLocation { .. }));
    }

    #[test]
    fn selectable_backend_file_round_trips_text_values() {
        let root = temp_dir("selection-text");
        let path = root.join("nested/auth.json");
        let store = SecretBackendSelection::file().into_manager();
        let location = SecretLocation::file(&path);

        store
            .write_text(&location, "{\"access_token\":\"abc\"}")
            .unwrap();

        assert_eq!(
            store.read_text(&location).unwrap().as_deref(),
            Some("{\"access_token\":\"abc\"}")
        );
        assert_eq!(
            store.read(&location).unwrap(),
            Some(SecretValue::Text("{\"access_token\":\"abc\"}".to_string()))
        );

        store.delete(&location).unwrap();
        assert_eq!(store.read(&location).unwrap(), None);

        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn selectable_backend_from_kind_requires_keyring_service() {
        assert_eq!(
            SecretBackendSelection::from_kind(SecretBackendKind::File, None)
                .unwrap()
                .kind(),
            SecretBackendKind::File
        );

        let err = SecretBackendSelection::from_kind(SecretBackendKind::Keyring, None).unwrap_err();
        assert!(matches!(err, SecretError::InvalidLocation { .. }));
    }

    #[test]
    fn file_backend_probe_revision_tracks_metadata() {
        let root = temp_dir("revision");
        let path = root.join("secret.bin");
        let store = SecretBackendSelection::file().into_manager();
        let location = SecretLocation::file(&path);

        store
            .write(&location, SecretValue::bytes(vec![0xff, 0x00, 0x41]))
            .unwrap();

        let metadata = fs::metadata(&path).unwrap();
        let revision = store.probe_revision(&location).unwrap();
        assert_eq!(revision, Some(SecretRevision::from_metadata(&metadata)));
        assert_eq!(revision.as_ref().map(SecretRevision::size_bytes), Some(3));
        assert_eq!(
            revision.as_ref().and_then(SecretRevision::modified_at),
            metadata.modified().ok()
        );

        store
            .write(&location, SecretValue::bytes(vec![0xff, 0x00, 0x41, 0x42]))
            .unwrap();
        let updated_revision = store.probe_revision(&location).unwrap();
        assert_ne!(revision, updated_revision);

        store.delete(&location).unwrap();
        assert_eq!(store.probe_revision(&location).unwrap(), None);

        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn auth_json_location_for_keyring_backend_uses_deterministic_account() {
        let selection = SecretBackendSelection::keyring("prodex").unwrap();
        let location = auth_json_location_for_backend("/tmp/codex-home", &selection);
        assert_eq!(
            location,
            SecretLocation::Keyring {
                service: "prodex".to_string(),
                account: "auth-json:/tmp/codex-home".to_string(),
            }
        );
        assert_eq!(
            describe_secret_location(&location),
            "keyring://prodex/auth-json:/tmp/codex-home"
        );
    }
}