Skip to main content

ferogram_e2e/
state.rs

1/*
2 * Copyright (c) 2026 Ankit Chaubey <ankitchaubey.dev@gmail.com>
3 * https://github.com/ankit-chaubey
4 *
5 * Project: ferogram
6 * Website: https://ferogram.dev
7 *
8 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
9 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
10 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
11 * This file may not be copied, modified, or distributed except according
12 * to those terms.
13 */
14
15//! Per-chat state and the store that keeps it (in memory, optionally on disk).
16//!
17//! # Store file format
18//!
19//! The optional on-disk store (conventionally `<session_name>.e2e`) is a small
20//! binary file, all integers little-endian:
21//!
22//! ```text
23//! magic    "FGE2E\0"            6 bytes
24//! version  u8                   currently 1
25//! count    u32                  number of chats
26//! chat*    count records        see `SecretChatState::encode`
27//! checksum SHA-256 of all preceding bytes (32 bytes)
28//! ```
29//!
30//! The file is replaced atomically (write to a temp file, then rename) and, on
31//! Unix, created with mode `0600`, because it holds every chat's `auth_key`.
32//! Only established chats are stored; pending exchanges and the resend buffer
33//! live in memory only.
34
35use std::collections::{HashMap, VecDeque};
36use std::io::{self, Write};
37use std::path::{Path, PathBuf};
38use std::time::{SystemTime, UNIX_EPOCH};
39
40use sha2::{Digest, Sha256};
41
42use crate::error::E2eError;
43
44/// Progress of a key re-exchange (forward secrecy) for one chat.
45#[derive(Debug, Clone)]
46pub enum RekeyingState {
47    /// No re-key in progress.
48    Idle,
49    /// We sent `RequestKey` and wait for the peer's `AcceptKey`.
50    Requested {
51        /// Identifier of this exchange.
52        exchange_id: i64,
53    },
54    /// We sent `AcceptKey` and wait for the peer's `CommitKey`.
55    Accepted {
56        /// Identifier of this exchange.
57        exchange_id: i64,
58    },
59}
60
61/// Maximum number of sent message blobs retained for Resend handling.
62const SENT_BUFFER_CAPACITY: usize = 100;
63
64/// Per-chat state stored in memory (and optionally persisted to disk).
65#[derive(Debug, Clone)]
66pub struct SecretChatState {
67    /// Secret chat id assigned by Telegram.
68    pub id: i32,
69    /// Access hash for `InputEncryptedChat`.
70    pub access_hash: i64,
71    /// Shared 256-byte key from the DH exchange. Written unencrypted to the store file.
72    pub auth_key: [u8; 256],
73    /// true = we initiated this chat (User A).
74    pub admin: bool,
75    /// Peer user ID.
76    pub user_id: i64,
77    /// Raw incoming sequence counter.
78    pub in_seq_no: i32,
79    /// Raw outgoing sequence counter.
80    pub out_seq_no: i32,
81    /// Parity bit for incoming wire encoding.
82    pub in_seq_no_x: i32,
83    /// Parity bit for outgoing wire encoding.
84    pub out_seq_no_x: i32,
85    /// Remote peer's supported layer (updated on NotifyLayer receipt).
86    pub layer: i32,
87    /// Per-message TTL in seconds (0 = no TTL).
88    pub ttl: i32,
89    /// Messages until next re-key.
90    pub ttr: i32,
91    /// Unix epoch seconds of last auth_key rotation (for 7-day re-key timer).
92    pub updated_at_secs: u64,
93    /// MTProto version in use (1 or 2).
94    pub mtproto: u8,
95    /// Where the current re-key exchange stands.
96    pub rekeying_state: RekeyingState,
97    /// Keyed by exchange_id.
98    /// Requested state: stores 256-byte private key.
99    /// Accepted state: stores 256-byte computed auth_key.
100    pub temp_rekey_map: HashMap<i64, Vec<u8>>,
101    /// Ring buffer of (wire_out_seq_no, encrypted_blob) for Resend support.
102    /// Not persisted: only valid for the current session.
103    pub sent: VecDeque<(i32, Vec<u8>)>,
104}
105
106impl SecretChatState {
107    /// Create the state for a freshly established chat.
108    ///
109    /// `admin` is `true` on the initiating side; it decides the sequence-number
110    /// parity bits. The layer defaults to [`crate::dh::DEFAULT_LAYER`] until the
111    /// peer announces its own.
112    pub fn new(id: i32, access_hash: i64, auth_key: [u8; 256], admin: bool, user_id: i64) -> Self {
113        let (in_seq_no_x, out_seq_no_x) = if admin { (0, 1) } else { (1, 0) };
114        Self {
115            id,
116            access_hash,
117            auth_key,
118            admin,
119            user_id,
120            in_seq_no: 0,
121            out_seq_no: 0,
122            in_seq_no_x,
123            out_seq_no_x,
124            layer: crate::dh::DEFAULT_LAYER,
125            ttl: 0,
126            ttr: 100,
127            updated_at_secs: now_secs(),
128            mtproto: 2,
129            rekeying_state: RekeyingState::Idle,
130            temp_rekey_map: HashMap::new(),
131            sent: VecDeque::new(),
132        }
133    }
134
135    /// Wire-encoded incoming seq no: raw * 2 + x.
136    pub fn wire_in_seq_no(&self) -> i32 {
137        self.in_seq_no * 2 + self.in_seq_no_x
138    }
139
140    /// Wire-encoded outgoing seq no: raw * 2 + x.
141    pub fn wire_out_seq_no(&self) -> i32 {
142        self.out_seq_no * 2 + self.out_seq_no_x
143    }
144
145    /// Seconds since last auth_key rotation.
146    pub fn secs_since_update(&self) -> u64 {
147        now_secs().saturating_sub(self.updated_at_secs)
148    }
149
150    /// Stamp updated_at_secs to now, reset ttr, swap in the new key.
151    pub fn rotate_key(&mut self, new_key: [u8; 256]) {
152        self.auth_key = new_key;
153        self.ttr = 100;
154        self.updated_at_secs = now_secs();
155    }
156
157    /// Buffer an outgoing encrypted blob for potential Resend.
158    /// `wire_seq_no` is the wire_out_seq_no that was used when this blob was sent.
159    pub fn push_sent(&mut self, wire_seq_no: i32, blob: Vec<u8>) {
160        self.sent.push_back((wire_seq_no, blob));
161        while self.sent.len() > SENT_BUFFER_CAPACITY {
162            self.sent.pop_front();
163        }
164    }
165
166    /// Look up sent blobs in the range [start_wire, end_wire] (inclusive, step 2).
167    pub fn lookup_sent(&self, start_wire: i32, end_wire: i32) -> Vec<(i32, Vec<u8>)> {
168        self.sent
169            .iter()
170            .filter(|(seq, _)| *seq >= start_wire && *seq <= end_wire)
171            .cloned()
172            .collect()
173    }
174}
175
176/// Current Unix time in seconds (0 if the clock is before the epoch).
177pub(crate) fn now_secs() -> u64 {
178    SystemTime::now()
179        .duration_since(UNIX_EPOCH)
180        .unwrap_or_default()
181        .as_secs()
182}
183
184/// File magic of the store format.
185const STORE_MAGIC: &[u8; 6] = b"FGE2E\0";
186/// Current store format version.
187const STORE_VERSION: u8 = 1;
188/// Length of the trailing SHA-256 checksum.
189const CHECKSUM_LEN: usize = 32;
190
191fn invalid(msg: &str) -> io::Error {
192    io::Error::new(io::ErrorKind::InvalidData, format!("e2e store: {msg}"))
193}
194
195/// Bounds-checked little-endian reader over a byte slice.
196struct Reader<'a> {
197    data: &'a [u8],
198    pos: usize,
199}
200
201impl<'a> Reader<'a> {
202    fn new(data: &'a [u8]) -> Self {
203        Self { data, pos: 0 }
204    }
205
206    fn take(&mut self, n: usize) -> io::Result<&'a [u8]> {
207        let end = self.pos.checked_add(n).ok_or_else(|| invalid("overflow"))?;
208        let slice = self
209            .data
210            .get(self.pos..end)
211            .ok_or_else(|| invalid("truncated"))?;
212        self.pos = end;
213        Ok(slice)
214    }
215
216    fn u8(&mut self) -> io::Result<u8> {
217        Ok(self.take(1)?[0])
218    }
219
220    fn u32(&mut self) -> io::Result<u32> {
221        Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
222    }
223
224    fn i32(&mut self) -> io::Result<i32> {
225        Ok(i32::from_le_bytes(self.take(4)?.try_into().unwrap()))
226    }
227
228    fn i64(&mut self) -> io::Result<i64> {
229        Ok(i64::from_le_bytes(self.take(8)?.try_into().unwrap()))
230    }
231
232    fn u64(&mut self) -> io::Result<u64> {
233        Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap()))
234    }
235
236    fn remaining(&self) -> usize {
237        self.data.len() - self.pos
238    }
239}
240
241impl SecretChatState {
242    /// Append the binary record of this chat to `out`.
243    ///
244    /// Layout: `id i32, access_hash i64, auth_key [256], admin u8, user_id i64,
245    /// in_seq_no i32, out_seq_no i32, in_seq_no_x i32, out_seq_no_x i32,
246    /// layer i32, ttl i32, ttr i32, updated_at_secs u64, mtproto u8,
247    /// rekey tag u8 (0 idle, 1 requested, 2 accepted) [+ exchange_id i64],
248    /// temp_rekey_map: count u32, then (exchange_id i64, len u32, bytes)*`.
249    fn encode(&self, out: &mut Vec<u8>) {
250        out.extend_from_slice(&self.id.to_le_bytes());
251        out.extend_from_slice(&self.access_hash.to_le_bytes());
252        out.extend_from_slice(&self.auth_key);
253        out.push(self.admin as u8);
254        out.extend_from_slice(&self.user_id.to_le_bytes());
255        for v in [
256            self.in_seq_no,
257            self.out_seq_no,
258            self.in_seq_no_x,
259            self.out_seq_no_x,
260            self.layer,
261            self.ttl,
262            self.ttr,
263        ] {
264            out.extend_from_slice(&v.to_le_bytes());
265        }
266        out.extend_from_slice(&self.updated_at_secs.to_le_bytes());
267        out.push(self.mtproto);
268        match self.rekeying_state {
269            RekeyingState::Idle => out.push(0),
270            RekeyingState::Requested { exchange_id } => {
271                out.push(1);
272                out.extend_from_slice(&exchange_id.to_le_bytes());
273            }
274            RekeyingState::Accepted { exchange_id } => {
275                out.push(2);
276                out.extend_from_slice(&exchange_id.to_le_bytes());
277            }
278        }
279        out.extend_from_slice(&(self.temp_rekey_map.len() as u32).to_le_bytes());
280        for (exchange_id, bytes) in &self.temp_rekey_map {
281            out.extend_from_slice(&exchange_id.to_le_bytes());
282            out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
283            out.extend_from_slice(bytes);
284        }
285    }
286
287    /// Parse one chat record written by [`SecretChatState::encode`].
288    fn decode(r: &mut Reader<'_>) -> io::Result<Self> {
289        let id = r.i32()?;
290        let access_hash = r.i64()?;
291        let mut auth_key = [0u8; 256];
292        auth_key.copy_from_slice(r.take(256)?);
293        let admin = match r.u8()? {
294            0 => false,
295            1 => true,
296            _ => return Err(invalid("bad admin flag")),
297        };
298        let user_id = r.i64()?;
299        let in_seq_no = r.i32()?;
300        let out_seq_no = r.i32()?;
301        let in_seq_no_x = r.i32()?;
302        let out_seq_no_x = r.i32()?;
303        let layer = r.i32()?;
304        let ttl = r.i32()?;
305        let ttr = r.i32()?;
306        let updated_at_secs = r.u64()?;
307        let mtproto = r.u8()?;
308        let rekeying_state = match r.u8()? {
309            0 => RekeyingState::Idle,
310            1 => RekeyingState::Requested {
311                exchange_id: r.i64()?,
312            },
313            2 => RekeyingState::Accepted {
314                exchange_id: r.i64()?,
315            },
316            _ => return Err(invalid("bad rekey state")),
317        };
318        let map_len = r.u32()? as usize;
319        // Each entry is at least 12 bytes; reject counts the file cannot hold.
320        if map_len > r.remaining() / 12 {
321            return Err(invalid("bad rekey map length"));
322        }
323        let mut temp_rekey_map = HashMap::with_capacity(map_len);
324        for _ in 0..map_len {
325            let exchange_id = r.i64()?;
326            let len = r.u32()? as usize;
327            temp_rekey_map.insert(exchange_id, r.take(len)?.to_vec());
328        }
329        Ok(Self {
330            id,
331            access_hash,
332            auth_key,
333            admin,
334            user_id,
335            in_seq_no,
336            out_seq_no,
337            in_seq_no_x,
338            out_seq_no_x,
339            layer,
340            ttl,
341            ttr,
342            updated_at_secs,
343            mtproto,
344            rekeying_state,
345            temp_rekey_map,
346            sent: VecDeque::new(),
347        })
348    }
349}
350
351/// Default store path for a session: the session path with its extension
352/// replaced by `e2e` (`mybot.session` becomes `mybot.e2e`, `mybot` becomes `mybot.e2e`).
353pub fn store_path_for_session(session: impl AsRef<Path>) -> PathBuf {
354    session.as_ref().with_extension("e2e")
355}
356
357/// Temporary state held while waiting for the peer to accept (User A side).
358#[derive(Debug)]
359pub struct TempChatState {
360    /// Secret chat id this exchange belongs to.
361    pub id: i32,
362    /// The 256-byte private exponent `a` used to compute the shared secret.
363    pub private_key_a: [u8; 256],
364}
365
366/// In-memory store for established and pending secret chats.
367///
368/// When a path is set (see [`ChatStore::load`]), `insert` and `remove` flush all
369/// established chats to that binary file. Pending exchanges are never persisted.
370#[derive(Default)]
371pub struct ChatStore {
372    chats: HashMap<i32, SecretChatState>,
373    pending: HashMap<i32, TempChatState>,
374    path: Option<PathBuf>,
375}
376
377impl ChatStore {
378    /// Create an empty in-memory store.
379    pub fn new() -> Self {
380        Self::default()
381    }
382
383    /// Load the store from `path`, or start empty if the file doesn't exist yet.
384    ///
385    /// Fails with `InvalidData` if the file has the wrong magic or version, is
386    /// truncated, or does not match its checksum. Later changes are written back
387    /// to `path`.
388    pub fn load(path: PathBuf) -> io::Result<Self> {
389        let chats = match std::fs::read(&path) {
390            Ok(data) => Self::decode_store(&data)?,
391            Err(e) if e.kind() == io::ErrorKind::NotFound => HashMap::new(),
392            Err(e) => return Err(e),
393        };
394        Ok(Self {
395            chats,
396            pending: HashMap::new(),
397            path: Some(path),
398        })
399    }
400
401    fn decode_store(data: &[u8]) -> io::Result<HashMap<i32, SecretChatState>> {
402        if data.len() < STORE_MAGIC.len() + 1 + 4 + CHECKSUM_LEN {
403            return Err(invalid("file too short"));
404        }
405        let (body, checksum) = data.split_at(data.len() - CHECKSUM_LEN);
406        if Sha256::digest(body).as_slice() != checksum {
407            return Err(invalid("checksum mismatch (file is corrupt)"));
408        }
409        let mut r = Reader::new(body);
410        if r.take(STORE_MAGIC.len())? != STORE_MAGIC {
411            return Err(invalid("not an e2e store file"));
412        }
413        let version = r.u8()?;
414        if version != STORE_VERSION {
415            return Err(invalid(&format!("unsupported version {version}")));
416        }
417        let count = r.u32()? as usize;
418        let mut chats = HashMap::new();
419        for _ in 0..count {
420            let chat = SecretChatState::decode(&mut r)?;
421            chats.insert(chat.id, chat);
422        }
423        if r.remaining() != 0 {
424            return Err(invalid("trailing bytes"));
425        }
426        Ok(chats)
427    }
428
429    fn encode_store(&self) -> Vec<u8> {
430        let mut out = Vec::with_capacity(64 + self.chats.len() * 400);
431        out.extend_from_slice(STORE_MAGIC);
432        out.push(STORE_VERSION);
433        out.extend_from_slice(&(self.chats.len() as u32).to_le_bytes());
434        for chat in self.chats.values() {
435            chat.encode(&mut out);
436        }
437        let checksum = Sha256::digest(&out);
438        out.extend_from_slice(&checksum);
439        out
440    }
441
442    /// Write all established chats to the configured path, atomically.
443    ///
444    /// The data goes to a temporary file next to the target, is synced, and then
445    /// renamed over it, so a crash never leaves a half-written store. Does
446    /// nothing if no path is set.
447    pub fn try_save(&self) -> io::Result<()> {
448        let Some(path) = &self.path else {
449            return Ok(());
450        };
451        let tmp = path.with_extension("e2e.tmp");
452        let mut opts = std::fs::OpenOptions::new();
453        opts.write(true).create(true).truncate(true);
454        #[cfg(unix)]
455        {
456            use std::os::unix::fs::OpenOptionsExt;
457            opts.mode(0o600);
458        }
459        let result = (|| {
460            let mut f = opts.open(&tmp)?;
461            f.write_all(&self.encode_store())?;
462            f.sync_all()?;
463            std::fs::rename(&tmp, path)
464        })();
465        if result.is_err() {
466            let _ = std::fs::remove_file(&tmp);
467        }
468        result
469    }
470
471    /// Like [`ChatStore::try_save`], but only logs a warning on failure.
472    pub fn save(&self) {
473        if let Err(e) = self.try_save() {
474            tracing::warn!("e2e: failed to persist secret chats: {e}");
475        }
476    }
477
478    /// Add an established chat; fails with `ChatAlreadyExists` if the id is taken.
479    pub fn insert(&mut self, state: SecretChatState) -> Result<(), E2eError> {
480        if self.chats.contains_key(&state.id) {
481            return Err(E2eError::ChatAlreadyExists(state.id));
482        }
483        self.chats.insert(state.id, state);
484        self.save();
485        Ok(())
486    }
487
488    /// Look up an established chat.
489    pub fn get(&self, id: i32) -> Result<&SecretChatState, E2eError> {
490        self.chats.get(&id).ok_or(E2eError::ChatNotFound(id))
491    }
492
493    /// Look up an established chat for modification.
494    ///
495    /// Changes are not written to disk until [`ChatStore::save`] is called.
496    pub fn get_mut(&mut self, id: i32) -> Result<&mut SecretChatState, E2eError> {
497        self.chats.get_mut(&id).ok_or(E2eError::ChatNotFound(id))
498    }
499
500    /// Forget a chat and any pending exchange for it.
501    pub fn remove(&mut self, id: i32) {
502        self.chats.remove(&id);
503        self.pending.remove(&id);
504        self.save();
505    }
506
507    /// Remember the private exponent of an outgoing request until the peer accepts.
508    pub fn insert_pending(&mut self, state: TempChatState) {
509        self.pending.insert(state.id, state);
510    }
511
512    /// Take (and remove) the pending exchange for `id`, if any.
513    pub fn take_pending(&mut self, id: i32) -> Option<TempChatState> {
514        self.pending.remove(&id)
515    }
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521
522    fn chat(id: i32) -> SecretChatState {
523        let mut key = [0u8; 256];
524        for (i, b) in key.iter_mut().enumerate() {
525            *b = (i as u8).wrapping_mul(31).wrapping_add(id as u8);
526        }
527        let mut c = SecretChatState::new(id, 0x1122_3344_5566_7788, key, id % 2 == 0, 4242);
528        c.in_seq_no = 5;
529        c.out_seq_no = 9;
530        c.ttl = 60;
531        c.ttr = 77;
532        c.layer = 143;
533        c.updated_at_secs = 1_700_000_000;
534        c
535    }
536
537    fn store_at(dir: &tempfile::TempDir) -> (ChatStore, PathBuf) {
538        let path = dir.path().join("test.e2e");
539        (ChatStore::load(path.clone()).unwrap(), path)
540    }
541
542    #[test]
543    fn round_trip_all_fields() {
544        let dir = tempfile::tempdir().unwrap();
545        let (mut store, path) = store_at(&dir);
546
547        let mut a = chat(1);
548        a.rekeying_state = RekeyingState::Requested { exchange_id: -7 };
549        a.temp_rekey_map.insert(-7, vec![9u8; 256]);
550        let mut b = chat(2);
551        b.rekeying_state = RekeyingState::Accepted { exchange_id: 55 };
552        b.temp_rekey_map.insert(55, vec![1u8; 256]);
553        let c = chat(3);
554        for s in [a, b, c] {
555            store.insert(s).unwrap();
556        }
557
558        let loaded = ChatStore::load(path).unwrap();
559        for id in 1..=3 {
560            let (x, y) = (store.get(id).unwrap(), loaded.get(id).unwrap());
561            assert_eq!(x.access_hash, y.access_hash);
562            assert_eq!(x.auth_key, y.auth_key);
563            assert_eq!(x.admin, y.admin);
564            assert_eq!(x.user_id, y.user_id);
565            assert_eq!(
566                (x.in_seq_no, x.out_seq_no, x.in_seq_no_x, x.out_seq_no_x),
567                (y.in_seq_no, y.out_seq_no, y.in_seq_no_x, y.out_seq_no_x)
568            );
569            assert_eq!((x.layer, x.ttl, x.ttr), (y.layer, y.ttl, y.ttr));
570            assert_eq!(x.updated_at_secs, y.updated_at_secs);
571            assert_eq!(x.mtproto, y.mtproto);
572            assert_eq!(x.temp_rekey_map, y.temp_rekey_map);
573            assert_eq!(
574                format!("{:?}", x.rekeying_state),
575                format!("{:?}", y.rekeying_state)
576            );
577        }
578    }
579
580    #[test]
581    fn remove_is_persisted() {
582        let dir = tempfile::tempdir().unwrap();
583        let (mut store, path) = store_at(&dir);
584        store.insert(chat(1)).unwrap();
585        store.insert(chat(2)).unwrap();
586        store.remove(1);
587        let loaded = ChatStore::load(path).unwrap();
588        assert!(loaded.get(1).is_err());
589        assert!(loaded.get(2).is_ok());
590    }
591
592    #[test]
593    fn missing_file_is_an_empty_store() {
594        let dir = tempfile::tempdir().unwrap();
595        let store = ChatStore::load(dir.path().join("nothing.e2e")).unwrap();
596        assert!(store.get(1).is_err());
597    }
598
599    #[test]
600    fn corruption_is_detected() {
601        let dir = tempfile::tempdir().unwrap();
602        let (mut store, path) = store_at(&dir);
603        store.insert(chat(1)).unwrap();
604
605        let mut data = std::fs::read(&path).unwrap();
606        data[40] ^= 1;
607        std::fs::write(&path, &data).unwrap();
608        let err = ChatStore::load(path.clone()).err().unwrap();
609        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
610
611        std::fs::write(&path, &data[..data.len() - 5]).unwrap();
612        assert!(ChatStore::load(path.clone()).is_err());
613
614        std::fs::write(&path, b"short").unwrap();
615        assert!(ChatStore::load(path).is_err());
616    }
617
618    #[test]
619    fn wrong_magic_and_version_are_rejected() {
620        let dir = tempfile::tempdir().unwrap();
621        let (mut store, path) = store_at(&dir);
622        store.insert(chat(1)).unwrap();
623        let good = std::fs::read(&path).unwrap();
624
625        // Re-seal the file with a changed header so only the header check can fail.
626        let reseal = |mut body: Vec<u8>| {
627            body.truncate(body.len() - CHECKSUM_LEN);
628            let sum = Sha256::digest(&body);
629            body.extend_from_slice(&sum);
630            body
631        };
632        let mut bad_magic = good.clone();
633        bad_magic[0] = b'X';
634        std::fs::write(&path, reseal(bad_magic)).unwrap();
635        assert!(ChatStore::load(path.clone()).is_err());
636
637        let mut bad_version = good;
638        bad_version[STORE_MAGIC.len()] = 99;
639        std::fs::write(&path, reseal(bad_version)).unwrap();
640        assert!(ChatStore::load(path).is_err());
641    }
642
643    #[test]
644    fn save_leaves_no_temp_file() {
645        let dir = tempfile::tempdir().unwrap();
646        let (mut store, _) = store_at(&dir);
647        store.insert(chat(1)).unwrap();
648        let names: Vec<_> = std::fs::read_dir(dir.path())
649            .unwrap()
650            .map(|e| e.unwrap().file_name())
651            .collect();
652        assert_eq!(names.len(), 1, "unexpected files: {names:?}");
653    }
654
655    #[cfg(unix)]
656    #[test]
657    fn store_file_is_private() {
658        use std::os::unix::fs::PermissionsExt;
659        let dir = tempfile::tempdir().unwrap();
660        let (mut store, path) = store_at(&dir);
661        store.insert(chat(1)).unwrap();
662        let mode = std::fs::metadata(path).unwrap().permissions().mode();
663        assert_eq!(mode & 0o777, 0o600);
664    }
665
666    #[test]
667    fn session_path_maps_to_e2e() {
668        assert_eq!(
669            store_path_for_session("mybot.session"),
670            PathBuf::from("mybot.e2e")
671        );
672        assert_eq!(store_path_for_session("mybot"), PathBuf::from("mybot.e2e"));
673        assert_eq!(
674            store_path_for_session("/data/x/hello.session"),
675            PathBuf::from("/data/x/hello.e2e")
676        );
677    }
678}