Skip to main content

surjection_core/secrets/
delivery.rs

1//! Delivery modes (SPEC 11.4): how a secret reference reaches an MCP server
2//! for one client and field, and what blocks it on this machine.
3//!
4//! - `env`: the client expands a variable reference itself (or forwards a
5//!   variable by name, Codex).
6//! - `launch`: the client starts `surject exec`, which resolves the
7//!   references in its argv and starts the server with the values in its
8//!   environment (SPEC 11.5). Stdio `env` values only.
9//! - `command`: the client runs a Surjection command at connect time (omp and
10//!   Pi `!command`, Claude Code `headersHelper`).
11//! - `inline`: Surjection writes the value into the client's file. Explicit
12//!   per server, or the fallback for `${env:..}` the client cannot get
13//!   otherwise; never into a shared file.
14//!
15//! [`Policy::choose`] implements the `auto` rules and checks an explicit
16//! `delivery.mode`. Planning never reads a 1Password value (that may
17//! prompt): a `launch` or `command` entry is blocked only when the
18//! provider is not usable here ([`check_available`]).
19
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::sync::{Arc, OnceLock};
23
24use crate::adapters::caps::{Caps, CommandRef, EnvRefSyntax, FieldSet};
25use crate::brand;
26use crate::env::Env;
27use crate::error::{CoreError, ErrorCode};
28use crate::fs::Fs;
29use crate::model::server::{DeliveryMode, Transport};
30use crate::secrets::catalog::{CATALOG_FILE, Catalog};
31use crate::secrets::grammar::SecretRef;
32use crate::secrets::providers::keyring::KeyringBackend;
33use crate::secrets::providers::onepassword::{OpCli, OpFeature};
34use crate::secrets::scanner::SecretMemory;
35use crate::secrets::status::SecretStatus;
36
37/// The variable `op` reads a service account token from.
38pub const SERVICE_ACCOUNT_VAR: &str = "OP_SERVICE_ACCOUNT_TOKEN";
39/// Keyring account of the service account token (service
40/// [`brand::KEYRING_SERVICE`]): `keyring://surjection/OP_SERVICE_ACCOUNT_TOKEN`.
41pub const SERVICE_ACCOUNT_KEYRING_ACCOUNT: &str = "OP_SERVICE_ACCOUNT_TOKEN";
42
43/// A delivery mode, ordered so that the most consequential mode of an entry
44/// is the greatest (the one an entry reports).
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub enum Mode {
47    Env,
48    Command,
49    Launch,
50    Inline,
51}
52
53impl Mode {
54    pub const fn as_str(self) -> &'static str {
55        match self {
56            Mode::Env => "env",
57            Mode::Command => "command",
58            Mode::Launch => "launch",
59            Mode::Inline => "inline",
60        }
61    }
62}
63
64/// Whether a target file is private to this user or shared (tracked by a
65/// project's git repository, or flagged shared).
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum Sharing {
68    /// User-scope files and private project files.
69    Private,
70    /// Shared project files: no `inline` values, and the launcher is the
71    /// bare `surject` so the file stays portable (SPEC 11.5).
72    Shared,
73}
74
75/// Where the value of a template reference comes from.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum Source {
78    /// `${env:NAME}`, or an alias whose reference is `env:NAME`: a variable
79    /// of the environment the client (or Surjection) runs in.
80    Env { name: String },
81    /// An alias with a provider reference (`op://`, `op-env://`,
82    /// `keyring://`).
83    Provider {
84        alias: String,
85        reference: SecretRef,
86        /// The variable `env` delivery uses (`env_name`, else the alias).
87        env_name: String,
88    },
89}
90
91impl Source {
92    /// The variable `env` delivery spells.
93    pub fn variable(&self) -> &str {
94        match self {
95            Source::Env { name } => name,
96            Source::Provider { env_name, .. } => env_name,
97        }
98    }
99
100    /// The reference `surject exec` and `surject secret get` resolve.
101    pub fn reference(&self) -> SecretRef {
102        match self {
103            Source::Env { name } => SecretRef::Env { name: name.clone() },
104            Source::Provider { reference, .. } => reference.clone(),
105        }
106    }
107
108    pub fn is_provider(&self) -> bool {
109        matches!(self, Source::Provider { .. })
110    }
111
112    /// How messages name it: the alias, or the variable.
113    pub fn label(&self) -> &str {
114        match self {
115            Source::Env { name } => name,
116            Source::Provider { alias, .. } => alias,
117        }
118    }
119}
120
121/// The source of `${secret:ALIAS}` on this machine. An alias no catalog
122/// defines is `missing_secret` (SPEC 11.9).
123pub fn source_of_alias(catalog: &Catalog, alias: &str) -> Result<Source, CoreError> {
124    let entry = catalog.get(alias).ok_or_else(|| {
125        CoreError::new(
126            ErrorCode::MissingSecret,
127            format!(
128                "{alias} is not defined in {CATALOG_FILE}; set it with `{} secrets set {alias} ...`",
129                brand::BIN_NAME
130            ),
131        )
132    })?;
133    Ok(match entry.parsed()? {
134        SecretRef::Env { name } => Source::Env { name },
135        reference => Source::Provider {
136            alias: alias.to_owned(),
137            reference,
138            env_name: entry.env_name().to_owned(),
139        },
140    })
141}
142
143/// One value that holds references: the field it is in and its sources.
144#[derive(Debug, Clone, Copy)]
145pub struct Slot<'a> {
146    pub field: FieldSet,
147    pub transport: Transport,
148    /// The value is exactly one reference, without literal text around it.
149    pub whole: bool,
150    /// The client forwards the variable by name here (Codex `env_vars`
151    /// under the same key, `bearer_token_env_var`, `env_http_headers`).
152    pub forwardable: bool,
153    pub sources: &'a [Source],
154}
155
156/// What decides the mode of a value: the server's `delivery.mode`, the
157/// client, the target and this machine's choices.
158#[derive(Debug, Clone, Copy)]
159pub struct Policy<'a> {
160    pub requested: DeliveryMode,
161    pub caps: &'a Caps,
162    /// The client's display name, for messages.
163    pub client: &'a str,
164    pub sharing: Sharing,
165    /// `[delivery] export_provider_secrets` of the machine overlay.
166    pub export_provider_secrets: bool,
167}
168
169/// A client's spelling of a variable reference in `field`, when it expands
170/// references there itself (never a client that only forwards variables by
171/// name, Codex).
172pub fn env_syntax(caps: &Caps, field: FieldSet) -> Option<EnvRefSyntax> {
173    caps.env_ref
174        .filter(|syntax| *syntax != EnvRefSyntax::CodexForward)
175        .filter(|_| field != FieldSet::NONE && caps.env_ref_fields.contains(field))
176}
177
178impl Policy<'_> {
179    /// The client's spelling of a variable reference in `field`, when it
180    /// expands references there itself.
181    pub fn env_syntax(&self, field: FieldSet) -> Option<EnvRefSyntax> {
182        env_syntax(self.caps, field)
183    }
184
185    /// Whether the client forwards variables by name (Codex).
186    pub fn forwards(&self) -> bool {
187        self.caps.env_ref == Some(EnvRefSyntax::CodexForward)
188    }
189
190    /// Whether the client can get this value by running a command. Never
191    /// for 1Password Environment variables: only `op run` hands them to a
192    /// process, so `surject secret get` cannot print them.
193    fn command_ok(&self, slot: &Slot<'_>) -> bool {
194        let environment = slot.sources.iter().any(|source| {
195            matches!(
196                source,
197                Source::Provider {
198                    reference: SecretRef::OnePasswordEnvironment { .. },
199                    ..
200                }
201            )
202        });
203        if environment {
204            return false;
205        }
206        match self.caps.command_ref {
207            Some(CommandRef::Bang) => matches!(slot.field, FieldSet::ENV | FieldSet::HEADERS),
208            Some(CommandRef::HeadersHelper) => {
209                slot.field == FieldSet::HEADERS && slot.transport != Transport::Stdio
210            }
211            None => false,
212        }
213    }
214
215    /// The mode for one value (SPEC 11.4 `auto` rules, or the explicit
216    /// mode when it can deliver the value).
217    pub fn choose(&self, slot: &Slot<'_>) -> Result<Mode, CoreError> {
218        let env_ok = self.env_syntax(slot.field).is_some() || slot.forwardable;
219        let launch_ok =
220            slot.transport == Transport::Stdio && slot.field == FieldSet::ENV && slot.whole;
221        let command_ok = self.command_ok(slot);
222        let provider = slot.sources.iter().any(Source::is_provider);
223        let field = field_name(slot.field);
224        let unavailable = |mode: &str, why: &str| {
225            Err(CoreError::new(
226                ErrorCode::DeliveryUnavailable,
227                format!(
228                    "`{mode}` delivery cannot bring a reference in `{field}` to {}: {why}",
229                    self.client
230                ),
231            ))
232        };
233        match self.requested {
234            DeliveryMode::Env if env_ok => Ok(Mode::Env),
235            DeliveryMode::Env => unavailable(
236                "env",
237                if self.forwards() {
238                    "it forwards whole variables under their own name only"
239                } else {
240                    "it does not expand variables in this field"
241                },
242            ),
243            DeliveryMode::Launch if launch_ok => Ok(Mode::Launch),
244            DeliveryMode::Launch => unavailable(
245                "launch",
246                "`surject exec` sets whole `env` values of stdio servers only",
247            ),
248            DeliveryMode::Command if command_ok => Ok(Mode::Command),
249            DeliveryMode::Command => unavailable("command", "it runs no command for this field"),
250            DeliveryMode::Inline => self.inline(),
251            DeliveryMode::Auto if !provider => {
252                if env_ok {
253                    Ok(Mode::Env)
254                } else if launch_ok {
255                    Ok(Mode::Launch)
256                } else {
257                    self.inline()
258                }
259            }
260            DeliveryMode::Auto => {
261                if launch_ok {
262                    Ok(Mode::Launch)
263                } else if command_ok && slot.transport != Transport::Stdio {
264                    Ok(Mode::Command)
265                } else if (slot.forwardable && slot.field == FieldSet::HEADERS)
266                    || (self.export_provider_secrets && env_ok)
267                {
268                    // Codex forwards header variables by name (SPEC 11.4
269                    // rule 2); elsewhere `env` needs the user's export.
270                    Ok(Mode::Env)
271                } else {
272                    let labels: Vec<&str> = slot
273                        .sources
274                        .iter()
275                        .filter(|source| source.is_provider())
276                        .map(Source::label)
277                        .collect();
278                    Err(CoreError::new(
279                        ErrorCode::NoSecretFreeDelivery,
280                        format!(
281                            "{} cannot get {} in `{field}` without the value in its config file; \
282                             fixes: export it to the environment (`{bin} env --export`, then \
283                             `[delivery] export_provider_secrets = true` in this machine's overlay), \
284                             or allow inline for this server (`[delivery] mode = \"inline\"`)",
285                            self.client,
286                            labels.join(", "),
287                            bin = brand::BIN_NAME,
288                        ),
289                    ))
290                }
291            }
292        }
293    }
294
295    fn inline(&self) -> Result<Mode, CoreError> {
296        match self.sharing {
297            Sharing::Private => Ok(Mode::Inline),
298            Sharing::Shared => Err(CoreError::new(
299                ErrorCode::SecretInSharedFile,
300                "inline delivery would write a secret value into a shared file; use `env` or \
301                 `launch` delivery, or move the server to the project-local layer",
302            )),
303        }
304    }
305}
306
307/// The name of a field in messages.
308pub fn field_name(field: FieldSet) -> &'static str {
309    match field {
310        FieldSet::COMMAND => "command",
311        FieldSet::ARGS => "args",
312        FieldSet::ENV => "env",
313        FieldSet::CWD => "cwd",
314        FieldSet::URL => "url",
315        FieldSet::HEADERS => "headers",
316        _ => "client fields",
317    }
318}
319
320/// What delivery needs from this machine: the launcher path, the keyring
321/// and the 1Password CLI (detected once, on first use).
322pub struct DeliveryEnv {
323    launcher: Option<PathBuf>,
324    keyring: Arc<dyn KeyringBackend>,
325    op: OnceLock<OpCli>,
326    /// Times the keyring was handed out: a read of secret state that no
327    /// file shows (the plan cache, [`crate::apply::cache`]).
328    keyring_uses: AtomicU64,
329}
330
331impl DeliveryEnv {
332    /// `launcher` is the absolute path of the installed `surject` binary
333    /// (as the target machine spells it), `None` when it cannot be
334    /// resolved.
335    pub fn new(launcher: Option<PathBuf>, keyring: Arc<dyn KeyringBackend>) -> Self {
336        Self {
337            launcher,
338            keyring,
339            op: OnceLock::new(),
340            keyring_uses: AtomicU64::new(0),
341        }
342    }
343
344    /// Uses `op` instead of detecting the CLI.
345    pub fn with_op(self, op: OpCli) -> Self {
346        let _ = self.op.set(op);
347        self
348    }
349
350    pub fn launcher_path(&self) -> Option<&Path> {
351        self.launcher.as_deref()
352    }
353
354    /// The keyring. Every secret value read while rendering (a keyring
355    /// entry, a 1Password item, the service account token) goes through
356    /// it, and each call counts in [`DeliveryEnv::provider_reads`].
357    pub fn keyring(&self) -> &dyn KeyringBackend {
358        self.keyring_uses.fetch_add(1, Ordering::Relaxed);
359        self.keyring.as_ref()
360    }
361
362    /// How often the keyring was handed out so far, by any caller: a plan
363    /// that saw this change may depend on secret values.
364    pub fn provider_reads(&self) -> u64 {
365        self.keyring_uses.load(Ordering::Relaxed)
366    }
367
368    /// The 1Password CLI of this machine (`op --version` runs once).
369    pub fn op(&self, env: &Env, fs: &dyn Fs) -> &OpCli {
370        self.op.get_or_init(|| OpCli::detect(env, fs))
371    }
372
373    /// How a target starts `surject`: the absolute path for private files,
374    /// the bare name for shared ones (SPEC 11.5).
375    pub fn launcher(&self, sharing: Sharing) -> Result<String, CoreError> {
376        match (sharing, &self.launcher) {
377            (Sharing::Shared, _) => Ok(brand::BIN_NAME.to_owned()),
378            (Sharing::Private, Some(path)) => Ok(path.to_string_lossy().into_owned()),
379            (Sharing::Private, None) => Err(CoreError::new(
380                ErrorCode::LauncherNotFound,
381                format!(
382                    "the path of the `{}` binary is not known, so the server cannot be started \
383                     through `{} exec`",
384                    brand::BIN_NAME,
385                    brand::BIN_NAME
386                ),
387            )),
388        }
389    }
390}
391
392impl std::fmt::Debug for DeliveryEnv {
393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394        f.debug_struct("DeliveryEnv")
395            .field("launcher", &self.launcher)
396            .field("keyring", &self.keyring.name())
397            .field("op", &self.op.get())
398            .finish()
399    }
400}
401
402/// The `op` environment variable naming the account to use.
403pub const ACCOUNT_VAR: &str = "OP_ACCOUNT";
404
405/// `env` for an `op` child: with the service account token from the OS
406/// keyring (SPEC 11.5) unless `env` already has one, and with `account`
407/// as `OP_ACCOUNT` unless `env` already names one (gate V1 FB-7: with
408/// several accounts signed in to the desktop app, `op` refuses to guess).
409/// An unreadable keyring means no token.
410pub fn op_env(env: &Env, keyring: &dyn KeyringBackend, account: Option<&str>) -> Env {
411    let env = match account {
412        Some(account) if env.var(ACCOUNT_VAR).is_none() => env.with_var(ACCOUNT_VAR, account),
413        _ => env.clone(),
414    };
415    if env.var(SERVICE_ACCOUNT_VAR).is_some() {
416        return env;
417    }
418    match keyring.get_own(SERVICE_ACCOUNT_KEYRING_ACCOUNT) {
419        Ok(Some(token)) => env.with_var(SERVICE_ACCOUNT_VAR, token.expose()),
420        _ => env,
421    }
422}
423
424/// Whether `source` can be delivered when the server starts (`launch`,
425/// `command`): the provider is installed and new enough, and a keyring
426/// entry exists (its value is recorded for the leak scanner, never kept).
427/// A 1Password value is never read here: that may prompt (SPEC 11.11), so
428/// `exec` reports a missing item when the server starts (exit 77).
429pub fn check_available(
430    source: &Source,
431    env: &Env,
432    fs: &dyn Fs,
433    delivery: &DeliveryEnv,
434    memory: &SecretMemory,
435) -> Result<(), CoreError> {
436    let Source::Provider {
437        alias, reference, ..
438    } = source
439    else {
440        // Read from the client's environment when the server starts.
441        return Ok(());
442    };
443    let feature = match reference {
444        SecretRef::OnePassword { .. } => OpFeature::ItemRead,
445        SecretRef::OnePasswordEnvironment { .. } => OpFeature::Environments,
446        SecretRef::Keyring { service, account } => {
447            return match delivery.keyring().get(service, account) {
448                Ok(Some(value)) => {
449                    memory.record(value.expose());
450                    Ok(())
451                }
452                Ok(None) => Err(CoreError::new(
453                    ErrorCode::MissingSecret,
454                    format!(
455                        "{alias}: no {} entry for {reference}; store one with \
456                         `{} secrets set {alias} --keyring`",
457                        delivery.keyring().name(),
458                        brand::BIN_NAME
459                    ),
460                )),
461                Err(resolution) if resolution.status == SecretStatus::ProviderUnavailable => {
462                    Err(resolution.into_error(alias))
463                }
464                // Locked or failing now: the server start tries again.
465                Err(_) => Ok(()),
466            };
467        }
468        SecretRef::Env { .. } => return Ok(()),
469    };
470    delivery
471        .op(env, fs)
472        .require(feature)
473        .map(|_| ())
474        .map_err(|resolution| {
475            let not_found = resolution.status == SecretStatus::ProviderUnavailable;
476            let err = resolution.into_error(alias);
477            if !not_found {
478                return err;
479            }
480            CoreError::new(
481                err.code(),
482                format!(
483                    "{}; install it or map {alias} to keyring/env for this machine (`{} secrets \
484                     set {alias} --this-machine --keyring` or `--ref env:NAME`)",
485                    err.message(),
486                    brand::BIN_NAME
487                ),
488            )
489        })
490}