surjection-core 1.1.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Delivery modes (SPEC 11.4): how a secret reference reaches an MCP server
//! for one client and field, and what blocks it on this machine.
//!
//! - `env`: the client expands a variable reference itself (or forwards a
//!   variable by name, Codex).
//! - `launch`: the client starts `surject exec`, which resolves the
//!   references in its argv and starts the server with the values in its
//!   environment (SPEC 11.5). Stdio `env` values only.
//! - `command`: the client runs a Surjection command at connect time (omp and
//!   Pi `!command`, Claude Code `headersHelper`).
//! - `inline`: Surjection writes the value into the client's file. Explicit
//!   per server, or the fallback for `${env:..}` the client cannot get
//!   otherwise; never into a shared file.
//!
//! [`Policy::choose`] implements the `auto` rules and checks an explicit
//! `delivery.mode`. Planning never reads a 1Password value (that may
//! prompt): a `launch` or `command` entry is blocked only when the
//! provider is not usable here ([`check_available`]).

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};

use crate::adapters::caps::{Caps, CommandRef, EnvRefSyntax, FieldSet};
use crate::brand;
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::model::server::{DeliveryMode, Transport};
use crate::secrets::catalog::{CATALOG_FILE, Catalog};
use crate::secrets::grammar::SecretRef;
use crate::secrets::providers::keyring::KeyringBackend;
use crate::secrets::providers::onepassword::{OpCli, OpFeature};
use crate::secrets::scanner::SecretMemory;
use crate::secrets::status::SecretStatus;

/// The variable `op` reads a service account token from.
pub const SERVICE_ACCOUNT_VAR: &str = "OP_SERVICE_ACCOUNT_TOKEN";
/// Keyring account of the service account token (service
/// [`brand::KEYRING_SERVICE`]): `keyring://surjection/OP_SERVICE_ACCOUNT_TOKEN`.
pub const SERVICE_ACCOUNT_KEYRING_ACCOUNT: &str = "OP_SERVICE_ACCOUNT_TOKEN";

/// A delivery mode, ordered so that the most consequential mode of an entry
/// is the greatest (the one an entry reports).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Mode {
    Env,
    Command,
    Launch,
    Inline,
}

impl Mode {
    pub const fn as_str(self) -> &'static str {
        match self {
            Mode::Env => "env",
            Mode::Command => "command",
            Mode::Launch => "launch",
            Mode::Inline => "inline",
        }
    }
}

/// Whether a target file is private to this user or shared (tracked by a
/// project's git repository, or flagged shared).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sharing {
    /// User-scope files and private project files.
    Private,
    /// Shared project files: no `inline` values, and the launcher is the
    /// bare `surject` so the file stays portable (SPEC 11.5).
    Shared,
}

/// Where the value of a template reference comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    /// `${env:NAME}`, or an alias whose reference is `env:NAME`: a variable
    /// of the environment the client (or Surjection) runs in.
    Env { name: String },
    /// An alias with a provider reference (`op://`, `op-env://`,
    /// `keyring://`).
    Provider {
        alias: String,
        reference: SecretRef,
        /// The variable `env` delivery uses (`env_name`, else the alias).
        env_name: String,
    },
}

impl Source {
    /// The variable `env` delivery spells.
    pub fn variable(&self) -> &str {
        match self {
            Source::Env { name } => name,
            Source::Provider { env_name, .. } => env_name,
        }
    }

    /// The reference `surject exec` and `surject secret get` resolve.
    pub fn reference(&self) -> SecretRef {
        match self {
            Source::Env { name } => SecretRef::Env { name: name.clone() },
            Source::Provider { reference, .. } => reference.clone(),
        }
    }

    pub fn is_provider(&self) -> bool {
        matches!(self, Source::Provider { .. })
    }

    /// How messages name it: the alias, or the variable.
    pub fn label(&self) -> &str {
        match self {
            Source::Env { name } => name,
            Source::Provider { alias, .. } => alias,
        }
    }
}

/// The source of `${secret:ALIAS}` on this machine. An alias no catalog
/// defines is `missing_secret` (SPEC 11.9).
pub fn source_of_alias(catalog: &Catalog, alias: &str) -> Result<Source, CoreError> {
    let entry = catalog.get(alias).ok_or_else(|| {
        CoreError::new(
            ErrorCode::MissingSecret,
            format!(
                "{alias} is not defined in {CATALOG_FILE}; set it with `{} secrets set {alias} ...`",
                brand::BIN_NAME
            ),
        )
    })?;
    Ok(match entry.parsed()? {
        SecretRef::Env { name } => Source::Env { name },
        reference => Source::Provider {
            alias: alias.to_owned(),
            reference,
            env_name: entry.env_name().to_owned(),
        },
    })
}

/// One value that holds references: the field it is in and its sources.
#[derive(Debug, Clone, Copy)]
pub struct Slot<'a> {
    pub field: FieldSet,
    pub transport: Transport,
    /// The value is exactly one reference, without literal text around it.
    pub whole: bool,
    /// The client forwards the variable by name here (Codex `env_vars`
    /// under the same key, `bearer_token_env_var`, `env_http_headers`).
    pub forwardable: bool,
    pub sources: &'a [Source],
}

/// What decides the mode of a value: the server's `delivery.mode`, the
/// client, the target and this machine's choices.
#[derive(Debug, Clone, Copy)]
pub struct Policy<'a> {
    pub requested: DeliveryMode,
    pub caps: &'a Caps,
    /// The client's display name, for messages.
    pub client: &'a str,
    pub sharing: Sharing,
    /// `[delivery] export_provider_secrets` of the machine overlay.
    pub export_provider_secrets: bool,
}

/// A client's spelling of a variable reference in `field`, when it expands
/// references there itself (never a client that only forwards variables by
/// name, Codex).
pub fn env_syntax(caps: &Caps, field: FieldSet) -> Option<EnvRefSyntax> {
    caps.env_ref
        .filter(|syntax| *syntax != EnvRefSyntax::CodexForward)
        .filter(|_| field != FieldSet::NONE && caps.env_ref_fields.contains(field))
}

impl Policy<'_> {
    /// The client's spelling of a variable reference in `field`, when it
    /// expands references there itself.
    pub fn env_syntax(&self, field: FieldSet) -> Option<EnvRefSyntax> {
        env_syntax(self.caps, field)
    }

    /// Whether the client forwards variables by name (Codex).
    pub fn forwards(&self) -> bool {
        self.caps.env_ref == Some(EnvRefSyntax::CodexForward)
    }

    /// Whether the client can get this value by running a command. Never
    /// for 1Password Environment variables: only `op run` hands them to a
    /// process, so `surject secret get` cannot print them.
    fn command_ok(&self, slot: &Slot<'_>) -> bool {
        let environment = slot.sources.iter().any(|source| {
            matches!(
                source,
                Source::Provider {
                    reference: SecretRef::OnePasswordEnvironment { .. },
                    ..
                }
            )
        });
        if environment {
            return false;
        }
        match self.caps.command_ref {
            Some(CommandRef::Bang) => matches!(slot.field, FieldSet::ENV | FieldSet::HEADERS),
            Some(CommandRef::HeadersHelper) => {
                slot.field == FieldSet::HEADERS && slot.transport != Transport::Stdio
            }
            None => false,
        }
    }

    /// The mode for one value (SPEC 11.4 `auto` rules, or the explicit
    /// mode when it can deliver the value).
    pub fn choose(&self, slot: &Slot<'_>) -> Result<Mode, CoreError> {
        let env_ok = self.env_syntax(slot.field).is_some() || slot.forwardable;
        let launch_ok =
            slot.transport == Transport::Stdio && slot.field == FieldSet::ENV && slot.whole;
        let command_ok = self.command_ok(slot);
        let provider = slot.sources.iter().any(Source::is_provider);
        let field = field_name(slot.field);
        let unavailable = |mode: &str, why: &str| {
            Err(CoreError::new(
                ErrorCode::DeliveryUnavailable,
                format!(
                    "`{mode}` delivery cannot bring a reference in `{field}` to {}: {why}",
                    self.client
                ),
            ))
        };
        match self.requested {
            DeliveryMode::Env if env_ok => Ok(Mode::Env),
            DeliveryMode::Env => unavailable(
                "env",
                if self.forwards() {
                    "it forwards whole variables under their own name only"
                } else {
                    "it does not expand variables in this field"
                },
            ),
            DeliveryMode::Launch if launch_ok => Ok(Mode::Launch),
            DeliveryMode::Launch => unavailable(
                "launch",
                "`surject exec` sets whole `env` values of stdio servers only",
            ),
            DeliveryMode::Command if command_ok => Ok(Mode::Command),
            DeliveryMode::Command => unavailable("command", "it runs no command for this field"),
            DeliveryMode::Inline => self.inline(),
            DeliveryMode::Auto if !provider => {
                if env_ok {
                    Ok(Mode::Env)
                } else if launch_ok {
                    Ok(Mode::Launch)
                } else {
                    self.inline()
                }
            }
            DeliveryMode::Auto => {
                if launch_ok {
                    Ok(Mode::Launch)
                } else if command_ok && slot.transport != Transport::Stdio {
                    Ok(Mode::Command)
                } else if (slot.forwardable && slot.field == FieldSet::HEADERS)
                    || (self.export_provider_secrets && env_ok)
                {
                    // Codex forwards header variables by name (SPEC 11.4
                    // rule 2); elsewhere `env` needs the user's export.
                    Ok(Mode::Env)
                } else {
                    let labels: Vec<&str> = slot
                        .sources
                        .iter()
                        .filter(|source| source.is_provider())
                        .map(Source::label)
                        .collect();
                    Err(CoreError::new(
                        ErrorCode::NoSecretFreeDelivery,
                        format!(
                            "{} cannot get {} in `{field}` without the value in its config file; \
                             fixes: export it to the environment (`{bin} env --export`, then \
                             `[delivery] export_provider_secrets = true` in this machine's overlay), \
                             or allow inline for this server (`[delivery] mode = \"inline\"`)",
                            self.client,
                            labels.join(", "),
                            bin = brand::BIN_NAME,
                        ),
                    ))
                }
            }
        }
    }

    fn inline(&self) -> Result<Mode, CoreError> {
        match self.sharing {
            Sharing::Private => Ok(Mode::Inline),
            Sharing::Shared => Err(CoreError::new(
                ErrorCode::SecretInSharedFile,
                "inline delivery would write a secret value into a shared file; use `env` or \
                 `launch` delivery, or move the server to the project-local layer",
            )),
        }
    }
}

/// The name of a field in messages.
pub fn field_name(field: FieldSet) -> &'static str {
    match field {
        FieldSet::COMMAND => "command",
        FieldSet::ARGS => "args",
        FieldSet::ENV => "env",
        FieldSet::CWD => "cwd",
        FieldSet::URL => "url",
        FieldSet::HEADERS => "headers",
        _ => "client fields",
    }
}

/// What delivery needs from this machine: the launcher path, the keyring
/// and the 1Password CLI (detected once, on first use).
pub struct DeliveryEnv {
    launcher: Option<PathBuf>,
    keyring: Arc<dyn KeyringBackend>,
    op: OnceLock<OpCli>,
    /// Times the keyring was handed out: a read of secret state that no
    /// file shows (the plan cache, [`crate::apply::cache`]).
    keyring_uses: AtomicU64,
}

impl DeliveryEnv {
    /// `launcher` is the absolute path of the installed `surject` binary
    /// (as the target machine spells it), `None` when it cannot be
    /// resolved.
    pub fn new(launcher: Option<PathBuf>, keyring: Arc<dyn KeyringBackend>) -> Self {
        Self {
            launcher,
            keyring,
            op: OnceLock::new(),
            keyring_uses: AtomicU64::new(0),
        }
    }

    /// Uses `op` instead of detecting the CLI.
    pub fn with_op(self, op: OpCli) -> Self {
        let _ = self.op.set(op);
        self
    }

    pub fn launcher_path(&self) -> Option<&Path> {
        self.launcher.as_deref()
    }

    /// The keyring. Every secret value read while rendering (a keyring
    /// entry, a 1Password item, the service account token) goes through
    /// it, and each call counts in [`DeliveryEnv::provider_reads`].
    pub fn keyring(&self) -> &dyn KeyringBackend {
        self.keyring_uses.fetch_add(1, Ordering::Relaxed);
        self.keyring.as_ref()
    }

    /// How often the keyring was handed out so far, by any caller: a plan
    /// that saw this change may depend on secret values.
    pub fn provider_reads(&self) -> u64 {
        self.keyring_uses.load(Ordering::Relaxed)
    }

    /// The 1Password CLI of this machine (`op --version` runs once).
    pub fn op(&self, env: &Env, fs: &dyn Fs) -> &OpCli {
        self.op.get_or_init(|| OpCli::detect(env, fs))
    }

    /// How a target starts `surject`: the absolute path for private files,
    /// the bare name for shared ones (SPEC 11.5).
    pub fn launcher(&self, sharing: Sharing) -> Result<String, CoreError> {
        match (sharing, &self.launcher) {
            (Sharing::Shared, _) => Ok(brand::BIN_NAME.to_owned()),
            (Sharing::Private, Some(path)) => Ok(path.to_string_lossy().into_owned()),
            (Sharing::Private, None) => Err(CoreError::new(
                ErrorCode::LauncherNotFound,
                format!(
                    "the path of the `{}` binary is not known, so the server cannot be started \
                     through `{} exec`",
                    brand::BIN_NAME,
                    brand::BIN_NAME
                ),
            )),
        }
    }
}

impl std::fmt::Debug for DeliveryEnv {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DeliveryEnv")
            .field("launcher", &self.launcher)
            .field("keyring", &self.keyring.name())
            .field("op", &self.op.get())
            .finish()
    }
}

/// The `op` environment variable naming the account to use.
pub const ACCOUNT_VAR: &str = "OP_ACCOUNT";

/// `env` for an `op` child: with the service account token from the OS
/// keyring (SPEC 11.5) unless `env` already has one, and with `account`
/// as `OP_ACCOUNT` unless `env` already names one (gate V1 FB-7: with
/// several accounts signed in to the desktop app, `op` refuses to guess).
/// An unreadable keyring means no token.
pub fn op_env(env: &Env, keyring: &dyn KeyringBackend, account: Option<&str>) -> Env {
    let env = match account {
        Some(account) if env.var(ACCOUNT_VAR).is_none() => env.with_var(ACCOUNT_VAR, account),
        _ => env.clone(),
    };
    if env.var(SERVICE_ACCOUNT_VAR).is_some() {
        return env;
    }
    match keyring.get_own(SERVICE_ACCOUNT_KEYRING_ACCOUNT) {
        Ok(Some(token)) => env.with_var(SERVICE_ACCOUNT_VAR, token.expose()),
        _ => env,
    }
}

/// Whether `source` can be delivered when the server starts (`launch`,
/// `command`): the provider is installed and new enough, and a keyring
/// entry exists (its value is recorded for the leak scanner, never kept).
/// A 1Password value is never read here: that may prompt (SPEC 11.11), so
/// `exec` reports a missing item when the server starts (exit 77).
pub fn check_available(
    source: &Source,
    env: &Env,
    fs: &dyn Fs,
    delivery: &DeliveryEnv,
    memory: &SecretMemory,
) -> Result<(), CoreError> {
    let Source::Provider {
        alias, reference, ..
    } = source
    else {
        // Read from the client's environment when the server starts.
        return Ok(());
    };
    let feature = match reference {
        SecretRef::OnePassword { .. } => OpFeature::ItemRead,
        SecretRef::OnePasswordEnvironment { .. } => OpFeature::Environments,
        SecretRef::Keyring { service, account } => {
            return match delivery.keyring().get(service, account) {
                Ok(Some(value)) => {
                    memory.record(value.expose());
                    Ok(())
                }
                Ok(None) => Err(CoreError::new(
                    ErrorCode::MissingSecret,
                    format!(
                        "{alias}: no {} entry for {reference}; store one with \
                         `{} secrets set {alias} --keyring`",
                        delivery.keyring().name(),
                        brand::BIN_NAME
                    ),
                )),
                Err(resolution) if resolution.status == SecretStatus::ProviderUnavailable => {
                    Err(resolution.into_error(alias))
                }
                // Locked or failing now: the server start tries again.
                Err(_) => Ok(()),
            };
        }
        SecretRef::Env { .. } => return Ok(()),
    };
    delivery
        .op(env, fs)
        .require(feature)
        .map(|_| ())
        .map_err(|resolution| {
            let not_found = resolution.status == SecretStatus::ProviderUnavailable;
            let err = resolution.into_error(alias);
            if !not_found {
                return err;
            }
            CoreError::new(
                err.code(),
                format!(
                    "{}; install it or map {alias} to keyring/env for this machine (`{} secrets \
                     set {alias} --this-machine --keyring` or `--ref env:NAME`)",
                    err.message(),
                    brand::BIN_NAME
                ),
            )
        })
}