surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
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
//! The secret catalog as this machine sees it: `secrets.toml` with the
//! `[secrets.*]` refs of `machines/<machine-id>.toml` on top (SPEC 5.3,
//! 5.6, 11.11), so one alias can resolve from 1Password on one machine and
//! from the keyring on another. References and metadata only.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use crate::apply::render::DesiredState;
use crate::error::{CoreError, ErrorCode};
use crate::model::clients::ClientSelection;
use crate::model::ids::{self, IdKind};
use crate::model::machine::MachineOverlay;
use crate::model::secrets::{SecretCatalog, SecretEntry};
use crate::model::{StoreModel, TomlDocument};
use crate::secrets::grammar::{SecretRef, TemplatePart, parse_template};
use crate::secrets::providers::Resolver;
use crate::secrets::status::{Resolution, SecretStatus};
use crate::store::{StoreRead, Transaction};

/// The catalog file at the store root.
pub const CATALOG_FILE: &str = "secrets.toml";

/// `machines/<machine-id>.toml`.
pub fn overlay_path(machine_id: &str) -> Result<String, CoreError> {
    ids::check(IdKind::Machine, machine_id)?;
    Ok(format!("machines/{machine_id}.toml"))
}

/// Where an alias's effective reference comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefSource {
    /// `secrets.toml`, shared by every machine.
    Store,
    /// This machine's overlay.
    Machine,
}

impl RefSource {
    pub const fn as_str(self) -> &'static str {
        match self {
            RefSource::Store => "store",
            RefSource::Machine => "machine",
        }
    }
}

/// One alias with this machine's reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Alias {
    pub alias: String,
    /// The effective reference text.
    pub reference: String,
    pub source: RefSource,
    /// The `secrets.toml` reference when the machine overrides it.
    pub store_reference: Option<String>,
    pub description: Option<String>,
    /// `env_name` as written; see [`Alias::env_name`].
    pub env_name: Option<String>,
}

impl Alias {
    pub fn parsed(&self) -> Result<SecretRef, CoreError> {
        SecretRef::parse(&self.reference)
    }

    /// The variable name env delivery uses: `env_name`, else the alias.
    pub fn env_name(&self) -> &str {
        self.env_name.as_deref().unwrap_or(&self.alias)
    }
}

/// The effective catalog.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Catalog {
    aliases: BTreeMap<String, Alias>,
    /// `[onepassword] environment`.
    pub environment: Option<String>,
    /// `[onepassword] account`: the account every `op` call names.
    pub op_account: Option<String>,
}

impl Catalog {
    /// Loads `secrets.toml` and, with `machine_id`, that machine's overlay.
    /// Either file failing validation fails the load.
    pub fn load(src: &dyn StoreRead, machine_id: Option<&str>) -> Result<Self, CoreError> {
        let mut catalog = Self::default();
        if let Some(file) = load::<SecretCatalog>(src, CATALOG_FILE)? {
            checked(file.validate().first_error(Some(Path::new(CATALOG_FILE))))?;
            if let Some(op) = file.onepassword {
                catalog.environment = op.environment;
                catalog.op_account = op.account;
            }
            for (alias, entry) in file.secrets.into_iter().flatten() {
                catalog.aliases.insert(
                    alias.clone(),
                    Alias {
                        alias,
                        reference: entry.reference,
                        source: RefSource::Store,
                        store_reference: None,
                        description: entry.description,
                        env_name: entry.env_name,
                    },
                );
            }
        }
        let Some(machine_id) = machine_id else {
            return Ok(catalog);
        };
        let relative = overlay_path(machine_id)?;
        if let Some(overlay) = load::<MachineOverlay>(src, &relative)? {
            checked(
                overlay
                    .validate(Some(machine_id))
                    .first_error(Some(Path::new(&relative))),
            )?;
            for (alias, entry) in overlay.secrets.into_iter().flatten() {
                let shared = catalog.aliases.remove(&alias);
                let store_reference = shared.as_ref().map(|shared| shared.reference.clone());
                let (description, env_name) = match shared {
                    Some(shared) => (
                        entry.description.or(shared.description),
                        entry.env_name.or(shared.env_name),
                    ),
                    None => (entry.description, entry.env_name),
                };
                catalog.aliases.insert(
                    alias.clone(),
                    Alias {
                        alias,
                        reference: entry.reference,
                        source: RefSource::Machine,
                        store_reference,
                        description,
                        env_name,
                    },
                );
            }
        }
        Ok(catalog)
    }

    pub fn get(&self, alias: &str) -> Option<&Alias> {
        self.aliases.get(alias)
    }

    /// Every alias, sorted.
    pub fn iter(&self) -> impl Iterator<Item = &Alias> {
        self.aliases.values()
    }

    pub fn is_empty(&self) -> bool {
        self.aliases.is_empty()
    }
}

/// Which file [`stage_set`] writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetScope {
    /// `secrets.toml`: every machine.
    Store,
    /// This machine's overlay only (SPEC 11.11 "use keyring on this
    /// machine").
    Machine,
}

/// What [`stage_set`] writes for an alias. `None` fields keep what the
/// entry has.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AliasUpdate {
    pub reference: SecretRef,
    pub description: Option<String>,
    pub env_name: Option<String>,
}

/// Stages an alias's reference in `secrets.toml` or in this machine's
/// overlay (created when absent), keeping comments and unknown keys.
pub fn stage_set(
    tx: &mut Transaction<'_>,
    alias: &str,
    update: &AliasUpdate,
    scope: SetScope,
) -> Result<(), CoreError> {
    ids::check(IdKind::SecretAlias, alias)?;
    if let Some(env_name) = &update.env_name {
        ids::check(IdKind::EnvVar, env_name)?;
    }
    let merge = |entries: &mut Option<BTreeMap<String, SecretEntry>>| {
        let entries = entries.get_or_insert_with(BTreeMap::new);
        let entry = entries
            .entry(alias.to_owned())
            .or_insert_with(|| SecretEntry {
                reference: String::new(),
                description: None,
                env_name: None,
                extra: toml::Table::new(),
            });
        entry.reference = update.reference.to_string();
        if update.description.is_some() {
            entry.description.clone_from(&update.description);
        }
        if update.env_name.is_some() {
            entry.env_name.clone_from(&update.env_name);
        }
    };
    match scope {
        SetScope::Store => {
            let mut doc = load_doc::<SecretCatalog>(tx, CATALOG_FILE)?
                .unwrap_or_else(|| TomlDocument::new(SecretCatalog::new()));
            merge(&mut doc.value_mut().secrets);
            tx.write(CATALOG_FILE, doc.to_text()?)
        }
        SetScope::Machine => {
            let machine = tx.machine().clone();
            let relative = overlay_path(&machine.id)?;
            let os = tx.store().env().os();
            let mut doc = load_doc::<MachineOverlay>(tx, &relative)?.unwrap_or_else(|| {
                TomlDocument::new(MachineOverlay::new(&machine.id, &machine.label, os))
            });
            merge(&mut doc.value_mut().secrets);
            tx.write(&relative, doc.to_text()?)
        }
    }
}

/// Stages `[onepassword] environment = <id>` in `secrets.toml`: the one
/// 1Password Environment holding MCP secrets (SPEC 11.10). Returns the
/// id it replaces, if another one was set.
pub fn stage_environment(
    tx: &mut Transaction<'_>,
    environment: &str,
) -> Result<Option<String>, CoreError> {
    if !crate::secrets::grammar::is_op_environment_id(environment) {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!("invalid 1Password Environment id {environment:?}"),
        ));
    }
    let mut doc = load_doc::<SecretCatalog>(tx, CATALOG_FILE)?
        .unwrap_or_else(|| TomlDocument::new(SecretCatalog::new()));
    let onepassword = doc
        .value_mut()
        .onepassword
        .get_or_insert_with(Default::default);
    let previous = onepassword
        .environment
        .replace(environment.to_owned())
        .filter(|previous| previous != environment);
    tx.write(CATALOG_FILE, doc.to_text()?)?;
    Ok(previous)
}

/// Stages `[onepassword] account` in `secrets.toml` (or removes it with
/// `None`): the 1Password account Surjection's `op` calls use (gate V1
/// FB-7). Returns the account it replaces.
pub fn stage_op_account(
    tx: &mut Transaction<'_>,
    account: Option<&str>,
) -> Result<Option<String>, CoreError> {
    if let Some(account) = account
        && !crate::secrets::grammar::is_op_account(account)
    {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!(
                "invalid 1Password account {account:?}: a sign-in address, shorthand or id \
                 (for example example.1password.com)"
            ),
        ));
    }
    let mut doc = load_doc::<SecretCatalog>(tx, CATALOG_FILE)?
        .unwrap_or_else(|| TomlDocument::new(SecretCatalog::new()));
    let onepassword = doc
        .value_mut()
        .onepassword
        .get_or_insert_with(Default::default);
    let previous = match account {
        Some(account) => onepassword.account.replace(account.to_owned()),
        None => onepassword.account.take(),
    };
    tx.write(CATALOG_FILE, doc.to_text()?)?;
    Ok(previous)
}

/// Aliases the servers use (`${secret:ALIAS}` in any string field of
/// `servers/*.toml`, and of this machine's server overrides), each with the
/// server ids that use it. Files that do not parse are skipped; validation
/// reports them elsewhere.
pub fn usage(
    src: &dyn StoreRead,
    machine_id: Option<&str>,
) -> Result<BTreeMap<String, BTreeSet<String>>, CoreError> {
    let mut used: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for name in src.list_files("servers")? {
        let Some(id) = name.strip_suffix(".toml") else {
            continue;
        };
        let Some(text) = src.read_file(&format!("servers/{name}"))? else {
            continue;
        };
        if let Ok(table) = text.parse::<toml::Table>() {
            for alias in aliases_in(&toml::Value::Table(table)) {
                used.entry(alias).or_default().insert(id.to_owned());
            }
        }
    }
    if let Some(machine_id) = machine_id
        && let Some(text) = src.read_file(&overlay_path(machine_id)?)?
        && let Ok(table) = text.parse::<toml::Table>()
        && let Some(toml::Value::Table(servers)) = table.get("servers")
    {
        for (id, fields) in servers {
            for alias in aliases_in(fields) {
                used.entry(alias).or_default().insert(id.clone());
            }
        }
    }
    Ok(used)
}

fn aliases_in(value: &toml::Value) -> BTreeSet<String> {
    let mut found = BTreeSet::new();
    let mut stack = vec![value];
    while let Some(value) = stack.pop() {
        match value {
            toml::Value::String(text) => {
                for part in parse_template(text).into_iter().flatten() {
                    if let TemplatePart::Secret(alias) = part {
                        found.insert(alias);
                    }
                }
            }
            toml::Value::Array(items) => stack.extend(items),
            toml::Value::Table(table) => stack.extend(table.values()),
            _ => {}
        }
    }
    found
}

/// One alias's status on this machine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AliasStatus {
    pub alias: String,
    /// `None` when no catalog defines the alias.
    pub reference: Option<String>,
    pub source: Option<RefSource>,
    pub resolution: Resolution,
    /// Servers using the alias.
    pub servers: BTreeSet<String>,
}

/// Checks every alias of the catalog and every alias a server uses (or
/// only `only`, when not empty). An alias used but not defined is
/// `missing`; a reference that does not parse is `error`. May prompt
/// (1Password approval): run on explicit request only.
pub fn check(
    catalog: &Catalog,
    usage: &BTreeMap<String, BTreeSet<String>>,
    resolver: &Resolver<'_>,
    only: &[String],
) -> Vec<AliasStatus> {
    let names: BTreeSet<&str> = catalog
        .iter()
        .map(|alias| alias.alias.as_str())
        .chain(usage.keys().map(String::as_str))
        .filter(|name| only.is_empty() || only.iter().any(|wanted| wanted == name))
        .chain(only.iter().map(String::as_str))
        .collect();
    names
        .into_iter()
        .map(|name| {
            let servers = usage.get(name).cloned().unwrap_or_default();
            let Some(alias) = catalog.get(name) else {
                return AliasStatus {
                    alias: name.to_owned(),
                    reference: None,
                    source: None,
                    resolution: Resolution::missing(format!(
                        "{name} is not defined in {CATALOG_FILE}"
                    )),
                    servers,
                };
            };
            let resolution = match alias.parsed() {
                Ok(reference) => resolver.check(&reference),
                Err(err) => Resolution::new(SecretStatus::Error, err.message()),
            };
            AliasStatus {
                alias: name.to_owned(),
                reference: Some(alias.reference.clone()),
                source: Some(alias.source),
                resolution,
                servers,
            }
        })
        .collect()
}

/// Each server using the alias, with the clients it is enabled for in
/// `desired` (`all-detected` for a server enabled for every detected
/// client; none when it is not enabled), for the missing-secret checklist
/// (SPEC 11.9).
pub fn needed_by(status: &AliasStatus, desired: &DesiredState) -> Vec<(String, Vec<String>)> {
    status
        .servers
        .iter()
        .map(|id| {
            let clients = match desired
                .servers
                .get(id)
                .and_then(|server| server.enable.as_ref())
                .and_then(|enable| enable.clients.as_ref())
            {
                Some(ClientSelection::List(ids)) => ids.clone(),
                Some(ClientSelection::AllDetected) => vec!["all-detected".to_owned()],
                None => Vec::new(),
            };
            (id.clone(), clients)
        })
        .collect()
}

fn load<T: StoreModel>(src: &dyn StoreRead, relative: &str) -> Result<Option<T>, CoreError> {
    Ok(load_doc(src, relative)?.map(TomlDocument::into_value))
}

fn load_doc<T: StoreModel>(
    src: &dyn StoreRead,
    relative: &str,
) -> Result<Option<TomlDocument<T>>, CoreError> {
    let Some(text) = src.read_file(relative)? else {
        return Ok(None);
    };
    TomlDocument::parse(&text)
        .map(Some)
        .map_err(|diagnostic| diagnostic.to_core_error(Some(Path::new(relative))))
}

fn checked(error: Option<CoreError>) -> Result<(), CoreError> {
    match error {
        Some(err) => Err(err),
        None => Ok(()),
    }
}

/// `invalid_value` for a reference that is not a keyring reference, used
/// where only keyring entries make sense (`secrets set --keyring`).
pub fn keyring_parts(reference: &SecretRef) -> Result<(&str, &str), CoreError> {
    match reference {
        SecretRef::Keyring { service, account } => Ok((service, account)),
        other => Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!("{other} is not a keyring reference"),
        )),
    }
}