Skip to main content

surjection_core/apply/
ledger.rs

1//! The ownership ledger `state/ledger.json` (SPEC 8.1): every native entry
2//! Surjection wrote or adopted on this machine, with a keyed hash of what was
3//! written. It is the only definition of ownership, machine-local and never
4//! versioned.
5
6use std::collections::{HashMap, HashSet};
7use std::fmt;
8use std::path::Path;
9
10use hmac::{Hmac, KeyInit, Mac};
11use serde::{Deserialize, Serialize};
12use sha2::Sha256;
13
14use crate::adapters::mapper::Canonical;
15use crate::apply::write_atomic;
16use crate::error::{CoreError, ErrorCode};
17use crate::fs::Fs;
18use crate::model::applied::Scope;
19
20/// Ledger file in `state/`.
21pub const LEDGER_FILE: &str = "ledger.json";
22/// HMAC key file in `state/` (32 random bytes, user-only permissions).
23pub const LEDGER_KEY_FILE: &str = "ledger.key";
24
25/// 2 since Surjection 1.1.0 (no change in the file; see `versions`).
26pub(crate) const LEDGER_SCHEMA: u32 = 2;
27const HASH_PREFIX: &str = "hmac-sha256:";
28const KEY_LEN: usize = 32;
29
30/// What a ledger entry owns.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum EntryKind {
34    /// A server entry in a container (`mcpServers.github`).
35    McpEntry,
36    /// A string member of a list (`disabledMcpServers` holding `slack`).
37    ListMember,
38}
39
40/// How an entry came to be owned.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Origin {
44    /// Surjection wrote a new entry.
45    Created,
46    /// A pre-existing entry the user handed to Surjection (or an identical one
47    /// adopted silently).
48    Adopted,
49}
50
51/// One owned item.
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53pub struct LedgerEntry {
54    pub kind: EntryKind,
55    pub client: String,
56    pub scope: Scope,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub project_id: Option<String>,
59    /// The native file, absolute, as resolved on this machine.
60    pub file: String,
61    /// JSON pointer of the container or list (`/mcpServers`), see
62    /// [`container_pointer`].
63    pub container: String,
64    /// The entry key, or the list member.
65    pub key: String,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub server_id: Option<String>,
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub origin: Option<Origin>,
70    /// `hmac-sha256:<hex>` over the mapper's canonical form of what was
71    /// written ([`LedgerKey::hash`]).
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub written_hash: Option<String>,
74    /// RFC 3339, UTC.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub written_at: Option<String>,
77    /// Abbreviated store commit the entry was written from.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub store_commit: Option<String>,
80    /// Delivery mode of the references in the entry (`env`), if any.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub delivery: Option<String>,
83    /// Keys a newer build wrote, kept on rewrite.
84    #[serde(flatten)]
85    pub extra: serde_json::Map<String, serde_json::Value>,
86}
87
88impl LedgerEntry {
89    /// The container this entry is owned in.
90    pub fn slot(&self) -> LedgerSlot<'_> {
91        LedgerSlot {
92            scope: self.scope,
93            project_id: self.project_id.as_deref(),
94            file: &self.file,
95            container: &self.container,
96        }
97    }
98
99    fn is(&self, slot: &LedgerSlot<'_>, key: &str) -> bool {
100        self.slot() == *slot && self.key == key
101    }
102}
103
104/// Where owned entries live: one container (or list) of one file, in one
105/// scope and project (SPEC 8.1, decision 10 of M9). Two projects, or a
106/// project and the user scope, never own each other's entries, even in
107/// the same file and container.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct LedgerSlot<'a> {
110    pub scope: Scope,
111    pub project_id: Option<&'a str>,
112    pub file: &'a str,
113    /// [`container_pointer`] of the container.
114    pub container: &'a str,
115}
116
117/// `state/ledger.json`.
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119pub struct Ledger {
120    pub schema: u32,
121    #[serde(default)]
122    pub entries: Vec<LedgerEntry>,
123    #[serde(flatten)]
124    pub extra: serde_json::Map<String, serde_json::Value>,
125}
126
127impl Default for Ledger {
128    fn default() -> Self {
129        Self {
130            schema: LEDGER_SCHEMA,
131            entries: Vec::new(),
132            extra: serde_json::Map::new(),
133        }
134    }
135}
136
137impl Ledger {
138    /// Reads the ledger in `state_dir`; an absent file is an empty ledger.
139    /// A ledger that does not parse is an error, never an empty ledger:
140    /// losing it would turn owned entries into foreign ones.
141    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
142        let path = state_dir.join(LEDGER_FILE);
143        if !fs.exists(&path) {
144            return Ok(Self::default());
145        }
146        let text = fs.read_to_string(&path).map_err(|err| {
147            CoreError::new(ErrorCode::IoError, format!("cannot read the ledger: {err}"))
148                .with_path(&path)
149        })?;
150        let mut ledger: Self = serde_json::from_str(&text).map_err(|err| {
151            CoreError::new(
152                ErrorCode::ParseError,
153                format!("the ledger does not parse: {err}"),
154            )
155            .with_path(&path)
156        })?;
157        // Schema 1 (Loadout 1.0.x) differs only in the number: read as is,
158        // and written back at the current one.
159        if !(1..=LEDGER_SCHEMA).contains(&ledger.schema) {
160            return Err(CoreError::new(
161                ErrorCode::UnsupportedSchema,
162                format!(
163                    "ledger schema {} is not supported; this build reads schema {LEDGER_SCHEMA}",
164                    ledger.schema
165                ),
166            )
167            .with_path(&path));
168        }
169        ledger.schema = LEDGER_SCHEMA;
170        Ok(ledger)
171    }
172
173    /// Writes the ledger atomically (temp file, then replace).
174    pub fn save(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
175        let mut text = serde_json::to_string_pretty(self).map_err(|err| {
176            CoreError::new(
177                ErrorCode::InvalidValue,
178                format!("cannot serialize the ledger: {err}"),
179            )
180        })?;
181        text.push('\n');
182        write_atomic(fs, &state_dir.join(LEDGER_FILE), text.as_bytes())
183    }
184
185    pub fn get(&self, slot: &LedgerSlot<'_>, key: &str) -> Option<&LedgerEntry> {
186        self.entries.iter().find(|entry| entry.is(slot, key))
187    }
188
189    /// Entries of one slot.
190    pub fn in_container<'a>(
191        &'a self,
192        slot: LedgerSlot<'a>,
193    ) -> impl Iterator<Item = &'a LedgerEntry> + 'a {
194        self.entries
195            .iter()
196            .filter(move |entry| entry.slot() == slot)
197    }
198
199    /// Replaces the entry with the same slot and key, or appends.
200    pub fn upsert(&mut self, entry: LedgerEntry) {
201        match self
202            .entries
203            .iter_mut()
204            .find(|known| known.slot() == entry.slot() && known.key == entry.key)
205        {
206            Some(slot) => *slot = entry,
207            None => self.entries.push(entry),
208        }
209    }
210
211    /// Drops the entry; returns whether it was there.
212    pub fn remove(&mut self, slot: &LedgerSlot<'_>, key: &str) -> bool {
213        let before = self.entries.len();
214        self.entries.retain(|entry| !entry.is(slot, key));
215        self.entries.len() != before
216    }
217
218    /// The entries of `slot`, from one pass over the ledger: what
219    /// [`Ledger::in_container`] and [`Ledger::get`] give for that slot,
220    /// without a pass per lookup (#14).
221    pub fn slot_entries(&self, slot: &LedgerSlot<'_>) -> SlotEntries<'_> {
222        let entries: Vec<&LedgerEntry> = self
223            .entries
224            .iter()
225            .filter(|entry| entry.slot() == *slot)
226            .collect();
227        let mut by_key = HashMap::with_capacity(entries.len());
228        for entry in &entries {
229            by_key.entry(entry.key.as_str()).or_insert(*entry);
230        }
231        SlotEntries { entries, by_key }
232    }
233
234    /// Applies `changes` to the entries of `slot` in one pass over the
235    /// ledger: what [`Ledger::upsert`] (`Some`) and [`Ledger::remove`]
236    /// (`None`) do called one after the other, with the same result. Returns
237    /// whether anything changed.
238    pub fn update_slot(
239        &mut self,
240        slot: &LedgerSlot<'_>,
241        changes: Vec<(String, Option<LedgerEntry>)>,
242    ) -> bool {
243        // Where the slot's entries of each key are, first one first.
244        let mut at: HashMap<String, Vec<usize>> = HashMap::new();
245        for (index, entry) in self.entries.iter().enumerate() {
246            if entry.slot() == *slot {
247                at.entry(entry.key.clone()).or_default().push(index);
248            }
249        }
250        let mut dropped: HashSet<usize> = HashSet::new();
251        let mut changed = false;
252        for (key, change) in changes {
253            match change {
254                Some(entry) => {
255                    debug_assert!(entry.slot() == *slot && entry.key == key);
256                    match at.get(&key).and_then(|indices| indices.first()) {
257                        Some(&index) => self.entries[index] = entry,
258                        None => {
259                            at.insert(key, vec![self.entries.len()]);
260                            self.entries.push(entry);
261                        }
262                    }
263                    changed = true;
264                }
265                None => {
266                    if let Some(indices) = at.remove(&key) {
267                        changed = true;
268                        dropped.extend(indices);
269                    }
270                }
271            }
272        }
273        if !dropped.is_empty() {
274            let mut index = 0;
275            self.entries.retain(|_| {
276                index += 1;
277                !dropped.contains(&(index - 1))
278            });
279        }
280        changed
281    }
282}
283
284/// [`Ledger::slot_entries`].
285#[derive(Debug)]
286pub struct SlotEntries<'a> {
287    entries: Vec<&'a LedgerEntry>,
288    by_key: HashMap<&'a str, &'a LedgerEntry>,
289}
290
291impl<'a> SlotEntries<'a> {
292    /// [`Ledger::get`] for the slot.
293    pub fn get(&self, key: &str) -> Option<&'a LedgerEntry> {
294        self.by_key.get(key).copied()
295    }
296
297    /// [`Ledger::in_container`] for the slot, in ledger order.
298    pub fn iter(&self) -> impl Iterator<Item = &'a LedgerEntry> + '_ {
299        self.entries.iter().copied()
300    }
301}
302
303/// The HMAC-SHA256 key of ledger hashes (`state/ledger.key`). Keyed because
304/// an inline-delivered entry holds secret values: a plain hash would let
305/// anyone with the ledger test guesses offline.
306#[derive(Clone)]
307pub struct LedgerKey([u8; KEY_LEN]);
308
309impl fmt::Debug for LedgerKey {
310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        f.write_str("LedgerKey(..)")
312    }
313}
314
315impl LedgerKey {
316    /// Reads the key in `state_dir`; `None` when there is none yet. A key
317    /// of the wrong length is `invalid_value`; it is never replaced
318    /// silently, since every hash in the ledger depends on it.
319    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Self>, CoreError> {
320        let path = state_dir.join(LEDGER_KEY_FILE);
321        if !fs.exists(&path) {
322            return Ok(None);
323        }
324        let bytes = fs.read(&path).map_err(|err| {
325            CoreError::new(
326                ErrorCode::IoError,
327                format!("cannot read the ledger key: {err}"),
328            )
329            .with_path(&path)
330        })?;
331        let key: [u8; KEY_LEN] = bytes.try_into().map_err(|_| {
332            CoreError::new(
333                ErrorCode::InvalidValue,
334                format!("the ledger key must be {KEY_LEN} bytes"),
335            )
336            .with_path(&path)
337        })?;
338        Ok(Some(Self(key)))
339    }
340
341    /// [`LedgerKey::load`], creating 32 random bytes with user-only
342    /// permissions on first use.
343    pub fn load_or_create(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
344        if let Some(key) = Self::load(fs, state_dir)? {
345            return Ok(key);
346        }
347        let path = state_dir.join(LEDGER_KEY_FILE);
348        let mut key = [0u8; KEY_LEN];
349        getrandom::fill(&mut key).map_err(|err| {
350            CoreError::new(
351                ErrorCode::IoError,
352                format!("cannot read random bytes for the ledger key: {err}"),
353            )
354        })?;
355        fs.create_dir_all(state_dir).map_err(|err| {
356            CoreError::new(
357                ErrorCode::IoError,
358                format!("cannot create directory: {err}"),
359            )
360            .with_path(state_dir)
361        })?;
362        fs.write_private(&path, &key).map_err(|err| {
363            CoreError::new(
364                ErrorCode::IoError,
365                format!("cannot write the ledger key: {err}"),
366            )
367            .with_path(&path)
368        })?;
369        Ok(Self(key))
370    }
371
372    /// A key for tests and tools that never persist hashes.
373    pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self {
374        Self(bytes)
375    }
376
377    /// `hmac-sha256:<hex>` of a canonical form.
378    pub fn hash(&self, canonical: &Canonical) -> String {
379        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&self.0)
380            .expect("HMAC accepts any key length");
381        mac.update(canonical.as_str().as_bytes());
382        let digest = mac.finalize().into_bytes();
383        let mut text = String::with_capacity(HASH_PREFIX.len() + digest.len() * 2);
384        text.push_str(HASH_PREFIX);
385        for byte in digest {
386            text.push_str(&format!("{byte:02x}"));
387        }
388        text
389    }
390}
391
392/// RFC 6901 JSON pointer of a key path: `/mcpServers`,
393/// `/projects/C:~1code~1app/mcpServers`.
394pub fn container_pointer<S: AsRef<str>>(keys: &[S]) -> String {
395    keys.iter()
396        .map(|key| format!("/{}", key.as_ref().replace('~', "~0").replace('/', "~1")))
397        .collect()
398}