qso-graph-trust 0.1.4

Sign ADIF logs for ARRL's Logbook of The World (LoTW)
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
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 the QSO Graph Trust contributors (see AUTHORS). Part of QSO Graph Trust; see LICENSE.

//! The shared QG Trust folder. Public records live in a bounded, versioned XML file; private
//! PKCS#8 DER stays in a library-owned backend scoped to [`SERVICE`] (or [`TEST_SERVICE`] in tests).
//! Each operation reloads the file while holding its OS lock, so separate library releases and
//! processes cannot lose each other's writes. Unknown versions are refused before any mutation.
//! The file also keeps the LoTW roots the operator has accepted beside the pinned ones
//! ([`Store::trust`], [`Store::trusted_roots`], [`Store::remove_root`]).
//!
//! Applications that sign must install the wiping allocator required by this crate's README.
//! Callers select a [`KeyBackend`]; raw credential access stays inside the library.

mod format;
mod import;
mod keys;
mod listing;
mod part;
mod roots;
mod signed;

pub use roots::{MAX_ROOTS, RootKind, RootSource, TrustedRoot};

pub use signed::{
    DuplicateChoice, MAX_SIGNED_KEY_LEN, MAX_SIGNED_QSOS, MAX_SIGNED_STATION_LEN,
    MAX_SIGNED_STATIONS, PreviouslySigned, SignedLog, SignedQso, SigningPlan, SigningSelection,
    duplicate_key,
};

pub use import::ExpiringCertificate;
pub use listing::{ListedCertificate, Listing};
pub use part::{PartError, RestoreReport};

pub use keys::{KeyStoreError, MAX_KEYS, OrphanDetection, SERVICE, TEST_SERVICE};

use keys::{KeyStore, MemoryKeyStore, OsKeyStore};

use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};

use crate::certificate::Certificate;
use crate::request::GeneratedRequest;
use crate::signing::{KeyError, TqslKey};
use crate::station::StationLocation;
use crate::tbk::BackedUpCertificate;

/// The newest store format this build reads and writes. Version 3 adds the accepted roots; 1 and 2
/// are still read.
pub const VERSION: u32 = 3;
/// The largest store file accepted, before parsing or allocating its contents.
pub const MAX_FILE_LEN: usize = 32 * 1024 * 1024;
/// The most certificates in a store.
pub const MAX_CERTIFICATES: usize = 1024;
/// The most station locations in a store.
pub const MAX_LOCATIONS: usize = 4096;
/// The most pending certificate requests in a store.
pub const MAX_PENDING_REQUESTS: usize = 1024;
/// The longest location name in bytes.
pub const MAX_NAME_LEN: usize = 255;
/// The largest credential secret QGT writes or accepts after a provider read, matching Windows
/// Credential Manager's limit. Provider allocations/copies before returning a read are not bounded.
pub const MAX_KEY_LEN: usize = 2560;

/// Select a library-owned credential backend. No backend handle or secret reader is exposed.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum KeyBackend {
    /// A fresh, volatile backend for tests and callers' own tests. Dropping the Store wipes its
    /// secrets; reopening the folder creates another empty backend and reports missing keys.
    /// This is not persistent storage for an operator's keys.
    Memory,
    /// The OS credential store, shared with Desktop and the command line. Uses [`SERVICE`],
    /// or [`TEST_SERVICE`] whenever `QG_DESKTOP_TEST_KEYCHAIN` is present, as Desktop does.
    /// The variable's value is never used as a service name. Selection is fixed at open.
    Os,
    /// The OS credential store under [`TEST_SERVICE`] only, regardless of the environment.
    OsTest,
}

/// A public certificate record; its identifier survives whole-file replacements.
#[derive(Clone, Debug)]
pub struct StoredCertificate {
    /// The store's opaque certificate identifier, used for signing and deletion.
    pub id: String,
    /// The certificate, parsed as a LoTW callsign certificate. Reading the store does not establish
    /// a new chain of trust; certificate issuers are verified on import, against the store's trust
    /// (`Store::trust_with`), as with `tbk::read`.
    pub certificate: Certificate,
    /// The credential entry's name, if this certificate has a key.
    pub key_name: Option<String>,
}

/// A named station location.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StoredLocation {
    /// Unique within this store; compared exactly, including case.
    pub name: String,
    /// The station's fields, checked by `StationLocation::new` on read.
    pub station: StationLocation,
}

/// Public metadata for a request whose private key is owned by this store.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingRequest {
    /// Opaque request identifier for abandonment.
    pub id: String,
    /// Requested uppercase callsign.
    pub callsign: String,
    /// Requested ARRL DXCC entity number.
    pub dxcc: u32,
    /// Requested SubjectPublicKeyInfo DER, used to match the response.
    pub public_key_der: Vec<u8>,
    /// Request creation time in whole seconds since the Unix epoch.
    pub created_at: u64,
    /// Library-owned credential name; this conveys no access to its bytes.
    pub key_name: String,
}

/// Inconsistencies found at open. Nothing is deleted or repaired automatically.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct OpenReport {
    /// Certificate identifiers whose named credential is missing.
    pub missing_keys: Vec<String>,
    /// Pending request identifiers whose named credential is missing.
    pub missing_request_keys: Vec<String>,
    /// Whether orphan detection was performed. Windows OS backends report `Unavailable`;
    /// missing-key checks still run for every certificate and pending request named by the file.
    pub orphan_detection: OrphanDetection,
    /// Credential names with no certificate or pending request in the file. An empty list means
    /// no orphans were found only when `orphan_detection` is `Available`.
    pub orphaned_keys: Vec<String>,
}

/// Why a store operation failed. No variant carries secret bytes or a password.
#[derive(Debug)]
pub enum StoreError {
    /// The log's station details cannot be resolved for signing.
    Log(crate::signed_log::LogError),
    /// An OS file operation failed before replacement.
    Io(io::Error),
    /// Replacement succeeded, but the durability sync failed. The visible file and its key must
    /// be kept together; the caller should report uncertain crash durability, not retry blindly.
    Durability(io::Error),
    /// A credential-store operation failed.
    KeyStore(KeyStoreError),
    /// A key could not be unlocked or does not match its certificate.
    Key(KeyError),
    /// The file uses a newer format; it has not been rewritten.
    NewerVersion {
        /// The version found in the file.
        found: u32,
        /// The newest version this build knows.
        supported: u32,
    },
    /// The input exceeds a documented bound.
    Limit(&'static str),
    /// Malformed or unsupported content. The explanation is fixed text, never input.
    Invalid(&'static str),
    /// A certificate or location already exists.
    AlreadyExists,
    /// A new-only signed log holds a QSO another signing recorded after the plan was made.
    /// Nothing was written; prepare and sign again.
    SignedMeanwhile,
    /// The requested certificate, location, key or accepted root is absent.
    NotFound,
    /// LoTW's pinned roots and CAs are part of this library and are always trusted: they cannot
    /// be removed.
    BuiltInRoot,
    /// Secure randomness was unavailable.
    Random,
    /// The file write failed and the backend also refused to remove the new key. It remains an
    /// orphan, reported next time the store is opened if orphan detection is available.
    Rollback {
        /// The file-write failure.
        write: Box<StoreError>,
        /// The credential cleanup failure.
        cleanup: KeyStoreError,
    },
}

impl fmt::Display for StoreError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Log(error) => write!(f, "the log: {error}"),
            Self::Io(e) => write!(f, "the store file: {e}"),
            Self::Durability(e) => write!(
                f,
                "the store was replaced but its durability sync failed: {e}"
            ),
            Self::KeyStore(e) => write!(f, "the credential store: {e}"),
            Self::Key(e) => write!(f, "the signing key: {e}"),
            Self::NewerVersion { found, supported } => write!(
                f,
                "store version {found} is newer than supported version {supported}"
            ),
            Self::Limit(what) => write!(f, "the store exceeds its limit for {what}"),
            Self::Invalid(what) => write!(f, "invalid store: {what}"),
            Self::AlreadyExists => f.write_str("the store entry already exists"),
            Self::SignedMeanwhile => f.write_str(
                "a QSO in this log was signed by another run meanwhile; nothing was written",
            ),
            Self::NotFound => f.write_str("the store entry or its key is missing"),
            Self::BuiltInRoot => f.write_str(
                "that is one of LoTW's roots or CAs built into QG Trust, which are always trusted \
                 and cannot be removed",
            ),
            Self::Random => f.write_str("secure randomness is unavailable"),
            Self::Rollback { write, cleanup } => write!(
                f,
                "{write}; the new credential could not be removed: {cleanup}"
            ),
        }
    }
}

impl std::error::Error for StoreError {}
impl From<io::Error> for StoreError {
    fn from(error: io::Error) -> Self {
        Self::Io(error)
    }
}
impl From<KeyStoreError> for StoreError {
    fn from(error: KeyStoreError) -> Self {
        Self::KeyStore(error)
    }
}
impl From<KeyError> for StoreError {
    fn from(error: KeyError) -> Self {
        Self::Key(error)
    }
}

#[derive(Default)]
struct Data {
    signed_qsos: std::collections::BTreeMap<String, SignedQso>,
    certificates: Vec<StoredCertificate>,
    locations: Vec<StoredLocation>,
    pending_requests: Vec<PendingRequest>,
    roots: Vec<roots::AcceptedRoot>,
}

/// A shared folder and its private, library-owned credential backend.
///
/// Raw credential access is deliberately unavailable to callers:
///
/// ```compile_fail,E0603
/// use qso_graph_trust::store::KeyStore;
/// ```
///
/// ```compile_fail,E0603
/// use qso_graph_trust::store::MemoryKeyStore;
/// ```
///
/// ```compile_fail,E0616
/// use qso_graph_trust::store::Store;
/// fn read_secret(store: &Store, name: &str) {
///     let _ = store.keys.get(name);
/// }
/// ```
///
/// ```compile_fail,E0599
/// use qso_graph_trust::store::Store;
/// fn read_secret(store: &Store, name: &str) {
///     let _ = store.get(name);
/// }
/// ```
pub struct Store {
    dir: PathBuf,
    keys: Box<dyn KeyStore>,
    // Exercise failures after rename without depending on host permissions or filesystem faults.
    #[cfg(test)]
    fail_sync: std::sync::atomic::AtomicBool,
}

impl Store {
    /// Open (or create) a folder, validate its file and report missing credentials. Report orphans
    /// when supported; `OpenReport::orphan_detection` explicitly identifies unavailable detection.
    /// An absent file is an empty store; the first successful mutation creates `store.xml`.
    pub fn open(
        dir: impl AsRef<Path>,
        backend: KeyBackend,
    ) -> Result<(Self, OpenReport), StoreError> {
        let keys: Box<dyn KeyStore> = match backend {
            KeyBackend::Memory => Box::new(MemoryKeyStore::new()),
            KeyBackend::Os => Box::new(OsKeyStore::new(false)),
            KeyBackend::OsTest => Box::new(OsKeyStore::new(true)),
        };
        Self::open_with_keys(dir.as_ref(), keys)
    }

    // Only the library can construct or retain a backend that can read credential bytes.
    fn open_with_keys(
        dir: &Path,
        keys: Box<dyn KeyStore>,
    ) -> Result<(Self, OpenReport), StoreError> {
        create_directory(dir, sync_directory)?;
        let store = Self {
            dir: dir.to_path_buf(),
            keys,
            #[cfg(test)]
            fail_sync: std::sync::atomic::AtomicBool::new(false),
        };
        let _lock = store.lock()?;
        let data = store.read()?;
        let mut report = OpenReport {
            orphan_detection: store.keys.orphan_detection(),
            ..OpenReport::default()
        };
        for cert in &data.certificates {
            if let Some(name) = &cert.key_name
                && !store.keys.exists(name)?
            {
                report.missing_keys.push(cert.id.clone());
            }
        }
        for request in &data.pending_requests {
            if !store.keys.exists(&request.key_name)? {
                report.missing_request_keys.push(request.id.clone());
            }
        }
        if report.orphan_detection == OrphanDetection::Unavailable {
            return Ok((store, report));
        }
        let names = store.keys.names()?;
        if names.len() > keys::MAX_KEYS {
            return Err(StoreError::Limit("credential names"));
        }
        for name in names {
            if !keys::valid_name(&name, "key:") {
                return Err(StoreError::Invalid("credential name"));
            }
            if !data
                .certificates
                .iter()
                .any(|c| c.key_name.as_ref() == Some(&name))
                && !data.pending_requests.iter().any(|r| r.key_name == name)
            {
                report.orphaned_keys.push(name);
            }
        }
        report.orphaned_keys.sort();
        report.orphaned_keys.dedup();
        Ok((store, report))
    }

    /// List public certificate records from the current file, under the lock.
    pub fn certificates(&self) -> Result<Vec<StoredCertificate>, StoreError> {
        let _lock = self.lock()?;
        Ok(self.read()?.certificates)
    }

    /// List checked station locations from the current file, under the lock.
    pub fn locations(&self) -> Result<Vec<StoredLocation>, StoreError> {
        let _lock = self.lock()?;
        Ok(self.read()?.locations)
    }

    /// Add an imported certificate and its key. Unlocks and validates the key with `password`,
    /// hands only PKCS#8 DER to the backend, then publishes its name in the file.
    pub fn add_certificate_with_key(
        &self,
        entry: &BackedUpCertificate,
        password: Option<&[u8]>,
    ) -> Result<String, StoreError> {
        let _lock = self.lock()?;
        let mut data = self.read()?;
        let cert = entry
            .certificate
            .as_ref()
            .ok_or(StoreError::Invalid("certificate is required"))?;
        // The same certificate already here without its key takes this one; with a key, it is
        // already here.
        let keyless = keyless_twin(&data, cert);
        if keyless.is_none() {
            check_certificate(&data, cert)?;
        }
        let key = entry.key.as_ref().ok_or(StoreError::NotFound)?;
        if key.callsign() != cert.callsign() || key.request_dxcc().is_some_and(|d| d != cert.dxcc())
        {
            return Err(StoreError::Invalid(
                "key identity does not match certificate",
            ));
        }
        let der = key.pkcs8_der(password)?;
        if der.len() > MAX_KEY_LEN {
            return Err(StoreError::Limit("credential bytes"));
        }
        // Validate the private key against the actual certificate, not just the backup's metadata.
        TqslKey::from_pkcs8_der(&der, cert.public_key_der())?;
        let name = keys::new_name("key:")?;
        if let Some(i) = keyless {
            if self.keys.exists(&name)? {
                return Err(StoreError::AlreadyExists);
            }
            data.certificates[i].key_name = Some(name.clone());
            let id = data.certificates[i].id.clone();
            let xml = format::write(&data)?;
            self.put_and_replace(&name, &der, &xml)?;
            return Ok(id);
        }
        let id = keys::new_name("cert:")?;
        if self.keys.exists(&name)? || data.certificates.iter().any(|c| c.id == id) {
            return Err(StoreError::AlreadyExists);
        }
        data.certificates.push(StoredCertificate {
            id: id.clone(),
            certificate: cert.clone(),
            key_name: Some(name.clone()),
        });
        // Serialize before putting the key, so bad public input cannot create even a temporary orphan.
        let xml = format::write(&data)?;
        self.put_and_replace(&name, &der, &xml)?;
        Ok(id)
    }

    /// Store a generated key and publish its pending request, returning a `request:<uuid>` ID.
    /// The request remains borrowed so a pre-replacement failure can be retried. Do not submit
    /// its `.tq5` until this succeeds. Duplicate SPKIs are refused. After `Durability`, consult
    /// `pending_requests` before retrying: the record is visible and its key has been retained.
    pub fn store_request(&self, request: &GeneratedRequest) -> Result<String, StoreError> {
        let _lock = self.lock()?;
        let mut data = self.read()?;
        if data.pending_requests.len() >= MAX_PENDING_REQUESTS {
            return Err(StoreError::Limit("pending requests"));
        }
        if data
            .pending_requests
            .iter()
            .any(|r| r.public_key_der == request.public)
        {
            return Err(StoreError::AlreadyExists);
        }
        if request.private.len() > MAX_KEY_LEN {
            return Err(StoreError::Limit("credential bytes"));
        }
        TqslKey::from_pkcs8_der(&request.private, &request.public)?;
        let name = keys::new_name("key:")?;
        let id = keys::new_name("request:")?;
        if self.keys.exists(&name)? || data.pending_requests.iter().any(|r| r.id == id) {
            return Err(StoreError::AlreadyExists);
        }
        data.pending_requests.push(PendingRequest {
            id: id.clone(),
            callsign: request.callsign.clone(),
            dxcc: request.dxcc,
            public_key_der: request.public.clone(),
            created_at: request.created_at,
            key_name: name.clone(),
        });
        let xml = format::write(&data)?;
        self.put_and_replace(&name, &request.private, &xml)?;
        Ok(id)
    }

    /// List pending public metadata from the current file under the lock.
    pub fn pending_requests(&self) -> Result<Vec<PendingRequest>, StoreError> {
        let _lock = self.lock()?;
        Ok(self.read()?.pending_requests)
    }

    /// Publish removal of a pending record before deleting its key. A failed durability sync
    /// retains the key; backend deletion failure leaves an orphan reported on the next open
    /// when orphan detection is available.
    pub fn abandon_request(&self, id: &str) -> Result<(), StoreError> {
        let _lock = self.lock()?;
        let mut data = self.read()?;
        let i = data
            .pending_requests
            .iter()
            .position(|r| r.id == id)
            .ok_or(StoreError::NotFound)?;
        let request = data.pending_requests.remove(i);
        self.replace(&format::write(&data)?)?;
        self.keys.delete(&request.key_name)?;
        Ok(())
    }

    /// Attach a response to its pending request by SPKI, call and DXCC, validating the stored
    /// private key against the certificate. The caller verifies issuer trust before import.
    /// Attachment and pending removal share one file replacement under the lock. Failures
    /// before replacement retain the pending request and key; `Durability` leaves the
    /// certificate visible and its key retained.
    pub fn add_requested_certificate(
        &self,
        certificate: &Certificate,
    ) -> Result<String, StoreError> {
        let _lock = self.lock()?;
        let mut data = self.read()?;
        check_certificate(&data, certificate)?;
        let i = data
            .pending_requests
            .iter()
            .position(|r| {
                r.public_key_der == certificate.public_key_der()
                    && r.callsign == certificate.callsign()
                    && r.dxcc == certificate.dxcc()
            })
            .ok_or(StoreError::NotFound)?;
        let key_name = data.pending_requests[i].key_name.clone();
        let der = self.keys.get(&key_name)?.ok_or(StoreError::NotFound)?;
        if der.len() > MAX_KEY_LEN {
            return Err(StoreError::Limit("credential bytes"));
        }
        TqslKey::from_pkcs8_der(&der, certificate.public_key_der())?;
        let id = keys::new_name("cert:")?;
        if data.certificates.iter().any(|c| c.id == id) {
            return Err(StoreError::AlreadyExists);
        }
        data.certificates.push(StoredCertificate {
            id: id.clone(),
            certificate: certificate.clone(),
            key_name: Some(key_name),
        });
        data.pending_requests.remove(i);
        self.replace(&format::write(&data)?)?;
        Ok(id)
    }

    /// Add a public certificate without a credential. The caller verifies its issuer on import.
    pub fn add_certificate(&self, certificate: &Certificate) -> Result<String, StoreError> {
        let _lock = self.lock()?;
        let mut data = self.read()?;
        check_certificate(&data, certificate)?;
        let id = keys::new_name("cert:")?;
        if data.certificates.iter().any(|c| c.id == id) {
            return Err(StoreError::AlreadyExists);
        }
        data.certificates.push(StoredCertificate {
            id: id.clone(),
            certificate: certificate.clone(),
            key_name: None,
        });
        self.replace(&format::write(&data)?)?;
        Ok(id)
    }

    /// Delete the file record first, then its credential. A backend failure leaves an orphan
    /// reported by the next open when orphan detection is available; it never leaves a certificate
    /// pointing to a key we deleted.
    pub fn delete_certificate(&self, id: &str) -> Result<(), StoreError> {
        let _lock = self.lock()?;
        let mut data = self.read()?;
        let i = data
            .certificates
            .iter()
            .position(|c| c.id == id)
            .ok_or(StoreError::NotFound)?;
        let cert = data.certificates.remove(i);
        self.replace(&format::write(&data)?)?;
        if let Some(name) = cert.key_name {
            self.keys.delete(&name)?;
        }
        Ok(())
    }

    /// Add a location; a name already present is refused.
    pub fn add_location(&self, name: &str, station: &StationLocation) -> Result<(), StoreError> {
        self.save_location(name, station, false)
    }

    /// Replace a location; a name not present is refused.
    pub fn replace_location(
        &self,
        name: &str,
        station: &StationLocation,
    ) -> Result<(), StoreError> {
        self.save_location(name, station, true)
    }

    fn save_location(
        &self,
        name: &str,
        station: &StationLocation,
        replace: bool,
    ) -> Result<(), StoreError> {
        let _lock = self.lock()?;
        let mut data = self.read()?;
        format::check_name(name)?;
        let i = data.locations.iter().position(|l| l.name == name);
        match (i, replace) {
            (Some(_), false) => return Err(StoreError::AlreadyExists),
            (None, true) => return Err(StoreError::NotFound),
            (Some(i), true) => data.locations[i].station = station.clone(),
            (None, false) => {
                if data.locations.len() >= MAX_LOCATIONS {
                    return Err(StoreError::Limit("locations"));
                }
                data.locations.push(StoredLocation {
                    name: name.into(),
                    station: station.clone(),
                });
            }
        }
        self.replace(&format::write(&data)?)
    }

    /// Delete a location by its exact name.
    pub fn delete_location(&self, name: &str) -> Result<(), StoreError> {
        let _lock = self.lock()?;
        let mut data = self.read()?;
        let i = data
            .locations
            .iter()
            .position(|l| l.name == name)
            .ok_or(StoreError::NotFound)?;
        data.locations.remove(i);
        self.replace(&format::write(&data)?)
    }

    /// Load and validate a key for one signing operation, then drop it. The callback can return
    /// a signature or its own result but cannot obtain private key bytes. The lock spans the
    /// callback, preventing concurrent deletion; the callback must not reenter this store.
    pub fn with_key<T>(
        &self,
        cert_id: &str,
        sign: impl FnOnce(&TqslKey) -> T,
    ) -> Result<T, StoreError> {
        let _lock = self.lock()?;
        let data = self.read()?;
        let cert = data
            .certificates
            .iter()
            .find(|c| c.id == cert_id)
            .ok_or(StoreError::NotFound)?;
        let name = cert.key_name.as_ref().ok_or(StoreError::NotFound)?;
        let der = self.keys.get(name)?.ok_or(StoreError::NotFound)?;
        if der.len() > MAX_KEY_LEN {
            return Err(StoreError::Limit("credential bytes"));
        }
        let key = TqslKey::from_pkcs8_der(&der, cert.certificate.public_key_der())?;
        drop(der);
        Ok(sign(&key))
    }

    fn put_and_replace(&self, name: &str, der: &[u8], xml: &str) -> Result<(), StoreError> {
        self.keys.put(name, der)?;
        if let Err(write) = self.replace(xml) {
            // After rename the file already names the key, even when durability sync fails.
            if matches!(write, StoreError::Durability(_)) {
                return Err(write);
            }
            if let Err(cleanup) = self.keys.delete(name) {
                return Err(StoreError::Rollback {
                    write: Box::new(write),
                    cleanup,
                });
            }
            return Err(write);
        }
        Ok(())
    }

    fn lock(&self) -> Result<File, StoreError> {
        let lock = owner_file()
            .create(true)
            .truncate(false)
            .open(self.dir.join("store.lock"))?;
        lock.lock()?;
        Ok(lock)
    }

    fn read(&self) -> Result<Data, StoreError> {
        read_file(&self.dir.join("store.xml"))
    }

    fn replace(&self, xml: &str) -> Result<(), StoreError> {
        let partial = self.dir.join("store.xml.partial");
        // A crash may have left this name behind. Unlink first, never follow an old symlink.
        match fs::remove_file(&partial) {
            Ok(()) => (),
            Err(e) if e.kind() == io::ErrorKind::NotFound => (),
            Err(e) => return Err(e.into()),
        }
        let result = (|| {
            let mut file = owner_file().create_new(true).open(&partial)?;
            file.write_all(xml.as_bytes())?;
            file.sync_all()?;
            drop(file);
            fs::rename(&partial, self.dir.join("store.xml"))?;
            Ok::<_, StoreError>(())
        })();
        if result.is_err() {
            let _ = fs::remove_file(&partial);
        }
        result?;
        #[cfg(test)]
        if self.fail_sync.load(std::sync::atomic::Ordering::Relaxed) {
            return Err(StoreError::Durability(io::Error::other(
                "injected sync failure after rename",
            )));
        }
        sync_replacement(&self.dir).map_err(StoreError::Durability)?;
        Ok(())
    }
}

/// Read and check `store.xml` at `path`: the one reader, for [`Store`] and [`Listing`]. An absent
/// file is an empty store. It opens the file read-only and creates nothing.
fn read_file(path: &Path) -> Result<Data, StoreError> {
    let file = match File::open(path) {
        Ok(file) => file,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Data::default()),
        Err(e) => return Err(e.into()),
    };
    if file.metadata()?.len() > MAX_FILE_LEN as u64 {
        return Err(StoreError::Limit("file bytes"));
    }
    let mut bytes = Vec::new();
    file.take(MAX_FILE_LEN as u64 + 1).read_to_end(&mut bytes)?;
    if bytes.len() > MAX_FILE_LEN {
        return Err(StoreError::Limit("file bytes"));
    }
    format::read(std::str::from_utf8(&bytes).map_err(|_| StoreError::Invalid("not UTF-8"))?)
}

fn sync_replacement(dir: &Path) -> io::Result<()> {
    #[cfg(windows)]
    {
        // The partial's flush predates the rename, so it cannot commit that metadata change.
        // Reopen the renamed file with write access: sync_all calls FlushFileBuffers, which
        // flushes cached file metadata as well as data. On NTFS this commits the rename before
        // we delete a credential. Microsoft's File Caching and FlushFileBuffers documentation:
        // https://learn.microsoft.com/en-us/windows/win32/fileio/file-caching
        // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers
        // This relies on the filesystem, drivers and hardware honoring flushes. Other filesystems
        // and network shares may differ; this is not a volume-wide or ancestor-directory flush.
        OpenOptions::new()
            .write(true)
            .open(dir.join("store.xml"))?
            .sync_all()?;
    }
    sync_directory(dir)
}

fn sync_directory(dir: &Path) -> io::Result<()> {
    #[cfg(unix)]
    File::open(dir)?.sync_all()?;
    #[cfg(not(unix))]
    let _ = dir;
    Ok(())
}

fn create_directory(dir: &Path, sync: impl Fn(&Path) -> io::Result<()>) -> io::Result<()> {
    const PENDING: &str = ".qgt-directory-pending";

    let dir = std::path::absolute(dir)?;
    let mut missing = Vec::new();
    let mut ancestor = dir.as_path();
    while !ancestor.try_exists()? {
        missing.push(ancestor);
        ancestor = ancestor
            .parent()
            .ok_or_else(|| io::Error::other("no existing store ancestor"))?;
    }
    // A marker identifies our unfinished work without opening an established ancestor for
    // reading. The first unmarked ancestor is the caller's existing directory boundary.
    let mut chain = Vec::new();
    // Creation can stop between mkdir and its marker. A marked parent identifies that one
    // unfinished child; its own marker was persisted before we attempted the child's mkdir.
    if !ancestor.join(PENDING).try_exists()?
        && let Some(parent) = ancestor.parent()
        && parent.join(PENDING).try_exists()?
    {
        chain.push(ancestor);
        ancestor = parent;
    }
    for path in ancestor.ancestors() {
        if !path.join(PENDING).try_exists()? {
            break;
        }
        chain.push(path);
    }
    chain.reverse();
    chain.extend(missing.into_iter().rev());

    #[cfg(unix)]
    let builder = {
        use std::os::unix::fs::DirBuilderExt;
        let mut builder = fs::DirBuilder::new();
        builder.mode(0o700);
        builder
    };
    #[cfg(not(unix))]
    let builder = fs::DirBuilder::new();
    for (index, path) in chain.iter().enumerate() {
        match builder.create(path) {
            Ok(()) => (),
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists && path.is_dir() => (),
            Err(e) => return Err(e),
        }
        match owner_file().create_new(true).open(path.join(PENDING)) {
            Ok(marker) => marker.sync_all()?,
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => (),
            Err(e) => return Err(e),
        }
        if index > 0 {
            sync(chain[index - 1])?;
        }
        // Persist the recovery marker before creating a descendant. Keep all markers until
        // every entry below the existing boundary has been synced.
        sync(path)?;
    }
    for path in &chain {
        match fs::remove_file(path.join(PENDING)) {
            Ok(()) => (),
            Err(e) if e.kind() == io::ErrorKind::NotFound => (),
            Err(e) => return Err(e),
        }
        // Remove markers from the top down: any remaining pending chain stays contiguous.
        sync(path)?;
    }
    if chain.is_empty() {
        sync(&dir)?;
    }
    Ok(())
}

/// The same certificate, already in the store with no key.
fn keyless_twin(data: &Data, cert: &Certificate) -> Option<usize> {
    data.certificates
        .iter()
        .position(|c| c.key_name.is_none() && c.certificate.der() == cert.der())
}

fn check_certificate(data: &Data, cert: &Certificate) -> Result<(), StoreError> {
    if data.certificates.len() >= MAX_CERTIFICATES {
        return Err(StoreError::Limit("certificates"));
    }
    if data
        .certificates
        .iter()
        .any(|c| c.certificate.der() == cert.der())
    {
        return Err(StoreError::AlreadyExists);
    }
    Ok(())
}

fn owner_file() -> OpenOptions {
    let mut options = OpenOptions::new();
    options.read(true).write(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    options
}

/// The shared data folder for this platform, or `None` when its required environment is absent.
/// Empty environment values are treated as absent; a relative XDG_DATA_HOME is ignored as XDG
/// requires an absolute path. Callers may always supply an explicit folder to `Store::open`.
pub fn default_dir() -> Option<PathBuf> {
    default_dir_from(|name| {
        std::env::var_os(name)
            .filter(|v| !v.is_empty())
            .map(PathBuf::from)
    })
}

fn default_dir_from(env: impl Fn(&str) -> Option<PathBuf>) -> Option<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        env("APPDATA").map(|p| p.join("qso-graph").join("trust"))
    }
    #[cfg(target_os = "macos")]
    {
        env("HOME").map(|p| p.join("Library/Application Support/io.qso-graph.trust"))
    }
    #[cfg(not(any(target_os = "windows", target_os = "macos")))]
    {
        env("XDG_DATA_HOME")
            .filter(|p| p.is_absolute())
            .or_else(|| env("HOME").map(|p| p.join(".local/share")))
            .map(|p| p.join("qso-graph-trust"))
    }
}

#[cfg(test)]
mod tests;