Skip to main content

agentmux_srv/server/
local_session_file.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The file that keeps a headless srv's browser sessions across a restart (`sessions.bin`, in the data root).
5//! docs/specs/SPEC_WINDOWS_HEADLESS_AS_A_SERVICE_2026_11_20.md D.2.
6//!
7//! What it holds: for each live session the SHA-256 of its cookie and of its per-tab token (the same digests the store keeps
8//! in memory, never a cookie or a token), when it was confirmed and when it was last used, as wall-clock seconds. One-time
9//! codes and pending sessions are never written. The file is written by a temp file and a rename, owner-only, when a session is
10//! confirmed or ended and (at most every [`SAVE_EVERY`]) when one is used.
11//!
12//! What it refuses: a file that cannot be trusted is ignored, every session in it is cleared, and the reason is logged once
13//! (never a digest). That is a file whose folder or own access list lets anyone but the owner, the system and the
14//! administrators open it, one that is truncated, has extra bytes, does not parse or fails its check value, one saved at a time
15//! after now (the clock has moved back, so the time that has passed is unknown), one with a time that cannot be (a session
16//! used before it was confirmed, or after the file was saved), and one made under a different sign-in key when the key is one
17//! the person provided. A key srv generated is new at every start, so a session cannot depend on it: the check value of such a
18//! file is a plain SHA-256, and of a file made under a provided key an HMAC under that key.
19
20use std::path::{Path, PathBuf};
21use std::time::Duration;
22
23use hmac::{Hmac, Mac};
24use sha2::{Digest, Sha256};
25
26pub(crate) type Digest32 = [u8; 32];
27
28/// The file's name in the data root.
29pub(crate) const FILE_NAME: &str = "sessions.bin";
30/// A use of a session is written at most this often; the saved time of last use is then at most this stale, which makes a
31/// session older after a restart, never younger.
32pub(crate) const SAVE_EVERY: Duration = Duration::from_secs(5 * 60);
33
34const MAGIC: &[u8; 8] = b"AMXSESS1";
35const HEADER_LEN: usize = 8 + 1 + 8 + 4;
36const RECORD_LEN: usize = 32 + 32 + 8 + 8;
37const TRAILER_LEN: usize = 32;
38/// Most sessions the file holds or accepts.
39pub(crate) const MAX_SESSIONS: usize = 4096;
40
41/// What the file is bound to: nothing (the key was generated at this start), or the key the person provided.
42#[derive(Clone)]
43pub(crate) enum KeyBinding {
44    Generated,
45    Provided(Vec<u8>),
46}
47
48impl KeyBinding {
49    fn mode(&self) -> u8 {
50        match self {
51            KeyBinding::Generated => 0,
52            KeyBinding::Provided(_) => 1,
53        }
54    }
55
56    fn check(&self, body: &[u8]) -> Digest32 {
57        match self {
58            KeyBinding::Generated => Sha256::digest(body).into(),
59            KeyBinding::Provided(key) => {
60                let mut m = Hmac::<Sha256>::new_from_slice(key).expect("hmac takes any key length");
61                m.update(b"amx-sessions-file-v1");
62                m.update(body);
63                m.finalize().into_bytes().into()
64            }
65        }
66    }
67}
68
69/// One saved session: the digests and the wall-clock seconds of its confirmation and last use.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub(crate) struct Record {
72    pub cookie: Digest32,
73    pub token: Digest32,
74    pub born_secs: u64,
75    pub last_seen_secs: u64,
76}
77
78/// Why the file was not used. A fixed text: it names no value from the file.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub(crate) enum Refused {
81    /// Someone besides the owner, the system and the administrators can open the file or its folder (or it could not be asked).
82    TooOpen,
83    /// Truncated, too long, not this format or its check value does not match (also: the file was made under a provided key
84    /// and the key now is another, or the other way round).
85    Damaged,
86    /// Saved at a time after now: the clock has moved back.
87    ClockMovedBack,
88    /// A time in it that cannot be.
89    Inconsistent,
90}
91
92impl Refused {
93    pub(crate) fn why(self) -> &'static str {
94        match self {
95            Refused::TooOpen => "the file or its folder can be opened by someone else",
96            Refused::Damaged => "the file is damaged, or the sign-in key it was made under has changed",
97            Refused::ClockMovedBack => "the clock is earlier than when the file was saved",
98            Refused::Inconsistent => "the file holds a time that cannot be",
99        }
100    }
101}
102
103/// The bytes of a file of `records`, saved at `saved_secs`.
104pub(crate) fn encode(binding: &KeyBinding, saved_secs: u64, records: &[Record]) -> Vec<u8> {
105    let records = &records[..records.len().min(MAX_SESSIONS)];
106    let mut out = Vec::with_capacity(HEADER_LEN + records.len() * RECORD_LEN + TRAILER_LEN);
107    out.extend_from_slice(MAGIC);
108    out.push(binding.mode());
109    out.extend_from_slice(&saved_secs.to_be_bytes());
110    out.extend_from_slice(&(records.len() as u32).to_be_bytes());
111    for r in records {
112        out.extend_from_slice(&r.cookie);
113        out.extend_from_slice(&r.token);
114        out.extend_from_slice(&r.born_secs.to_be_bytes());
115        out.extend_from_slice(&r.last_seen_secs.to_be_bytes());
116    }
117    let check = binding.check(&out);
118    out.extend_from_slice(&check);
119    out
120}
121
122/// The sessions in `bytes`, if it is a whole file made under `binding` and saved at or before `now_secs`.
123pub(crate) fn decode(binding: &KeyBinding, now_secs: u64, bytes: &[u8]) -> Result<Vec<Record>, Refused> {
124    if bytes.len() < HEADER_LEN + TRAILER_LEN || &bytes[..8] != MAGIC {
125        return Err(Refused::Damaged);
126    }
127    let count = u32::from_be_bytes(bytes[17..21].try_into().expect("four bytes")) as usize;
128    if count > MAX_SESSIONS || bytes.len() != HEADER_LEN + count * RECORD_LEN + TRAILER_LEN {
129        return Err(Refused::Damaged);
130    }
131    let (body, trailer) = bytes.split_at(bytes.len() - TRAILER_LEN);
132    if bytes[8] != binding.mode() || !agentmux_common::secret_eq::secret_eq(&binding.check(body), trailer) {
133        return Err(Refused::Damaged);
134    }
135    let saved = u64::from_be_bytes(bytes[9..17].try_into().expect("eight bytes"));
136    if saved > now_secs {
137        return Err(Refused::ClockMovedBack);
138    }
139    let mut out = Vec::with_capacity(count);
140    for chunk in body[HEADER_LEN..].chunks_exact(RECORD_LEN) {
141        let r = Record {
142            cookie: chunk[..32].try_into().expect("32 bytes"),
143            token: chunk[32..64].try_into().expect("32 bytes"),
144            born_secs: u64::from_be_bytes(chunk[64..72].try_into().expect("eight bytes")),
145            last_seen_secs: u64::from_be_bytes(chunk[72..80].try_into().expect("eight bytes")),
146        };
147        if r.born_secs > r.last_seen_secs || r.last_seen_secs > saved {
148            return Err(Refused::Inconsistent);
149        }
150        out.push(r);
151    }
152    Ok(out)
153}
154
155/// Whether the file and its folder can be opened by nobody but the owner, the system and the administrators. A failure to
156/// find out is a refusal.
157pub(crate) fn private_enough(path: &Path) -> Result<(), Refused> {
158    #[cfg(windows)]
159    {
160        let folder = path.parent().ok_or(Refused::TooOpen)?;
161        for p in [path, folder] {
162            match agentmux_common::owner_only::others_who_can_open(p) {
163                Ok(others) if others.is_empty() => {}
164                _ => return Err(Refused::TooOpen),
165            }
166        }
167        Ok(())
168    }
169    #[cfg(unix)]
170    {
171        use std::os::unix::fs::PermissionsExt;
172        let file = std::fs::metadata(path).map_err(|_| Refused::TooOpen)?;
173        let folder = std::fs::metadata(path.parent().ok_or(Refused::TooOpen)?).map_err(|_| Refused::TooOpen)?;
174        // The file is the owner's alone; the folder may not be written by anyone else.
175        if file.permissions().mode() & 0o077 != 0 || folder.permissions().mode() & 0o022 != 0 {
176            return Err(Refused::TooOpen);
177        }
178        Ok(())
179    }
180}
181
182/// Read the file: `Ok(None)` when there is none, the sessions when it can be trusted. On any refusal the file is deleted, so
183/// a later start does not meet it again.
184pub(crate) fn load(path: &Path, binding: &KeyBinding, now_secs: u64) -> Result<Option<Vec<Record>>, Refused> {
185    let bytes = match std::fs::read(path) {
186        Ok(b) => b,
187        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
188        Err(_) => {
189            let _ = clear(path, binding, now_secs);
190            return Err(Refused::TooOpen);
191        }
192    };
193    let result = private_enough(path).and_then(|()| decode(binding, now_secs, &bytes));
194    if result.is_err() {
195        let _ = clear(path, binding, now_secs);
196    }
197    result.map(Some)
198}
199
200/// Write the file: a temp file in the same folder (owner-only before it holds anything on unix, and with its list set on
201/// Windows) and a rename over the old one.
202pub(crate) fn save(path: &Path, binding: &KeyBinding, saved_secs: u64, records: &[Record]) -> std::io::Result<()> {
203    let folder = path.parent().ok_or_else(|| std::io::Error::other("the sessions file has no folder"))?;
204    let mut tmp: PathBuf = folder.to_path_buf();
205    tmp.push(format!(".{FILE_NAME}.{}.tmp", std::process::id()));
206    let _ = std::fs::remove_file(&tmp);
207    let mut opts = std::fs::OpenOptions::new();
208    opts.write(true).create_new(true);
209    #[cfg(unix)]
210    {
211        use std::os::unix::fs::OpenOptionsExt;
212        opts.mode(0o600);
213    }
214    use std::io::Write;
215    let written = opts.open(&tmp).and_then(|mut f| {
216        f.write_all(&encode(binding, saved_secs, records))?;
217        f.sync_all()
218    });
219    #[cfg(windows)]
220    let written = written.and_then(|()| agentmux_common::owner_only::restrict_to_user(&tmp).map_err(std::io::Error::other));
221    let renamed = written.and_then(|()| std::fs::rename(&tmp, path));
222    if renamed.is_err() {
223        let _ = std::fs::remove_file(&tmp);
224    }
225    renamed
226}
227
228/// Delete the file (a logout, or a refusal). Nothing is wrong if it is not there. When it cannot be deleted (a sharing
229/// violation, a scanner holding it) it is replaced by a file with no sessions; only when that fails too is the error returned,
230/// and the file, with whatever sessions it holds, is still there.
231pub(crate) fn clear(path: &Path, binding: &KeyBinding, now_secs: u64) -> std::io::Result<()> {
232    match std::fs::remove_file(path) {
233        Ok(()) => Ok(()),
234        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
235        Err(_) => save(path, binding, now_secs, &[]),
236    }
237}
238
239#[cfg(test)]
240#[path = "tests/local_session_file_tests.rs"]
241mod tests;