Skip to main content

surjection_core/secrets/
catalog.rs

1//! The secret catalog as this machine sees it: `secrets.toml` with the
2//! `[secrets.*]` refs of `machines/<machine-id>.toml` on top (SPEC 5.3,
3//! 5.6, 11.11), so one alias can resolve from 1Password on one machine and
4//! from the keyring on another. References and metadata only.
5
6use std::collections::{BTreeMap, BTreeSet};
7use std::path::Path;
8
9use crate::apply::render::DesiredState;
10use crate::error::{CoreError, ErrorCode};
11use crate::model::clients::ClientSelection;
12use crate::model::ids::{self, IdKind};
13use crate::model::machine::MachineOverlay;
14use crate::model::secrets::{SecretCatalog, SecretEntry};
15use crate::model::{StoreModel, TomlDocument};
16use crate::secrets::grammar::{SecretRef, TemplatePart, parse_template};
17use crate::secrets::providers::Resolver;
18use crate::secrets::status::{Resolution, SecretStatus};
19use crate::store::{StoreRead, Transaction};
20
21/// The catalog file at the store root.
22pub const CATALOG_FILE: &str = "secrets.toml";
23
24/// `machines/<machine-id>.toml`.
25pub fn overlay_path(machine_id: &str) -> Result<String, CoreError> {
26    ids::check(IdKind::Machine, machine_id)?;
27    Ok(format!("machines/{machine_id}.toml"))
28}
29
30/// Where an alias's effective reference comes from.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum RefSource {
33    /// `secrets.toml`, shared by every machine.
34    Store,
35    /// This machine's overlay.
36    Machine,
37}
38
39impl RefSource {
40    pub const fn as_str(self) -> &'static str {
41        match self {
42            RefSource::Store => "store",
43            RefSource::Machine => "machine",
44        }
45    }
46}
47
48/// One alias with this machine's reference.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Alias {
51    pub alias: String,
52    /// The effective reference text.
53    pub reference: String,
54    pub source: RefSource,
55    /// The `secrets.toml` reference when the machine overrides it.
56    pub store_reference: Option<String>,
57    pub description: Option<String>,
58    /// `env_name` as written; see [`Alias::env_name`].
59    pub env_name: Option<String>,
60}
61
62impl Alias {
63    pub fn parsed(&self) -> Result<SecretRef, CoreError> {
64        SecretRef::parse(&self.reference)
65    }
66
67    /// The variable name env delivery uses: `env_name`, else the alias.
68    pub fn env_name(&self) -> &str {
69        self.env_name.as_deref().unwrap_or(&self.alias)
70    }
71}
72
73/// The effective catalog.
74#[derive(Debug, Clone, Default, PartialEq, Eq)]
75pub struct Catalog {
76    aliases: BTreeMap<String, Alias>,
77    /// `[onepassword] environment`.
78    pub environment: Option<String>,
79    /// `[onepassword] account`: the account every `op` call names.
80    pub op_account: Option<String>,
81}
82
83impl Catalog {
84    /// Loads `secrets.toml` and, with `machine_id`, that machine's overlay.
85    /// Either file failing validation fails the load.
86    pub fn load(src: &dyn StoreRead, machine_id: Option<&str>) -> Result<Self, CoreError> {
87        let mut catalog = Self::default();
88        if let Some(file) = load::<SecretCatalog>(src, CATALOG_FILE)? {
89            checked(file.validate().first_error(Some(Path::new(CATALOG_FILE))))?;
90            if let Some(op) = file.onepassword {
91                catalog.environment = op.environment;
92                catalog.op_account = op.account;
93            }
94            for (alias, entry) in file.secrets.into_iter().flatten() {
95                catalog.aliases.insert(
96                    alias.clone(),
97                    Alias {
98                        alias,
99                        reference: entry.reference,
100                        source: RefSource::Store,
101                        store_reference: None,
102                        description: entry.description,
103                        env_name: entry.env_name,
104                    },
105                );
106            }
107        }
108        let Some(machine_id) = machine_id else {
109            return Ok(catalog);
110        };
111        let relative = overlay_path(machine_id)?;
112        if let Some(overlay) = load::<MachineOverlay>(src, &relative)? {
113            checked(
114                overlay
115                    .validate(Some(machine_id))
116                    .first_error(Some(Path::new(&relative))),
117            )?;
118            for (alias, entry) in overlay.secrets.into_iter().flatten() {
119                let shared = catalog.aliases.remove(&alias);
120                let store_reference = shared.as_ref().map(|shared| shared.reference.clone());
121                let (description, env_name) = match shared {
122                    Some(shared) => (
123                        entry.description.or(shared.description),
124                        entry.env_name.or(shared.env_name),
125                    ),
126                    None => (entry.description, entry.env_name),
127                };
128                catalog.aliases.insert(
129                    alias.clone(),
130                    Alias {
131                        alias,
132                        reference: entry.reference,
133                        source: RefSource::Machine,
134                        store_reference,
135                        description,
136                        env_name,
137                    },
138                );
139            }
140        }
141        Ok(catalog)
142    }
143
144    pub fn get(&self, alias: &str) -> Option<&Alias> {
145        self.aliases.get(alias)
146    }
147
148    /// Every alias, sorted.
149    pub fn iter(&self) -> impl Iterator<Item = &Alias> {
150        self.aliases.values()
151    }
152
153    pub fn is_empty(&self) -> bool {
154        self.aliases.is_empty()
155    }
156}
157
158/// Which file [`stage_set`] writes.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum SetScope {
161    /// `secrets.toml`: every machine.
162    Store,
163    /// This machine's overlay only (SPEC 11.11 "use keyring on this
164    /// machine").
165    Machine,
166}
167
168/// What [`stage_set`] writes for an alias. `None` fields keep what the
169/// entry has.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct AliasUpdate {
172    pub reference: SecretRef,
173    pub description: Option<String>,
174    pub env_name: Option<String>,
175}
176
177/// Stages an alias's reference in `secrets.toml` or in this machine's
178/// overlay (created when absent), keeping comments and unknown keys.
179pub fn stage_set(
180    tx: &mut Transaction<'_>,
181    alias: &str,
182    update: &AliasUpdate,
183    scope: SetScope,
184) -> Result<(), CoreError> {
185    ids::check(IdKind::SecretAlias, alias)?;
186    if let Some(env_name) = &update.env_name {
187        ids::check(IdKind::EnvVar, env_name)?;
188    }
189    let merge = |entries: &mut Option<BTreeMap<String, SecretEntry>>| {
190        let entries = entries.get_or_insert_with(BTreeMap::new);
191        let entry = entries
192            .entry(alias.to_owned())
193            .or_insert_with(|| SecretEntry {
194                reference: String::new(),
195                description: None,
196                env_name: None,
197                extra: toml::Table::new(),
198            });
199        entry.reference = update.reference.to_string();
200        if update.description.is_some() {
201            entry.description.clone_from(&update.description);
202        }
203        if update.env_name.is_some() {
204            entry.env_name.clone_from(&update.env_name);
205        }
206    };
207    match scope {
208        SetScope::Store => {
209            let mut doc = load_doc::<SecretCatalog>(tx, CATALOG_FILE)?
210                .unwrap_or_else(|| TomlDocument::new(SecretCatalog::new()));
211            merge(&mut doc.value_mut().secrets);
212            tx.write(CATALOG_FILE, doc.to_text()?)
213        }
214        SetScope::Machine => {
215            let machine = tx.machine().clone();
216            let relative = overlay_path(&machine.id)?;
217            let os = tx.store().env().os();
218            let mut doc = load_doc::<MachineOverlay>(tx, &relative)?.unwrap_or_else(|| {
219                TomlDocument::new(MachineOverlay::new(&machine.id, &machine.label, os))
220            });
221            merge(&mut doc.value_mut().secrets);
222            tx.write(&relative, doc.to_text()?)
223        }
224    }
225}
226
227/// Stages `[onepassword] environment = <id>` in `secrets.toml`: the one
228/// 1Password Environment holding MCP secrets (SPEC 11.10). Returns the
229/// id it replaces, if another one was set.
230pub fn stage_environment(
231    tx: &mut Transaction<'_>,
232    environment: &str,
233) -> Result<Option<String>, CoreError> {
234    if !crate::secrets::grammar::is_op_environment_id(environment) {
235        return Err(CoreError::new(
236            ErrorCode::InvalidValue,
237            format!("invalid 1Password Environment id {environment:?}"),
238        ));
239    }
240    let mut doc = load_doc::<SecretCatalog>(tx, CATALOG_FILE)?
241        .unwrap_or_else(|| TomlDocument::new(SecretCatalog::new()));
242    let onepassword = doc
243        .value_mut()
244        .onepassword
245        .get_or_insert_with(Default::default);
246    let previous = onepassword
247        .environment
248        .replace(environment.to_owned())
249        .filter(|previous| previous != environment);
250    tx.write(CATALOG_FILE, doc.to_text()?)?;
251    Ok(previous)
252}
253
254/// Stages `[onepassword] account` in `secrets.toml` (or removes it with
255/// `None`): the 1Password account Surjection's `op` calls use (gate V1
256/// FB-7). Returns the account it replaces.
257pub fn stage_op_account(
258    tx: &mut Transaction<'_>,
259    account: Option<&str>,
260) -> Result<Option<String>, CoreError> {
261    if let Some(account) = account
262        && !crate::secrets::grammar::is_op_account(account)
263    {
264        return Err(CoreError::new(
265            ErrorCode::InvalidValue,
266            format!(
267                "invalid 1Password account {account:?}: a sign-in address, shorthand or id \
268                 (for example example.1password.com)"
269            ),
270        ));
271    }
272    let mut doc = load_doc::<SecretCatalog>(tx, CATALOG_FILE)?
273        .unwrap_or_else(|| TomlDocument::new(SecretCatalog::new()));
274    let onepassword = doc
275        .value_mut()
276        .onepassword
277        .get_or_insert_with(Default::default);
278    let previous = match account {
279        Some(account) => onepassword.account.replace(account.to_owned()),
280        None => onepassword.account.take(),
281    };
282    tx.write(CATALOG_FILE, doc.to_text()?)?;
283    Ok(previous)
284}
285
286/// Aliases the servers use (`${secret:ALIAS}` in any string field of
287/// `servers/*.toml`, and of this machine's server overrides), each with the
288/// server ids that use it. Files that do not parse are skipped; validation
289/// reports them elsewhere.
290pub fn usage(
291    src: &dyn StoreRead,
292    machine_id: Option<&str>,
293) -> Result<BTreeMap<String, BTreeSet<String>>, CoreError> {
294    let mut used: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
295    for name in src.list_files("servers")? {
296        let Some(id) = name.strip_suffix(".toml") else {
297            continue;
298        };
299        let Some(text) = src.read_file(&format!("servers/{name}"))? else {
300            continue;
301        };
302        if let Ok(table) = text.parse::<toml::Table>() {
303            for alias in aliases_in(&toml::Value::Table(table)) {
304                used.entry(alias).or_default().insert(id.to_owned());
305            }
306        }
307    }
308    if let Some(machine_id) = machine_id
309        && let Some(text) = src.read_file(&overlay_path(machine_id)?)?
310        && let Ok(table) = text.parse::<toml::Table>()
311        && let Some(toml::Value::Table(servers)) = table.get("servers")
312    {
313        for (id, fields) in servers {
314            for alias in aliases_in(fields) {
315                used.entry(alias).or_default().insert(id.clone());
316            }
317        }
318    }
319    Ok(used)
320}
321
322fn aliases_in(value: &toml::Value) -> BTreeSet<String> {
323    let mut found = BTreeSet::new();
324    let mut stack = vec![value];
325    while let Some(value) = stack.pop() {
326        match value {
327            toml::Value::String(text) => {
328                for part in parse_template(text).into_iter().flatten() {
329                    if let TemplatePart::Secret(alias) = part {
330                        found.insert(alias);
331                    }
332                }
333            }
334            toml::Value::Array(items) => stack.extend(items),
335            toml::Value::Table(table) => stack.extend(table.values()),
336            _ => {}
337        }
338    }
339    found
340}
341
342/// One alias's status on this machine.
343#[derive(Debug, Clone, PartialEq, Eq)]
344pub struct AliasStatus {
345    pub alias: String,
346    /// `None` when no catalog defines the alias.
347    pub reference: Option<String>,
348    pub source: Option<RefSource>,
349    pub resolution: Resolution,
350    /// Servers using the alias.
351    pub servers: BTreeSet<String>,
352}
353
354/// Checks every alias of the catalog and every alias a server uses (or
355/// only `only`, when not empty). An alias used but not defined is
356/// `missing`; a reference that does not parse is `error`. May prompt
357/// (1Password approval): run on explicit request only.
358pub fn check(
359    catalog: &Catalog,
360    usage: &BTreeMap<String, BTreeSet<String>>,
361    resolver: &Resolver<'_>,
362    only: &[String],
363) -> Vec<AliasStatus> {
364    let names: BTreeSet<&str> = catalog
365        .iter()
366        .map(|alias| alias.alias.as_str())
367        .chain(usage.keys().map(String::as_str))
368        .filter(|name| only.is_empty() || only.iter().any(|wanted| wanted == name))
369        .chain(only.iter().map(String::as_str))
370        .collect();
371    names
372        .into_iter()
373        .map(|name| {
374            let servers = usage.get(name).cloned().unwrap_or_default();
375            let Some(alias) = catalog.get(name) else {
376                return AliasStatus {
377                    alias: name.to_owned(),
378                    reference: None,
379                    source: None,
380                    resolution: Resolution::missing(format!(
381                        "{name} is not defined in {CATALOG_FILE}"
382                    )),
383                    servers,
384                };
385            };
386            let resolution = match alias.parsed() {
387                Ok(reference) => resolver.check(&reference),
388                Err(err) => Resolution::new(SecretStatus::Error, err.message()),
389            };
390            AliasStatus {
391                alias: name.to_owned(),
392                reference: Some(alias.reference.clone()),
393                source: Some(alias.source),
394                resolution,
395                servers,
396            }
397        })
398        .collect()
399}
400
401/// Each server using the alias, with the clients it is enabled for in
402/// `desired` (`all-detected` for a server enabled for every detected
403/// client; none when it is not enabled), for the missing-secret checklist
404/// (SPEC 11.9).
405pub fn needed_by(status: &AliasStatus, desired: &DesiredState) -> Vec<(String, Vec<String>)> {
406    status
407        .servers
408        .iter()
409        .map(|id| {
410            let clients = match desired
411                .servers
412                .get(id)
413                .and_then(|server| server.enable.as_ref())
414                .and_then(|enable| enable.clients.as_ref())
415            {
416                Some(ClientSelection::List(ids)) => ids.clone(),
417                Some(ClientSelection::AllDetected) => vec!["all-detected".to_owned()],
418                None => Vec::new(),
419            };
420            (id.clone(), clients)
421        })
422        .collect()
423}
424
425fn load<T: StoreModel>(src: &dyn StoreRead, relative: &str) -> Result<Option<T>, CoreError> {
426    Ok(load_doc(src, relative)?.map(TomlDocument::into_value))
427}
428
429fn load_doc<T: StoreModel>(
430    src: &dyn StoreRead,
431    relative: &str,
432) -> Result<Option<TomlDocument<T>>, CoreError> {
433    let Some(text) = src.read_file(relative)? else {
434        return Ok(None);
435    };
436    TomlDocument::parse(&text)
437        .map(Some)
438        .map_err(|diagnostic| diagnostic.to_core_error(Some(Path::new(relative))))
439}
440
441fn checked(error: Option<CoreError>) -> Result<(), CoreError> {
442    match error {
443        Some(err) => Err(err),
444        None => Ok(()),
445    }
446}
447
448/// `invalid_value` for a reference that is not a keyring reference, used
449/// where only keyring entries make sense (`secrets set --keyring`).
450pub fn keyring_parts(reference: &SecretRef) -> Result<(&str, &str), CoreError> {
451    match reference {
452        SecretRef::Keyring { service, account } => Ok((service, account)),
453        other => Err(CoreError::new(
454            ErrorCode::InvalidValue,
455            format!("{other} is not a keyring reference"),
456        )),
457    }
458}