car-sync 0.50.0

Multi-device sync core for Common Agent Runtime — replica-tagged append-only oplog + deterministic CRDT fold
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
//! Org-key directory — the publish/fetch surface for the client-side org-key
//! agreement (the follow-up named in `crypto.rs` alongside the merged
//! `wrap_org_key`/`unwrap_org_key` primitives).
//!
//! ## What this carries — and why it is NOT the oplog
//!
//! The org master key `K_org` is shared across an org's members by *wrapping*
//! it once per member ([`crate::crypto::wrap_org_key`], ECIES over X25519) so
//! every member can recover the same key while the relay only ever sees
//! ciphertext. To distribute those wraps, members need a place to **publish**
//! their [`WrappedOrgKey`] blobs and their X25519 **public keys**, and to
//! **fetch** the ones addressed to them.
//!
//! That surface is a **key-value directory**, not an append-only op stream:
//!
//! - a wrapped blob is keyed by `(epoch, recipient_user_id)` within one org;
//! - a member public key is keyed by `account_id`;
//! - there is no sequence chain, no frontier, no GC horizon, no checkpoint
//!   dominance — the invariants that define [`crate::relay::Relay`].
//!
//! So it is deliberately a **separate trait**, not four more methods bolted
//! onto `Relay`/`SyncTransport`. Bolting KV semantics onto the oplog state
//! machine would let a blob be counted in a device frontier or swept by a GC
//! pass that mistook it for a stale op. Routing org-key traffic around the
//! oplog keeps both models honest. (This mirrors the crate's own idiom: a
//! [`OrgKeyDirectory`] trait over a pure [`OrgKeyDirectoryState`] machine,
//! driven by both an in-memory and an fs-backed reference — exactly as
//! `Relay` is driven by `InMemoryRelay` + `FsRelay`.)
//!
//! ## Scope, and what this slice is (and is not)
//!
//! Like [`crate::relay::Relay`], the trait here is **single-directory**: one
//! handle serves one org's directory (an [`FsOrgKeyDirectory`] is bound to one
//! dir, just as an `FsRelay` is bound to one scope dir). The scope-keyed,
//! network-faithful form (the `org:<id>` param, mirroring
//! [`crate::net_relay::SyncTransport`]) and the Parslee/m365 backend come in a
//! later slice — this one is the pure reference: no prod caller dispatches it,
//! no `SyncTransport`/`car-parslee` change is forced, and it stays inert until
//! the org-scope path is wired behind the cryptographer-audit gate.
//!
//! ## Trust boundary — publisher authz is CONFIDENTIALITY-critical, not availability
//!
//! This reference is a **dumb store**: `publish_*` is last-write-wins and does
//! NOT authenticate the publisher. That is the right shape for a pure state
//! machine — but do not mistake it for "just a DoS surface." The authz the
//! backend slice must add ("only the account itself may publish its own pubkey,
//! and only a legitimate `K_org` holder may publish a wrap") is a
//! **confidentiality** control. Unauthenticated publish enables two attacks,
//! both strictly worse than denial of service:
//!
//! - **Wrap-table poisoning → key substitution.** A member's X25519 public key
//!   is public (it is served from THIS directory). Anyone can therefore wrap an
//!   attacker-chosen `K_org'` against a victim's real pubkey and publish it;
//!   the victim's [`crate::crypto::unwrap_org_key`] *authenticates* it (the DH
//!   matches the victim's secret, the bound `user_id` is the victim's), so the
//!   victim adopts the attacker's key and encrypts future org data under it.
//! - **Pubkey-table poisoning → genuine `K_org` leak.** Overwrite a victim's
//!   pubkey entry with the attacker's own pubkey; a legitimate holder of
//!   `K_org` then wraps the REAL `K_org` against that attacker pubkey (it
//!   believes it is the victim's), and the attacker unwraps it with their own
//!   secret and the victim's `user_id` — recovering the real org key.
//!
//! Neither attack is stopped by the AEAD / contributory-DH checks in
//! `unwrap_org_key`: those only prove "some wrapper used my `user_id` and a
//! pubkey matching my secret," and both inputs are public. The `recipient`
//! field is likewise ADVISORY (see [`crate::crypto::WrappedOrgKey`]) and must
//! not be routed or authorized on. So the backend MUST authenticate the
//! publisher of every `publish_wrapped` / `publish_pubkey`; treating that as
//! optional hardening is a key-compromise bug, not a UX one. The one thing the
//! wrap ciphertext itself never leaks is `K_org` to a passive relay — but the
//! pubkey-poisoning path above leaks it to an *active* publisher, which is why
//! publish authz cannot be deferred as availability-only.

use crate::crypto::WrappedOrgKey;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};

/// A member's published X25519 identity public key (the recipient key
/// [`crate::crypto::wrap_org_key`] wraps against), addressed by `account_id`.
/// `public_hex` is the lowercase hex of the 32-byte X25519 point produced by
/// [`crate::crypto::x25519_public`]; the directory stores it opaquely and does
/// not validate the point (validation happens at wrap/unwrap time).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemberPublicKey {
    pub account_id: String,
    pub public_hex: String,
}

/// Failures publishing to / fetching from an org-key directory.
#[derive(Debug)]
pub enum OrgKeyDirectoryError {
    /// Persistence I/O (fs-backed directory only).
    Io(std::io::Error),
    /// The publisher is not authorized for this directory / key. This is a
    /// LOAD-BEARING, distinct signal — NOT a transient failure to retry.
    /// Because publisher authz here is confidentiality-critical (see the module
    /// doc: unauthenticated publish enables key substitution + `K_org` leak),
    /// the transport-backed directory must surface a backend authz refusal as
    /// THIS variant, never collapse it into `Io` where a retry loop would treat
    /// a security "no" as a network blip.
    Unauthorized(String),
}

impl fmt::Display for OrgKeyDirectoryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OrgKeyDirectoryError::Io(e) => write!(f, "org-key directory io error: {e}"),
            OrgKeyDirectoryError::Unauthorized(m) => {
                write!(f, "org-key directory unauthorized: {m}")
            }
        }
    }
}

impl std::error::Error for OrgKeyDirectoryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            OrgKeyDirectoryError::Io(e) => Some(e),
            OrgKeyDirectoryError::Unauthorized(_) => None,
        }
    }
}

/// The publish/fetch surface for one org's directory.
///
/// Single-directory (no `org` param) — one handle serves one org, mirroring
/// [`crate::relay::Relay`]. `&mut self` because the fs-backed reference takes
/// an exclusive file lock and persists on write.
pub trait OrgKeyDirectory {
    /// Publish (or replace) the wrap for `(wrapped.epoch, wrapped.recipient)`.
    /// Last-write-wins — re-publishing a fresh wrap of the same `K_org`
    /// (a new ephemeral each time) for a recipient is expected and benign.
    fn publish_wrapped(&mut self, wrapped: &WrappedOrgKey) -> Result<(), OrgKeyDirectoryError>;

    /// Fetch the wrap addressed to `recipient_user_id` at exactly `epoch`, if
    /// one has been published. Reads are pure (`&self`) — unlike
    /// [`crate::relay::Relay`], this type has no per-call roster/checkpoint
    /// reconciliation, so a fetch never rewrites state (the fs reference takes a
    /// shared lock and returns; no fsync-on-read).
    fn fetch_wrapped(
        &self,
        epoch: u64,
        recipient_user_id: &str,
    ) -> Result<Option<WrappedOrgKey>, OrgKeyDirectoryError>;

    /// Every wrap addressed to `recipient_user_id`, newest epoch first — the
    /// client picks the highest epoch it can [`crate::crypto::unwrap_org_key`].
    fn fetch_wrapped_for(
        &self,
        recipient_user_id: &str,
    ) -> Result<Vec<WrappedOrgKey>, OrgKeyDirectoryError>;

    /// Publish (or replace) `account_id`'s X25519 public key.
    fn publish_pubkey(
        &mut self,
        account_id: &str,
        public_hex: &str,
    ) -> Result<(), OrgKeyDirectoryError>;

    /// Every member public key in this directory, ordered by `account_id`.
    fn fetch_pubkeys(&self) -> Result<Vec<MemberPublicKey>, OrgKeyDirectoryError>;
}

/// The pure directory state — the same "trait over a pure state machine"
/// shape as [`crate::relay::RelayState`]. Both references drive this; it holds
/// no I/O and is deterministic.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct OrgKeyDirectoryState {
    /// `recipient_user_id → (epoch → wrap)`. Nested so a recipient's wraps
    /// across epochs stay grouped for `fetch_wrapped_for`. `BTreeMap<u64, _>`
    /// serializes to a JSON object with stringified integer keys (serde_json).
    ///
    /// TODO(org-scope): the key is `(recipient, epoch)` only — `wrapped.org` is
    /// NOT part of it because this handle is single-org by construction (one dir
    /// = one org, like `FsRelay` = one scope). When the scope-keyed `org:<id>`
    /// transport form lands, the key must include `org` (or the handle must
    /// carry + verify it) or two orgs sharing a `(recipient, epoch)` in one
    /// store would collide.
    #[serde(default)]
    wrapped: BTreeMap<String, BTreeMap<u64, WrappedOrgKey>>,
    /// `account_id → X25519 public key hex`.
    #[serde(default)]
    pubkeys: BTreeMap<String, String>,
}

impl OrgKeyDirectoryState {
    fn publish_wrapped(&mut self, wrapped: &WrappedOrgKey) {
        self.wrapped
            .entry(wrapped.recipient.clone())
            .or_default()
            .insert(wrapped.epoch, wrapped.clone());
    }

    fn fetch_wrapped(&self, epoch: u64, recipient_user_id: &str) -> Option<WrappedOrgKey> {
        self.wrapped
            .get(recipient_user_id)
            .and_then(|by_epoch| by_epoch.get(&epoch))
            .cloned()
    }

    fn fetch_wrapped_for(&self, recipient_user_id: &str) -> Vec<WrappedOrgKey> {
        self.wrapped
            .get(recipient_user_id)
            .map(|by_epoch| by_epoch.values().rev().cloned().collect())
            .unwrap_or_default()
    }

    fn publish_pubkey(&mut self, account_id: &str, public_hex: &str) {
        self.pubkeys
            .insert(account_id.to_string(), public_hex.to_string());
    }

    fn fetch_pubkeys(&self) -> Vec<MemberPublicKey> {
        self.pubkeys
            .iter()
            .map(|(account_id, public_hex)| MemberPublicKey {
                account_id: account_id.clone(),
                public_hex: public_hex.clone(),
            })
            .collect()
    }
}

/// In-memory reference — tests and in-process coordination (the
/// [`crate::relay::InMemoryRelay`] analogue).
#[derive(Clone, Debug, Default)]
pub struct InMemoryOrgKeyDirectory {
    state: OrgKeyDirectoryState,
}

impl InMemoryOrgKeyDirectory {
    pub fn new() -> Self {
        Self::default()
    }
}

impl OrgKeyDirectory for InMemoryOrgKeyDirectory {
    fn publish_wrapped(&mut self, wrapped: &WrappedOrgKey) -> Result<(), OrgKeyDirectoryError> {
        self.state.publish_wrapped(wrapped);
        Ok(())
    }

    fn fetch_wrapped(
        &self,
        epoch: u64,
        recipient_user_id: &str,
    ) -> Result<Option<WrappedOrgKey>, OrgKeyDirectoryError> {
        Ok(self.state.fetch_wrapped(epoch, recipient_user_id))
    }

    fn fetch_wrapped_for(
        &self,
        recipient_user_id: &str,
    ) -> Result<Vec<WrappedOrgKey>, OrgKeyDirectoryError> {
        Ok(self.state.fetch_wrapped_for(recipient_user_id))
    }

    fn publish_pubkey(
        &mut self,
        account_id: &str,
        public_hex: &str,
    ) -> Result<(), OrgKeyDirectoryError> {
        self.state.publish_pubkey(account_id, public_hex);
        Ok(())
    }

    fn fetch_pubkeys(&self) -> Result<Vec<MemberPublicKey>, OrgKeyDirectoryError> {
        Ok(self.state.fetch_pubkeys())
    }
}

/// Fs-backed reference — one directory of one org's wraps + member pubkeys,
/// the [`crate::relay::FsRelay`] analogue (the realistic single-host / shared
/// dir). Every mutation runs under an exclusive lock file and persists the
/// whole state via temp-write + fsync + atomic rename, matching `FsRelay`.
#[derive(Debug)]
pub struct FsOrgKeyDirectory {
    dir: PathBuf,
}

impl FsOrgKeyDirectory {
    pub fn open(dir: &Path) -> std::io::Result<Self> {
        fs::create_dir_all(dir)?;
        Ok(Self {
            dir: dir.to_path_buf(),
        })
    }

    fn state_path(&self) -> PathBuf {
        self.dir.join("org-keys.json")
    }

    fn lock_path(&self) -> PathBuf {
        self.dir.join("org-keys.lock")
    }

    /// Deserialize the state file; a missing file is an empty directory.
    fn read_state(path: &Path) -> Result<OrgKeyDirectoryState, OrgKeyDirectoryError> {
        match fs::read_to_string(path) {
            Ok(raw) => serde_json::from_str(&raw)
                .map_err(|e| OrgKeyDirectoryError::Io(std::io::Error::other(e))),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                Ok(OrgKeyDirectoryState::default())
            }
            Err(e) => Err(OrgKeyDirectoryError::Io(e)),
        }
    }

    /// Load state under a SHARED lock — a pure read that never rewrites the
    /// file. Unlike [`crate::relay::FsRelay`], which rewrites on every call to
    /// run roster liveness + checkpoint reconciliation, a directory fetch has
    /// no such side work, so reads take a shared lock (concurrent readers) and
    /// return — no fsync-on-read, and `fetch_*` stay `&self`.
    fn load(&self) -> Result<OrgKeyDirectoryState, OrgKeyDirectoryError> {
        let lock = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(self.lock_path())
            .map_err(OrgKeyDirectoryError::Io)?;
        lock.lock_shared().map_err(OrgKeyDirectoryError::Io)?; // shared; released on drop
        Self::read_state(&self.state_path())
    }

    /// Run `f` over the loaded state under the EXCLUSIVE lock, then persist —
    /// same durable-write shape as [`crate::relay::FsRelay::with_state`].
    fn with_state<T>(
        &mut self,
        f: impl FnOnce(&mut OrgKeyDirectoryState) -> T,
    ) -> Result<T, OrgKeyDirectoryError> {
        let lock = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(self.lock_path())
            .map_err(OrgKeyDirectoryError::Io)?;
        lock.lock().map_err(OrgKeyDirectoryError::Io)?; // exclusive; released on drop

        let mut state = Self::read_state(&self.state_path())?;

        let result = f(&mut state);

        let tmp = self.dir.join("org-keys.json.tmp");
        {
            let mut file = File::create(&tmp).map_err(OrgKeyDirectoryError::Io)?;
            file.write_all(
                serde_json::to_string(&state)
                    .map_err(|e| OrgKeyDirectoryError::Io(std::io::Error::other(e)))?
                    .as_bytes(),
            )
            .map_err(OrgKeyDirectoryError::Io)?;
            file.sync_all().map_err(OrgKeyDirectoryError::Io)?;
        }
        fs::rename(&tmp, self.state_path()).map_err(OrgKeyDirectoryError::Io)?;
        Ok(result)
    }
}

impl OrgKeyDirectory for FsOrgKeyDirectory {
    fn publish_wrapped(&mut self, wrapped: &WrappedOrgKey) -> Result<(), OrgKeyDirectoryError> {
        self.with_state(|state| state.publish_wrapped(wrapped))
    }

    fn fetch_wrapped(
        &self,
        epoch: u64,
        recipient_user_id: &str,
    ) -> Result<Option<WrappedOrgKey>, OrgKeyDirectoryError> {
        Ok(self.load()?.fetch_wrapped(epoch, recipient_user_id))
    }

    fn fetch_wrapped_for(
        &self,
        recipient_user_id: &str,
    ) -> Result<Vec<WrappedOrgKey>, OrgKeyDirectoryError> {
        Ok(self.load()?.fetch_wrapped_for(recipient_user_id))
    }

    fn publish_pubkey(
        &mut self,
        account_id: &str,
        public_hex: &str,
    ) -> Result<(), OrgKeyDirectoryError> {
        self.with_state(|state| state.publish_pubkey(account_id, public_hex))
    }

    fn fetch_pubkeys(&self) -> Result<Vec<MemberPublicKey>, OrgKeyDirectoryError> {
        Ok(self.load()?.fetch_pubkeys())
    }
}

/// The shared behavioural contract for any [`OrgKeyDirectory`] — kept out of
/// `mod tests` (as `pub(crate)`) so both the reference tests here AND the
/// `LoopbackTransport`-backed `NetworkOrgKeyDirectory` tests in
/// [`crate::net_relay`] drive the *same* sequence, proving the wire form is
/// identical to these references before a byte crosses into `car-parslee`.
#[cfg(test)]
pub(crate) mod conformance {
    use super::*;
    use crate::crypto::{
        derive_ed25519_identity, derive_x25519_identity, wrap_org_key, x25519_public,
        StretchedMaster,
    };

    /// A real wrap for `recipient` at `epoch` — exercises the actual crypto (now
    /// signed by a publisher) so the directory is proven to carry the genuine wire
    /// type intact, not a hand-built stand-in. Uses issued-high-entropy masters
    /// (skips Argon2id) so the conformance suite stays fast.
    pub(crate) fn make_wrap(org: &str, epoch: u64, recipient: &str) -> WrappedOrgKey {
        let k_org = [7u8; 32];
        let sk = derive_x25519_identity(
            &StretchedMaster::from_issued_high_entropy(b"login-secret-for-tests", recipient),
            recipient,
        );
        let recipient_pub = x25519_public(&sk);
        let signer = derive_ed25519_identity(
            &StretchedMaster::from_issued_high_entropy(b"granter-login-for-tests", "acc_granter"),
            "acc_granter",
        );
        wrap_org_key(
            &k_org,
            org,
            epoch,
            recipient,
            &recipient_pub,
            "acc_granter",
            &signer,
        )
        .expect("wrap succeeds")
    }

    /// The behavioural contract every `OrgKeyDirectory` implementation must
    /// satisfy — run against both references here, and reused verbatim against
    /// the `LoopbackTransport`-backed directory in the next slice.
    pub(crate) fn round_trip_suite(dir: &mut dyn OrgKeyDirectory) {
        // wrapped: composite-key (epoch, recipient) round-trip
        let w = make_wrap("acme", 1, "alice");
        dir.publish_wrapped(&w).unwrap();
        assert_eq!(dir.fetch_wrapped(1, "alice").unwrap().as_ref(), Some(&w));
        // opaque payload preserved bit-identically (the AEAD envelope survives)
        let got = dir.fetch_wrapped(1, "alice").unwrap().unwrap();
        assert_eq!(got.envelope, w.envelope);
        assert_eq!(got.ephemeral_pub, w.ephemeral_pub);
        assert_eq!(got.car_wrap, w.car_wrap);

        // isolation: wrong epoch / wrong recipient miss
        assert!(dir.fetch_wrapped(2, "alice").unwrap().is_none());
        assert!(dir.fetch_wrapped(1, "bob").unwrap().is_none());

        // multiple epochs for one recipient, newest first
        let w2 = make_wrap("acme", 5, "alice");
        let w3 = make_wrap("acme", 3, "alice");
        dir.publish_wrapped(&w2).unwrap();
        dir.publish_wrapped(&w3).unwrap();
        let epochs: Vec<u64> = dir
            .fetch_wrapped_for("alice")
            .unwrap()
            .iter()
            .map(|w| w.epoch)
            .collect();
        assert_eq!(epochs, vec![5, 3, 1], "newest epoch first");
        assert!(dir.fetch_wrapped_for("nobody").unwrap().is_empty());

        // pubkey round-trip + ordering
        dir.publish_pubkey("bob", "beef").unwrap();
        dir.publish_pubkey("alice", "cafe").unwrap();
        let keys = dir.fetch_pubkeys().unwrap();
        assert_eq!(
            keys,
            vec![
                MemberPublicKey {
                    account_id: "alice".into(),
                    public_hex: "cafe".into()
                },
                MemberPublicKey {
                    account_id: "bob".into(),
                    public_hex: "beef".into()
                },
            ],
            "ordered by account_id"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::conformance::{make_wrap, round_trip_suite};
    use super::*;
    use serde_json::json;

    #[test]
    fn in_memory_round_trip() {
        let mut dir = InMemoryOrgKeyDirectory::new();
        round_trip_suite(&mut dir);
    }

    #[test]
    fn fs_round_trip() {
        let tmp = tempfile::tempdir().unwrap();
        let mut dir = FsOrgKeyDirectory::open(tmp.path()).unwrap();
        round_trip_suite(&mut dir);
    }

    #[test]
    fn publish_wrapped_is_last_write_wins() {
        let mut dir = InMemoryOrgKeyDirectory::new();
        let mut w = make_wrap("acme", 1, "alice");
        dir.publish_wrapped(&w).unwrap();
        // a re-publish at the same (epoch, recipient) replaces, not duplicates
        w.envelope = json!({"car_enc": "org-key-wrap/v1", "nonce": "00", "ct": "ff"});
        dir.publish_wrapped(&w).unwrap();
        assert_eq!(dir.fetch_wrapped_for("alice").unwrap().len(), 1);
        assert_eq!(
            dir.fetch_wrapped(1, "alice").unwrap().unwrap().envelope,
            w.envelope
        );
    }

    #[test]
    fn publish_pubkey_is_last_write_wins() {
        let mut dir = InMemoryOrgKeyDirectory::new();
        dir.publish_pubkey("alice", "aaaa").unwrap();
        dir.publish_pubkey("alice", "bbbb").unwrap();
        let keys = dir.fetch_pubkeys().unwrap();
        assert_eq!(keys.len(), 1);
        assert_eq!(keys[0].public_hex, "bbbb");
    }

    #[test]
    fn fs_persists_across_handles() {
        let tmp = tempfile::tempdir().unwrap();
        let w = make_wrap("acme", 2, "alice");
        {
            let mut dir = FsOrgKeyDirectory::open(tmp.path()).unwrap();
            dir.publish_wrapped(&w).unwrap();
            dir.publish_pubkey("alice", "cafe").unwrap();
        }
        // a fresh handle over the same dir sees the persisted state (reads are
        // `&self` now, so the handle needs no `mut`)
        let dir = FsOrgKeyDirectory::open(tmp.path()).unwrap();
        assert_eq!(dir.fetch_wrapped(2, "alice").unwrap().as_ref(), Some(&w));
        assert_eq!(dir.fetch_pubkeys().unwrap()[0].public_hex, "cafe");
    }

    /// Pins the `#[serde(default)]` forward-compat guarantee: a state file
    /// written by an older build (missing one or both fields, or `{}`) still
    /// loads as an empty-for-that-field directory rather than failing.
    #[test]
    fn state_loads_from_files_missing_fields() {
        let empty: OrgKeyDirectoryState = serde_json::from_str("{}").unwrap();
        assert!(empty.fetch_pubkeys().is_empty());
        assert!(empty.fetch_wrapped_for("alice").is_empty());

        // only pubkeys present → wrapped defaults
        let partial: OrgKeyDirectoryState =
            serde_json::from_str(r#"{"pubkeys":{"alice":"ff"}}"#).unwrap();
        assert_eq!(partial.fetch_pubkeys().len(), 1);
        assert!(partial.fetch_wrapped_for("alice").is_empty());
    }

    /// A corrupt state file must SURFACE as an error on both read and write —
    /// never panic, and never silently reset to an empty directory (which would
    /// drop everyone's published keys). This is the "someone overwrote the
    /// file" case the module doc warns about.
    #[test]
    fn corrupt_state_file_surfaces_as_error() {
        let tmp = tempfile::tempdir().unwrap();
        let mut dir = FsOrgKeyDirectory::open(tmp.path()).unwrap();
        dir.publish_pubkey("alice", "cafe").unwrap(); // creates the state file
        std::fs::write(tmp.path().join("org-keys.json"), b"{ not json").unwrap();

        assert!(matches!(
            dir.fetch_pubkeys(),
            Err(OrgKeyDirectoryError::Io(_))
        ));
        assert!(matches!(
            dir.publish_pubkey("bob", "beef"),
            Err(OrgKeyDirectoryError::Io(_))
        ));
    }
}