autumn-web 0.9.0

An opinionated, convention-over-configuration web framework for Rust
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
//! Persistence for the ACME account and issued certificates (issue #1608).
//!
//! [`AcmeStore`] is an async trait so later work can back it with a database or
//! a per-tenant store (#1620/#1635). The first implementation, [`FsAcmeStore`],
//! keeps everything under a **per-directory subdirectory** of the cache
//! directory (`{cache_dir}/{directory-label}/`, `0700`) as `0600` files: the
//! ACME account credentials (`account.json`) and, per certificate,
//! `<cert-id>.chain.pem` + `<cert-id>.key.pem`. Namespacing by directory label
//! keeps a staging leaf from being reused after a promotion to production (a
//! browser-untrusted staging cert still has ~90d validity, so an un-namespaced
//! leaf would silently be served for weeks).

use std::io;
use std::path::{Path, PathBuf};

/// A boxed, pinned future returned by [`AcmeStore`] operations, so the trait
/// stays object-safe (`Arc<dyn AcmeStore>`).
pub use crate::custom_domain::StoreFuture;

/// Stable identifier for a certificate, derived from its (sorted) domain set.
///
/// Two configurations requesting the same domains — in any order — map to the
/// same `CertId`, so a stored certificate is reused across restarts and the
/// renewal leader-election key is stable.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CertId(pub String);

impl CertId {
    /// Derive the id from a domain set (order-independent).
    #[must_use]
    pub fn from_domains(domains: &[String]) -> Self {
        use sha2::{Digest as _, Sha256};
        let mut sorted: Vec<&str> = domains.iter().map(String::as_str).collect();
        sorted.sort_unstable();
        sorted.dedup();
        let mut hasher = Sha256::new();
        for domain in sorted {
            hasher.update(domain.as_bytes());
            hasher.update(b"\0");
        }
        let digest = hasher.finalize();
        let mut out = String::with_capacity(32);
        for byte in &digest[..16] {
            use std::fmt::Write as _;
            let _ = write!(out, "{byte:02x}");
        }
        Self(out)
    }

    /// The id as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A stored certificate: the PEM chain (leaf first) and its private key PEM.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoredCert {
    /// PEM certificate chain, leaf first.
    pub chain_pem: String,
    /// PEM private key matching the leaf.
    pub key_pem: String,
}

/// Persistence contract for ACME material.
///
/// Implementations must persist the account credentials and each issued
/// certificate durably enough to survive a restart, so a reboot does not
/// re-register or re-order (which would burn ACME rate limits).
pub trait AcmeStore: Send + Sync {
    /// Load the persisted ACME account credentials, if any.
    fn load_account(&self) -> StoreFuture<'_, io::Result<Option<Vec<u8>>>>;

    /// Persist the ACME account credentials.
    fn save_account<'a>(&'a self, data: &'a [u8]) -> StoreFuture<'a, io::Result<()>>;

    /// Load the stored certificate for `id`, if any.
    fn load_cert<'a>(&'a self, id: &'a CertId) -> StoreFuture<'a, io::Result<Option<StoredCert>>>;

    /// Persist the certificate for `id`.
    fn save_cert<'a>(
        &'a self,
        id: &'a CertId,
        cert: &'a StoredCert,
    ) -> StoreFuture<'a, io::Result<()>>;

    /// Delete the certificate for `id`. Deleting an absent one succeeds.
    ///
    /// Offboarding a tenant custom domain (#1635) deletes its certificate here
    /// rather than leaving it on disk forever.
    ///
    /// Defaulted to a no-op so an existing store keeps compiling. A store that
    /// does not override it retains offboarded certificates; override it if
    /// that matters for your deployment.
    fn delete_cert<'a>(&'a self, _id: &'a CertId) -> StoreFuture<'a, io::Result<()>> {
        Box::pin(async { Ok(()) })
    }
}

/// Filesystem-backed [`AcmeStore`] rooted at a cache directory.
///
/// Both the account file and the certificate files live under a per-directory
/// subdirectory (`{dir}/{directory_label}/`) so distinct ACME directories
/// (staging vs production vs a custom CA) never share an account **or a
/// certificate** — promoting `directory = "production"` must not reuse a
/// leftover, browser-untrusted staging leaf. All writes are `0600` on Unix
/// (owner-only) inside a `0700` subdirectory, mirroring the owner-only
/// discipline the unix socket path uses — the account key and certificate
/// private key are secrets.
#[derive(Debug, Clone)]
pub struct FsAcmeStore {
    dir: PathBuf,
    directory_label: String,
}

impl FsAcmeStore {
    /// Create a store rooted at `dir`, namespaced by `directory_label` (see
    /// [`crate::acme::directory_label`]).
    #[must_use]
    pub fn new(dir: impl Into<PathBuf>, directory_label: impl Into<String>) -> Self {
        Self {
            dir: dir.into(),
            directory_label: directory_label.into(),
        }
    }

    /// The per-directory subdirectory holding this store's account + certs
    /// (`{dir}/{directory_label}/`).
    fn cert_dir(&self) -> PathBuf {
        self.dir.join(&self.directory_label)
    }

    fn account_path(&self) -> PathBuf {
        self.cert_dir().join("account.json")
    }

    /// The on-disk path of the certificate chain PEM for `id`.
    fn chain_path(&self, id: &CertId) -> PathBuf {
        self.cert_dir().join(format!("{}.chain.pem", id.as_str()))
    }

    /// The on-disk path of the private key PEM for `id`.
    fn key_path(&self, id: &CertId) -> PathBuf {
        self.cert_dir().join(format!("{}.key.pem", id.as_str()))
    }

    /// The stored chain+key pair for `domains`, if both paths are present.
    ///
    /// Mirrors [`AcmeStore::load_cert`]'s treatment of a partial pair as
    /// absent, but works purely off the filesystem (no read/parse), so a
    /// caller that only needs the paths — like `autumn doctor`'s offline
    /// certificate scan — can locate them without re-deriving this store's
    /// on-disk layout independently (issue #1864).
    ///
    /// Deliberately checks `exists()`, not "is a regular file": a path
    /// occupied by a directory (or another non-regular node) is a genuinely
    /// broken cache, not an absent one, and the caller's own read (e.g.
    /// `tls::inspect_leaf`, or this store's `load_cert`) is what surfaces
    /// that as an error — same as it always has for a present-but-corrupt
    /// file. Reporting `None` (→ "not provisioned yet", benign) for that case
    /// would let `autumn doctor --strict` bless a cache that will fail to
    /// load at boot.
    #[must_use]
    pub fn find_cert_for_domains(&self, domains: &[String]) -> Option<(PathBuf, PathBuf)> {
        let id = CertId::from_domains(domains);
        let chain = self.chain_path(&id);
        let key = self.key_path(&id);
        if chain.exists() && key.exists() {
            Some((chain, key))
        } else {
            None
        }
    }

    /// Enumerate every complete (chain+key) certificate pair currently stored
    /// under this store's directory, alongside its [`CertId`] and on-disk
    /// paths. A partial pair (one file present, its sibling missing — e.g. a
    /// torn write interrupted mid-publish) is skipped rather than reported,
    /// mirroring [`AcmeStore::load_cert`]'s treatment of a partial pair as
    /// absent.
    ///
    /// Returns an empty list (not an error) when the store's directory does
    /// not exist yet — a benign first-run state — so callers do not need to
    /// special-case "never provisioned" from "provisioned, nothing stored".
    ///
    /// # Errors
    ///
    /// Returns an error if the store's directory exists but cannot be read
    /// (e.g. a permissions problem).
    pub fn list_certs(&self) -> io::Result<Vec<(CertId, PathBuf, PathBuf)>> {
        let dir = self.cert_dir();
        let entries = match std::fs::read_dir(&dir) {
            Ok(entries) => entries,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(e) => return Err(e),
        };

        let mut ids = std::collections::BTreeSet::new();
        for entry in entries {
            let name = entry?.file_name();
            if let Some(id) = name.to_string_lossy().strip_suffix(".chain.pem") {
                ids.insert(id.to_owned());
            }
        }

        Ok(ids
            .into_iter()
            .filter_map(|id| {
                let id = CertId(id);
                let chain = self.chain_path(&id);
                let key = self.key_path(&id);
                key.is_file().then_some((id, chain, key))
            })
            .collect())
    }
}

impl AcmeStore for FsAcmeStore {
    fn load_account(&self) -> StoreFuture<'_, io::Result<Option<Vec<u8>>>> {
        let path = self.account_path();
        Box::pin(async move { read_optional(&path).await })
    }

    fn save_account<'a>(&'a self, data: &'a [u8]) -> StoreFuture<'a, io::Result<()>> {
        let dir = self.cert_dir();
        let path = self.account_path();
        let data = data.to_vec();
        Box::pin(async move {
            ensure_dir(&dir).await?;
            write_owner_only(&path, &data).await
        })
    }

    fn load_cert<'a>(&'a self, id: &'a CertId) -> StoreFuture<'a, io::Result<Option<StoredCert>>> {
        let chain_path = self.chain_path(id);
        let key_path = self.key_path(id);
        Box::pin(async move {
            let (Some(chain), Some(key)) = (
                read_optional(&chain_path).await?,
                read_optional(&key_path).await?,
            ) else {
                return Ok(None);
            };
            Ok(Some(StoredCert {
                chain_pem: String::from_utf8(chain)
                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
                key_pem: String::from_utf8(key)
                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
            }))
        })
    }

    fn save_cert<'a>(
        &'a self,
        id: &'a CertId,
        cert: &'a StoredCert,
    ) -> StoreFuture<'a, io::Result<()>> {
        let dir = self.cert_dir();
        let chain_path = self.chain_path(id);
        let key_path = self.key_path(id);
        let chain = cert.chain_pem.clone().into_bytes();
        let key = cert.key_pem.clone().into_bytes();
        Box::pin(async move {
            ensure_dir(&dir).await?;
            // Publish the pair as atomically as two files allow: STAGE both temp
            // files fully (write + flush) BEFORE renaming EITHER into place, so a
            // crash can only tear the pair during the two back-to-back rename
            // syscalls rather than across a full write+flush of the key. Any
            // residual torn state (a new chain with the old/mismatched key, or
            // vice-versa) is still caught at load time by the renewal decision's
            // pair validation, which treats a non-loadable pair as absent.
            //
            // Each staged handle (`crate::fs_atomic::StagedFile`) removes its
            // own temp file on drop unless `publish_staged` consumes it, so an
            // early return here — staging the key fails, publishing the chain
            // fails, or this whole future is cancelled — cannot leak a
            // partial-secret temp file; no manual cleanup needed.
            let chain_tmp = stage_owner_only(&chain_path, &chain).await?;
            let key_tmp = stage_owner_only(&key_path, &key).await?;
            publish_staged(chain_tmp, &chain_path).await?;
            publish_staged(key_tmp, &key_path).await
        })
    }

    fn delete_cert<'a>(&'a self, id: &'a CertId) -> StoreFuture<'a, io::Result<()>> {
        let chain_path = self.chain_path(id);
        let key_path = self.key_path(id);
        Box::pin(async move {
            // Remove the key first: a crash between the two leaves a chain with
            // no key, which every loader already treats as absent — the reverse
            // would leave a usable private key for a domain no longer served.
            remove_optional(&key_path).await?;
            remove_optional(&chain_path).await
        })
    }
}

/// Remove a file, treating "already gone" as success.
async fn remove_optional(path: &Path) -> io::Result<()> {
    match tokio::fs::remove_file(path).await {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e),
    }
}

/// Read a file, returning `Ok(None)` when it does not exist.
async fn read_optional(path: &Path) -> io::Result<Option<Vec<u8>>> {
    match tokio::fs::read(path).await {
        Ok(bytes) => Ok(Some(bytes)),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e),
    }
}

/// Create `dir` (and parents), owner-only on Unix.
///
/// Delegates to the shared [`crate::fs_atomic`] helper (issue #1864) on
/// tokio's blocking thread pool, since the helper's core is synchronous
/// `std::fs`.
async fn ensure_dir(dir: &Path) -> io::Result<()> {
    let dir = dir.to_path_buf();
    blocking(move || crate::fs_atomic::ensure_owner_only_dir(&dir)).await
}

/// Atomically write `data` to `path` with owner-only (`0600`) permissions on
/// Unix, via the shared [`crate::fs_atomic`] helper (issue #1864).
///
/// Stages the data to an unpredictable sibling temp file and then `rename`s
/// it over `path`. `rename` is atomic within a directory, so a crash
/// mid-write can never leave a torn single file for the loader/reload path:
/// `path` is either the old contents or the complete new contents, never a
/// partial write.
async fn write_owner_only(path: &Path, data: &[u8]) -> io::Result<()> {
    let path = path.to_path_buf();
    let data = data.to_vec();
    blocking(move || crate::fs_atomic::write_owner_only(&path, &data)).await
}

/// Stage `data` to an unpredictable owner-only (`0600` on Unix) sibling of
/// `path`, WITHOUT renaming it into place, via the shared [`crate::fs_atomic`]
/// helper (issue #1864).
///
/// Splitting staging from the final [`publish_staged`] rename lets a
/// multi-file publish (the cert chain + its key) stage BOTH files before
/// renaming EITHER, shrinking the window in which a crash could tear the pair
/// down to the two back-to-back rename syscalls.
async fn stage_owner_only(path: &Path, data: &[u8]) -> io::Result<crate::fs_atomic::StagedFile> {
    let path = path.to_path_buf();
    let data = data.to_vec();
    blocking(move || crate::fs_atomic::stage_owner_only(&path, &data)).await
}

/// Atomically publish a staged temp file by renaming it over `path`, via the
/// shared [`crate::fs_atomic`] helper (issue #1864). On error, best-effort
/// clean up the temp file so it does not accumulate.
async fn publish_staged(staged: crate::fs_atomic::StagedFile, path: &Path) -> io::Result<()> {
    let path = path.to_path_buf();
    blocking(move || crate::fs_atomic::publish_staged(staged, &path)).await
}

/// Run a blocking `std::fs` operation on tokio's blocking thread pool.
///
/// Thin alias for [`crate::fs_atomic::blocking`], kept so this module's
/// wrappers read the same as they always have.
async fn blocking<T: Send + 'static>(
    f: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
    crate::fs_atomic::blocking(f).await
}

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

    #[test]
    fn cert_id_is_order_independent_and_deduped() {
        let a = CertId::from_domains(&["b.example.com".into(), "a.example.com".into()]);
        let b = CertId::from_domains(&["a.example.com".into(), "b.example.com".into()]);
        let c = CertId::from_domains(&[
            "a.example.com".into(),
            "b.example.com".into(),
            "a.example.com".into(),
        ]);
        assert_eq!(a, b);
        assert_eq!(a, c);
        assert_eq!(a.as_str().len(), 32);
    }

    #[test]
    fn cert_id_distinct_domain_sets_differ() {
        let a = CertId::from_domains(&["a.example.com".into()]);
        let b = CertId::from_domains(&["b.example.com".into()]);
        assert_ne!(a, b);
    }

    #[tokio::test]
    async fn account_save_load_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path().join("acme"), "staging");
        assert!(store.load_account().await.unwrap().is_none());
        store.save_account(b"creds-json").await.unwrap();
        assert_eq!(
            store.load_account().await.unwrap().as_deref(),
            Some(&b"creds-json"[..])
        );
    }

    #[tokio::test]
    async fn account_is_keyed_per_directory() {
        let dir = tempfile::tempdir().unwrap();
        let staging = FsAcmeStore::new(dir.path(), "staging");
        let production = FsAcmeStore::new(dir.path(), "production");
        staging.save_account(b"staging-creds").await.unwrap();
        // A production store in the same dir must not see the staging account.
        assert!(production.load_account().await.unwrap().is_none());
        assert_eq!(
            staging.load_account().await.unwrap().as_deref(),
            Some(&b"staging-creds"[..])
        );
    }

    #[tokio::test]
    async fn cert_save_load_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "staging");
        let id = CertId::from_domains(&["app.example.com".into()]);
        assert!(store.load_cert(&id).await.unwrap().is_none());
        let cert = StoredCert {
            chain_pem: "CHAIN".into(),
            key_pem: "KEY".into(),
        };
        store.save_cert(&id, &cert).await.unwrap();
        assert_eq!(store.load_cert(&id).await.unwrap(), Some(cert));
    }

    #[tokio::test]
    async fn partial_cert_reads_as_absent() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "staging");
        let id = CertId::from_domains(&["app.example.com".into()]);
        // Only the chain written (no key) → treated as no stored cert.
        let chain_path = store.chain_path(&id);
        tokio::fs::create_dir_all(chain_path.parent().unwrap())
            .await
            .unwrap();
        tokio::fs::write(&chain_path, b"CHAIN").await.unwrap();
        assert!(store.load_cert(&id).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn cert_is_namespaced_per_directory() {
        // Regression: a staging-issued leaf must NOT be served after promoting
        // the same cache dir to production. The cert files are keyed only by the
        // domain-set `CertId`, so before per-directory namespacing a production
        // store would load the leftover (browser-untrusted) staging cert.
        let dir = tempfile::tempdir().unwrap();
        let staging = FsAcmeStore::new(dir.path(), "staging");
        let production = FsAcmeStore::new(dir.path(), "production");
        let id = CertId::from_domains(&["app.example.com".into()]);
        let staging_cert = StoredCert {
            chain_pem: "STAGING-CHAIN".into(),
            key_pem: "STAGING-KEY".into(),
        };
        staging.save_cert(&id, &staging_cert).await.unwrap();

        // Same domain set, but the production store must see nothing.
        assert!(production.load_cert(&id).await.unwrap().is_none());
        // The staging store still finds its own cert.
        assert_eq!(staging.load_cert(&id).await.unwrap(), Some(staging_cert));
    }

    #[tokio::test]
    async fn save_cert_publishes_both_files_without_leftover_temps() {
        // The staged-then-rename publish must leave BOTH files in place and no
        // `.tmp` siblings behind (regression for the atomic-pair-publish change).
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "staging");
        let id = CertId::from_domains(&["app.example.com".into()]);
        store
            .save_cert(
                &id,
                &StoredCert {
                    chain_pem: "CHAIN".into(),
                    key_pem: "KEY".into(),
                },
            )
            .await
            .unwrap();

        assert!(store.chain_path(&id).exists(), "chain must be published");
        assert!(store.key_path(&id).exists(), "key must be published");

        let mut entries = tokio::fs::read_dir(store.cert_dir()).await.unwrap();
        while let Some(entry) = entries.next_entry().await.unwrap() {
            let name = entry.file_name();
            assert!(
                !name.to_string_lossy().ends_with(".tmp"),
                "no staged temp file should linger, found {name:?}"
            );
        }
    }

    #[tokio::test]
    async fn save_cert_cleans_up_the_key_temp_when_chain_publish_fails() {
        // Codex review (#1864): once both files stage under unpredictable
        // per-attempt names, a chain-publish failure must not leak the
        // already-staged key temp file — unlike the old fixed `.tmp` name,
        // a fresh name every attempt means nothing overwrites it later.
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "staging");
        let id = CertId::from_domains(&["app.example.com".into()]);

        // Make the chain's publish (rename) fail: occupy its target path
        // with a non-empty directory, which `rename` refuses to replace.
        let chain_path = store.chain_path(&id);
        tokio::fs::create_dir_all(&chain_path).await.unwrap();
        tokio::fs::write(chain_path.join("occupied"), b"x")
            .await
            .unwrap();

        let result = store
            .save_cert(
                &id,
                &StoredCert {
                    chain_pem: "CHAIN".into(),
                    key_pem: "KEY".into(),
                },
            )
            .await;
        assert!(result.is_err(), "chain publish must fail as arranged");

        let mut entries = tokio::fs::read_dir(store.cert_dir()).await.unwrap();
        while let Some(entry) = entries.next_entry().await.unwrap() {
            let name = entry.file_name();
            assert!(
                !name.to_string_lossy().ends_with(".tmp"),
                "the key's staged temp file must not leak, found {name:?}"
            );
        }
    }

    #[tokio::test]
    async fn find_cert_for_domains_locates_the_configured_pair_and_ignores_others() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "production");
        let configured = vec!["app.example.com".to_owned()];
        let other = vec!["old.example.com".to_owned()];

        store
            .save_cert(
                &CertId::from_domains(&other),
                &StoredCert {
                    chain_pem: "OLD-CHAIN".into(),
                    key_pem: "OLD-KEY".into(),
                },
            )
            .await
            .unwrap();
        assert!(
            store.find_cert_for_domains(&configured).is_none(),
            "a cert for different domains must not be reported as the configured one"
        );

        let id = CertId::from_domains(&configured);
        store
            .save_cert(
                &id,
                &StoredCert {
                    chain_pem: "CHAIN".into(),
                    key_pem: "KEY".into(),
                },
            )
            .await
            .unwrap();
        let (chain, key) = store
            .find_cert_for_domains(&configured)
            .expect("configured pair must be found");
        assert_eq!(chain, store.chain_path(&id));
        assert_eq!(key, store.key_path(&id));
    }

    #[tokio::test]
    async fn find_cert_for_domains_treats_a_partial_pair_as_absent() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "production");
        let id = CertId::from_domains(&["app.example.com".into()]);
        tokio::fs::create_dir_all(store.cert_dir()).await.unwrap();
        tokio::fs::write(store.chain_path(&id), b"CHAIN")
            .await
            .unwrap();
        assert!(
            store
                .find_cert_for_domains(&["app.example.com".to_owned()])
                .is_none()
        );
    }

    // Codex review (#1864): a path occupied by a directory (or any other
    // non-regular node) is a genuinely broken cache, not an absent one — it
    // must be reported as present (`Some`) so the caller's own read attempt
    // surfaces the real error, exactly as it always has for a present but
    // corrupt file. Reporting `None` here would have `autumn doctor` grade a
    // cache that will fail to load at boot as the benign "not configured yet".
    #[tokio::test]
    async fn find_cert_for_domains_reports_an_occupied_directory_as_present() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "production");
        let id = CertId::from_domains(&["app.example.com".into()]);
        tokio::fs::create_dir_all(store.chain_path(&id))
            .await
            .unwrap();
        tokio::fs::write(store.key_path(&id), b"KEY").await.unwrap();

        assert_eq!(
            store.find_cert_for_domains(&["app.example.com".to_owned()]),
            Some((store.chain_path(&id), store.key_path(&id))),
            "an occupied-but-invalid chain path must not read as absent"
        );
    }

    #[tokio::test]
    async fn find_cert_for_domains_is_absent_when_the_store_dir_does_not_exist() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "production");
        assert!(
            store
                .find_cert_for_domains(&["app.example.com".to_owned()])
                .is_none()
        );
    }

    #[tokio::test]
    async fn list_certs_is_empty_when_the_store_dir_does_not_exist_yet() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "production");
        assert_eq!(store.list_certs().unwrap(), Vec::new());
    }

    #[tokio::test]
    async fn list_certs_enumerates_only_complete_pairs() {
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path(), "production");

        let a = CertId::from_domains(&["a.example.com".into()]);
        let b = CertId::from_domains(&["b.example.com".into()]);
        store
            .save_cert(
                &a,
                &StoredCert {
                    chain_pem: "A-CHAIN".into(),
                    key_pem: "A-KEY".into(),
                },
            )
            .await
            .unwrap();
        store
            .save_cert(
                &b,
                &StoredCert {
                    chain_pem: "B-CHAIN".into(),
                    key_pem: "B-KEY".into(),
                },
            )
            .await
            .unwrap();
        // A partial pair alongside the two complete ones must be skipped.
        let partial = CertId::from_domains(&["partial.example.com".into()]);
        tokio::fs::write(store.chain_path(&partial), b"PARTIAL")
            .await
            .unwrap();

        let mut listed = store.list_certs().unwrap();
        listed.sort_by(|x, y| x.0.as_str().cmp(y.0.as_str()));
        let mut expected = [a.clone(), b.clone()];
        expected.sort_by(|x, y| x.as_str().cmp(y.as_str()));

        assert_eq!(listed.len(), 2, "the partial pair must not be listed");
        for ((id, chain, key), expected_id) in listed.iter().zip(expected.iter()) {
            assert_eq!(id, expected_id);
            assert_eq!(*chain, store.chain_path(id));
            assert_eq!(*key, store.key_path(id));
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn written_files_are_owner_only_0600() {
        use std::os::unix::fs::PermissionsExt as _;
        let dir = tempfile::tempdir().unwrap();
        let store = FsAcmeStore::new(dir.path().join("acme"), "staging");
        store.save_account(b"secret").await.unwrap();
        let id = CertId::from_domains(&["app.example.com".into()]);
        store
            .save_cert(
                &id,
                &StoredCert {
                    chain_pem: "CHAIN".into(),
                    key_pem: "KEY".into(),
                },
            )
            .await
            .unwrap();

        for path in [
            store.account_path(),
            store.chain_path(&id),
            store.key_path(&id),
        ] {
            let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
            assert_eq!(
                mode,
                0o600,
                "{} should be 0600, was {mode:o}",
                path.display()
            );
        }

        // The per-directory subdirectory that holds the secrets is 0700.
        let subdir_mode = std::fs::metadata(store.cert_dir())
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(subdir_mode, 0o700, "cert subdir should be 0700");
    }
}