Skip to main content

surjection_core/secrets/
render.rs

1//! Template rendering for one server and client with secret delivery (SPEC
2//! 11.2, 11.4): path variables become paths, and each value holding
3//! references is written in the mode [`Policy::choose`] picks:
4//!
5//! - `env`: the client's own variable syntax (`${NAME}`, `${env:NAME}`),
6//!   or a forwarded variable name (Codex);
7//! - `launch`: the key leaves the entry's `env`, and the entry starts
8//!   `surject exec --ref KEY=REF ... -- <command> <args>` instead;
9//! - `command`: omp and Pi get `!<surjection> secret get --ref REF`, Claude
10//!   Code gets one `headersHelper` running `<surjection> secret-header`;
11//! - `inline`: the resolved value, kept for masking in diffs.
12//!
13//! Command templates mark a value with `{secret:KEY}`, bound by `--ref
14//! KEY=REF`: no `$`, `%` or `!`, so neither a client nor a shell expands it.
15
16use std::path::Path;
17use std::sync::Arc;
18
19use crate::adapters::caps::{Caps, CommandRef, EnvRefSyntax, FieldSet};
20use crate::adapters::mapper::{RemoteLaunch, StdioLaunch};
21use crate::brand;
22use crate::env::{Env, Os};
23use crate::error::{CoreError, ErrorCode};
24use crate::fs::Fs;
25use crate::model::server::{DeliveryMode, Transport};
26use crate::secrets::SecretValue;
27use crate::secrets::catalog::Catalog;
28use crate::secrets::delivery::{
29    DeliveryEnv, Mode, Policy, Sharing, Slot, Source, check_available, env_syntax, field_name,
30    op_env, source_of_alias,
31};
32use crate::secrets::grammar::{PathVar, SecretRef, TemplatePart, parse_template};
33use crate::secrets::providers::{Resolver, env};
34use crate::secrets::scanner::SecretMemory;
35
36/// The placeholder opening of a bound value in command templates.
37pub const PLACEHOLDER: &str = "{secret:";
38
39/// What rendering reads: Surjection's environment (paths, inline `env:`
40/// values), the catalog and this machine's providers.
41#[derive(Clone, Copy)]
42pub struct RenderEnv<'a> {
43    pub env: &'a Env,
44    pub fs: &'a dyn Fs,
45    pub surjection_home: &'a Path,
46    pub catalog: &'a Catalog,
47    pub delivery: &'a DeliveryEnv,
48    pub memory: &'a Arc<SecretMemory>,
49    /// The project folder `${project}` stands for; `None` at system scope.
50    pub project: Option<&'a Path>,
51}
52
53/// A stdio `env` value as written.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum EnvValue {
56    Value(String),
57    /// Forwarded from the client's environment under the same name (Codex
58    /// `env_vars`).
59    Forward(String),
60    /// Set by `surject exec` when the server starts.
61    Launched,
62}
63
64/// A header value as written.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub enum HeaderValue {
67    Value(String),
68    /// `Authorization: Bearer <variable>` (Codex `bearer_token_env_var`).
69    Bearer(String),
70    /// The whole value from a variable (Codex `env_http_headers`).
71    FromEnv(String),
72    /// Printed by the entry's `headersHelper`.
73    Helper,
74}
75
76#[derive(Debug, Clone)]
77enum Piece {
78    Text(String),
79    Ref(Source),
80}
81
82/// Renders the values of one server for one client.
83pub struct Renderer<'a> {
84    rx: RenderEnv<'a>,
85    policy: Policy<'a>,
86    transport: Transport,
87    modes: Vec<Mode>,
88    launch: Vec<(String, Source)>,
89    helper_refs: Vec<(String, Source)>,
90    helper_headers: Vec<(String, String)>,
91    /// Values written in plain text (`inline`), for masking.
92    pub inline: Vec<SecretValue>,
93    /// `inline_env_fallback` warnings.
94    pub warnings: Vec<CoreError>,
95}
96
97impl<'a> Renderer<'a> {
98    pub fn new(rx: RenderEnv<'a>, policy: Policy<'a>, transport: Transport) -> Self {
99        Self {
100            rx,
101            policy,
102            transport,
103            modes: Vec::new(),
104            launch: Vec::new(),
105            helper_refs: Vec::new(),
106            helper_headers: Vec::new(),
107            inline: Vec::new(),
108            warnings: Vec::new(),
109        }
110    }
111
112    /// The entry's delivery: its most consequential mode, if it holds
113    /// references.
114    pub fn delivery(&self) -> Option<Mode> {
115        self.modes.iter().copied().max()
116    }
117
118    /// A `command`, `args`, `cwd`, `url` or client field value.
119    pub fn value(&mut self, text: &str, field: FieldSet) -> Result<String, CoreError> {
120        let pieces = self.pieces(text)?;
121        let sources = sources(&pieces);
122        if sources.is_empty() {
123            return self.literal(&pieces, field);
124        }
125        let mode = self.choose(field, &pieces, &sources, false)?;
126        match mode {
127            Mode::Env => self.spell(&pieces, field),
128            Mode::Inline => self.inline_value(&pieces, field),
129            Mode::Launch | Mode::Command => Err(CoreError::new(
130                ErrorCode::DeliveryUnavailable,
131                format!(
132                    "`{}` cannot be delivered to `{}`",
133                    mode.as_str(),
134                    field_name(field)
135                ),
136            )),
137        }
138    }
139
140    /// The value of stdio `env.<key>`.
141    pub fn env_value(&mut self, key: &str, text: &str) -> Result<EnvValue, CoreError> {
142        let pieces = self.pieces(text)?;
143        let sources = sources(&pieces);
144        if sources.is_empty() {
145            return self.literal(&pieces, FieldSet::ENV).map(EnvValue::Value);
146        }
147        let whole = is_whole(&pieces);
148        let forwardable = self.policy.forwards() && whole && sources[0].variable() == key;
149        match self.choose(FieldSet::ENV, &pieces, &sources, forwardable)? {
150            Mode::Env if forwardable => Ok(EnvValue::Forward(sources[0].variable().to_owned())),
151            Mode::Env => self.spell(&pieces, FieldSet::ENV).map(EnvValue::Value),
152            Mode::Launch => {
153                let source = sources[0].clone();
154                self.available(&source)?;
155                self.launch.push((key.to_owned(), source));
156                Ok(EnvValue::Launched)
157            }
158            Mode::Command => self.bang(&pieces).map(EnvValue::Value),
159            Mode::Inline => self
160                .inline_value(&pieces, FieldSet::ENV)
161                .map(EnvValue::Value),
162        }
163    }
164
165    /// The value of header `name`.
166    pub fn header(&mut self, name: &str, text: &str) -> Result<HeaderValue, CoreError> {
167        let pieces = self.pieces(text)?;
168        let sources = sources(&pieces);
169        if sources.is_empty() {
170            return self
171                .literal(&pieces, FieldSet::HEADERS)
172                .map(HeaderValue::Value);
173        }
174        let whole = is_whole(&pieces);
175        let bearer = name.eq_ignore_ascii_case("authorization")
176            && matches!(pieces.as_slice(), [Piece::Text(prefix), Piece::Ref(_)] if prefix == "Bearer ");
177        let forwardable = self.policy.forwards() && (whole || bearer);
178        match self.choose(FieldSet::HEADERS, &pieces, &sources, forwardable)? {
179            Mode::Env if forwardable => {
180                let variable = sources[0].variable().to_owned();
181                Ok(if bearer {
182                    HeaderValue::Bearer(variable)
183                } else {
184                    HeaderValue::FromEnv(variable)
185                })
186            }
187            Mode::Env => self
188                .spell(&pieces, FieldSet::HEADERS)
189                .map(HeaderValue::Value),
190            Mode::Command if self.policy.caps.command_ref == Some(CommandRef::HeadersHelper) => {
191                let template = self.template(&pieces, true)?;
192                self.helper_headers.push((name.to_owned(), template));
193                Ok(HeaderValue::Helper)
194            }
195            Mode::Command => self.bang(&pieces).map(HeaderValue::Value),
196            Mode::Inline => self
197                .inline_value(&pieces, FieldSet::HEADERS)
198                .map(HeaderValue::Value),
199            Mode::Launch => Err(CoreError::new(
200                ErrorCode::DeliveryUnavailable,
201                "`launch` delivery cannot bring a header value",
202            )),
203        }
204    }
205
206    /// Wraps the command in `surject exec` when a value is launched.
207    pub fn finish_stdio(&mut self, stdio: &mut StdioLaunch) -> Result<(), CoreError> {
208        if self.launch.is_empty() {
209            return Ok(());
210        }
211        let launcher = self.rx.delivery.launcher(self.policy.sharing)?;
212        let mut args = vec!["exec".to_owned()];
213        let mut environment: Option<String> = None;
214        let mut maps = Vec::new();
215        if let Some(account) = self.op_account(self.launch.iter().map(|(_, s)| s)) {
216            args.push("--op-account".to_owned());
217            args.push(account.to_owned());
218        }
219        for (key, source) in &self.launch {
220            match source.reference() {
221                SecretRef::OnePasswordEnvironment {
222                    environment: id,
223                    name,
224                } => {
225                    if environment.as_ref().is_some_and(|other| *other != id) {
226                        return Err(CoreError::new(
227                            ErrorCode::DeliveryUnavailable,
228                            "`surject exec` takes variables from one 1Password Environment per \
229                             server; this server uses several",
230                        ));
231                    }
232                    environment = Some(id);
233                    maps.push(format!("{key}={name}"));
234                }
235                reference => {
236                    args.push("--ref".to_owned());
237                    args.push(format!("{key}={reference}"));
238                }
239            }
240        }
241        if let Some(id) = environment {
242            args.push("--op-env".to_owned());
243            args.push(id);
244            for map in maps {
245                args.push("--map".to_owned());
246                args.push(map);
247            }
248        }
249        args.push("--".to_owned());
250        args.push(std::mem::take(&mut stdio.command));
251        args.append(&mut stdio.args);
252        stdio.command = launcher;
253        stdio.args = args;
254        Ok(())
255    }
256
257    /// Sets the `headersHelper` of the entry when a header uses it.
258    pub fn finish_remote(&mut self, remote: &mut RemoteLaunch) -> Result<(), CoreError> {
259        if self.helper_headers.is_empty() {
260            return Ok(());
261        }
262        let os = self.rx.env.os();
263        let mut command = vec![
264            shell_quote(os, &self.rx.delivery.launcher(self.policy.sharing)?)?,
265            "secret-header".to_owned(),
266        ];
267        if let Some(account) = self.op_account(self.helper_refs.iter().map(|(_, s)| s)) {
268            command.push("--op-account".to_owned());
269            command.push(shell_quote(os, account)?);
270        }
271        for (key, source) in &self.helper_refs {
272            command.push("--ref".to_owned());
273            command.push(shell_quote(os, &format!("{key}={}", source.reference()))?);
274        }
275        for (name, template) in &self.helper_headers {
276            command.push(shell_quote(os, &format!("{name}={template}"))?);
277        }
278        remote.headers_helper = Some(command.join(" "));
279        Ok(())
280    }
281
282    fn choose(
283        &mut self,
284        field: FieldSet,
285        pieces: &[Piece],
286        sources: &[Source],
287        forwardable: bool,
288    ) -> Result<Mode, CoreError> {
289        let mode = self.policy.choose(&Slot {
290            field,
291            transport: self.transport,
292            whole: is_whole(pieces),
293            forwardable,
294            sources,
295        })?;
296        if mode == Mode::Inline && self.policy.requested == DeliveryMode::Auto {
297            let names: Vec<&str> = sources.iter().map(Source::variable).collect();
298            self.warnings.push(CoreError::new(
299                ErrorCode::InlineEnvFallback,
300                format!(
301                    "{} cannot get `${{env:{}}}` in `{}` otherwise; the value from {}'s \
302                     environment is written into its config file",
303                    self.policy.client,
304                    names.join("}`, `${env:"),
305                    field_name(field),
306                    brand::PRODUCT_NAME
307                ),
308            ));
309        }
310        self.modes.push(mode);
311        Ok(mode)
312    }
313
314    /// The template as pieces: path variables filled in, references looked
315    /// up in the catalog.
316    fn pieces(&self, text: &str) -> Result<Vec<Piece>, CoreError> {
317        let mut pieces: Vec<Piece> = Vec::new();
318        let push_text = |pieces: &mut Vec<Piece>, text: &str| match pieces.last_mut() {
319            Some(Piece::Text(last)) => last.push_str(text),
320            _ => pieces.push(Piece::Text(text.to_owned())),
321        };
322        for part in parse_template(text)? {
323            match part {
324                TemplatePart::Literal(literal) => push_text(&mut pieces, &literal),
325                TemplatePart::Var(PathVar::Home) => {
326                    push_text(&mut pieces, &self.rx.env.home().to_string_lossy());
327                }
328                TemplatePart::Var(PathVar::SurjectionHome) => {
329                    push_text(&mut pieces, &self.rx.surjection_home.to_string_lossy());
330                }
331                TemplatePart::Var(PathVar::Project) => match self.rx.project {
332                    Some(project) => push_text(&mut pieces, &project.to_string_lossy()),
333                    None => {
334                        return Err(CoreError::new(
335                            ErrorCode::InvalidRef,
336                            format!("`${{project}}` in {text:?} has no value at system scope"),
337                        ));
338                    }
339                },
340                TemplatePart::Env(name) => pieces.push(Piece::Ref(Source::Env { name })),
341                TemplatePart::Secret(alias) => {
342                    pieces.push(Piece::Ref(source_of_alias(self.rx.catalog, &alias)?));
343                }
344            }
345        }
346        Ok(pieces)
347    }
348
349    /// Literal text; escaped where the client has an escape (Pi), refused
350    /// where the client would expand part of it otherwise
351    /// ([`expanded_token`]).
352    fn literal(&self, pieces: &[Piece], field: FieldSet) -> Result<String, CoreError> {
353        let mut out = String::new();
354        for piece in pieces {
355            if let Piece::Text(text) = piece {
356                self.push_literal(&mut out, text, field)?;
357            }
358        }
359        Ok(self.guard_command(out, field))
360    }
361
362    /// Whether the client reads `$$` as a literal `$` and `$!` as a literal
363    /// `!` in `field` (Pi), so literal text is written escaped.
364    fn escapes(&self, field: FieldSet) -> bool {
365        self.policy.env_syntax(field) == Some(EnvRefSyntax::Dollar)
366    }
367
368    /// Appends literal text the way the client reads it back unchanged.
369    fn push_literal(&self, out: &mut String, text: &str, field: FieldSet) -> Result<(), CoreError> {
370        push_literal(self.policy.env_syntax(field), self.policy.client, out, text)
371    }
372
373    /// `value` with a leading literal `!` written as `$!` where the client
374    /// would otherwise run the value as a command (Pi). References are
375    /// spelled with a leading `$`, so a leading `!` is always literal text;
376    /// Surjection's own commands come from [`Renderer::bang`], never from here.
377    fn guard_command(&self, value: String, field: FieldSet) -> String {
378        guard_command(self.policy.env_syntax(field), value)
379    }
380
381    /// `env` delivery in the client's syntax.
382    fn spell(&self, pieces: &[Piece], field: FieldSet) -> Result<String, CoreError> {
383        let spelled: Vec<Spell<'_>> = pieces
384            .iter()
385            .map(|piece| match piece {
386                Piece::Text(text) => Spell::Text(text),
387                Piece::Ref(source) => Spell::Variable(source.variable()),
388            })
389            .collect();
390        spell(self.policy.caps, self.policy.client, field, &spelled)
391    }
392
393    /// `inline` delivery: values resolved now. A resolved value is literal
394    /// text too, escaped like any other; the escaped spelling is kept for
395    /// masking as well when it differs.
396    fn inline_value(&mut self, pieces: &[Piece], field: FieldSet) -> Result<String, CoreError> {
397        let mut out = String::new();
398        for piece in pieces {
399            match piece {
400                Piece::Text(text) => self.push_literal(&mut out, text, field)?,
401                Piece::Ref(source) => {
402                    let value = self.resolve(source)?;
403                    if self.escapes(field) && value.expose().contains('$') {
404                        let escaped = value.expose().replace('$', "$$");
405                        self.rx.memory.record(&escaped);
406                        out.push_str(&escaped);
407                        self.inline.push(SecretValue::new(escaped));
408                    } else {
409                        // The value is secret: the message names the
410                        // reference, never the value.
411                        if let Some(token) =
412                            expanded_token(self.policy.env_syntax(field), value.expose())
413                        {
414                            return Err(CoreError::new(
415                                ErrorCode::DeliveryUnavailable,
416                                format!(
417                                    "{} would expand `{token}` in the value of `{}` written \
418                                     inline; it has no escape for it (use another delivery mode)",
419                                    self.policy.client,
420                                    source.variable()
421                                ),
422                            ));
423                        }
424                        out.push_str(value.expose());
425                    }
426                    self.inline.push(value);
427                }
428            }
429        }
430        Ok(self.guard_command(out, field))
431    }
432
433    fn resolve(&self, source: &Source) -> Result<SecretValue, CoreError> {
434        let value = match source {
435            Source::Env { name } => {
436                env::resolve(self.rx.env, name).map_err(|resolution| resolution.into_error(name))?
437            }
438            Source::Provider {
439                alias,
440                reference: SecretRef::OnePasswordEnvironment { .. },
441                ..
442            } => {
443                return Err(CoreError::new(
444                    ErrorCode::DeliveryUnavailable,
445                    format!(
446                        "{alias}: 1Password Environment variables reach a server only through \
447                         `op run` when it starts (`launch` delivery); they are never written inline"
448                    ),
449                ));
450            }
451            Source::Provider {
452                alias, reference, ..
453            } => {
454                let keyring = self.rx.delivery.keyring();
455                let env = op_env(self.rx.env, keyring, self.rx.catalog.op_account.as_deref());
456                let op = self.rx.delivery.op(self.rx.env, self.rx.fs);
457                Resolver::new(&env, keyring, op, self.rx.memory.clone())
458                    .resolve(reference)
459                    .map_err(|resolution| resolution.into_error(alias))?
460            }
461        };
462        self.rx.memory.record(value.expose());
463        Ok(value)
464    }
465
466    fn available(&self, source: &Source) -> Result<(), CoreError> {
467        check_available(
468            source,
469            self.rx.env,
470            self.rx.fs,
471            self.rx.delivery,
472            self.rx.memory,
473        )
474    }
475
476    /// `--op-account` for a `surject` command resolving `sources`: the
477    /// configured 1Password account when any of them is a 1Password
478    /// reference (gate V1 FB-7). Never in a shared file: the account is
479    /// this machine's, so a committed file relies on `OP_ACCOUNT` or each
480    /// machine's own setting, which `surject exec` reads at run time.
481    fn op_account<'s>(&self, mut sources: impl Iterator<Item = &'s Source>) -> Option<&'a str> {
482        if self.policy.sharing == Sharing::Shared {
483            return None;
484        }
485        let account = self.rx.catalog.op_account.as_deref()?;
486        sources
487            .any(|source| {
488                matches!(
489                    source.reference(),
490                    SecretRef::OnePassword { .. } | SecretRef::OnePasswordEnvironment { .. }
491                )
492            })
493            .then_some(account)
494    }
495
496    /// `!<surjection> secret get --ref REF` (omp, Pi), with a template when the
497    /// value has text around the reference.
498    fn bang(&mut self, pieces: &[Piece]) -> Result<String, CoreError> {
499        let os = self.rx.env.os();
500        let launcher = shell_quote(os, &self.rx.delivery.launcher(self.policy.sharing)?)?;
501        let mut command = format!("!{launcher} secret get");
502        if let [Piece::Ref(source)] = pieces {
503            self.available(source)?;
504            if let Some(account) = self.op_account(std::iter::once(source)) {
505                command.push_str(&format!(" --op-account {}", shell_quote(os, account)?));
506            }
507            command.push_str(&format!(
508                " --ref {}",
509                shell_quote(os, &source.reference().to_string())?
510            ));
511            return Ok(command);
512        }
513        let start = self.helper_refs.len();
514        let template = self.template(pieces, false)?;
515        let bound: Vec<(String, Source)> = self.helper_refs.drain(start..).collect();
516        if let Some(account) = self.op_account(bound.iter().map(|(_, s)| s)) {
517            command.push_str(&format!(" --op-account {}", shell_quote(os, account)?));
518        }
519        for (key, source) in &bound {
520            command.push_str(&format!(
521                " --ref {}",
522                shell_quote(os, &format!("{key}={}", source.reference()))?
523            ));
524        }
525        command.push_str(&format!(" --template {}", shell_quote(os, &template)?));
526        Ok(command)
527    }
528
529    /// The pieces as a command template; references are bound in
530    /// `helper_refs` (shared by every header of a `headersHelper` when
531    /// `shared`).
532    fn template(&mut self, pieces: &[Piece], shared: bool) -> Result<String, CoreError> {
533        let start = if shared { 0 } else { self.helper_refs.len() };
534        let mut out = String::new();
535        for piece in pieces {
536            match piece {
537                Piece::Text(text) => {
538                    if text.contains(PLACEHOLDER) {
539                        return Err(CoreError::new(
540                            ErrorCode::DeliveryUnavailable,
541                            format!(
542                                "the literal {PLACEHOLDER:?} in {text:?} cannot be written in a command template"
543                            ),
544                        ));
545                    }
546                    out.push_str(text);
547                }
548                Piece::Ref(source) => {
549                    self.available(source)?;
550                    let key = source.label().to_owned();
551                    let bound = self.helper_refs[start..].iter().find(|(k, _)| *k == key);
552                    match bound {
553                        Some((_, existing)) if existing != source => {
554                            return Err(CoreError::new(
555                                ErrorCode::DeliveryUnavailable,
556                                format!("{key} names two different references here"),
557                            ));
558                        }
559                        Some(_) => {}
560                        None => self.helper_refs.push((key.clone(), source.clone())),
561                    }
562                    out.push_str(&format!("{PLACEHOLDER}{key}}}"));
563                }
564            }
565        }
566        Ok(out)
567    }
568}
569
570/// One part of a value spelled in a client's own variable syntax
571/// ([`spell`]).
572#[derive(Debug, Clone, Copy, PartialEq, Eq)]
573pub enum Spell<'a> {
574    /// Literal text.
575    Text(&'a str),
576    /// A variable the client expands itself.
577    Variable(&'a str),
578}
579
580/// `pieces` as `client` writes them in `field` (SPEC 11.4 `env` delivery):
581/// each variable in the client's syntax, literal text escaped where the
582/// client has an escape (Pi) and refused where the client would expand part
583/// of it. `delivery_unavailable` when the client does not expand variables
584/// in `field`.
585pub fn spell(
586    caps: &Caps,
587    client: &str,
588    field: FieldSet,
589    pieces: &[Spell<'_>],
590) -> Result<String, CoreError> {
591    let syntax = env_syntax(caps, field);
592    let mut out = String::new();
593    for piece in pieces {
594        match piece {
595            Spell::Text(text) => push_literal(syntax, client, &mut out, text)?,
596            Spell::Variable(name) => match syntax {
597                Some(EnvRefSyntax::DollarBrace { .. } | EnvRefSyntax::Dollar) => {
598                    out.push_str(&format!("${{{name}}}"));
599                }
600                Some(EnvRefSyntax::DollarBraceEnv) => out.push_str(&format!("${{env:{name}}}")),
601                Some(EnvRefSyntax::BraceEnv) => out.push_str(&format!("{{env:{name}}}")),
602                Some(EnvRefSyntax::CodexForward) | None => {
603                    return Err(CoreError::new(
604                        ErrorCode::DeliveryUnavailable,
605                        format!(
606                            "{client} does not expand variables in `{}`",
607                            field_name(field)
608                        ),
609                    ));
610                }
611            },
612        }
613    }
614    Ok(guard_command(syntax, out))
615}
616
617/// Appends literal text the way a client expanding `syntax` reads it back
618/// unchanged: escaped for Pi, refused where the client has no escape.
619fn push_literal(
620    syntax: Option<EnvRefSyntax>,
621    client: &str,
622    out: &mut String,
623    text: &str,
624) -> Result<(), CoreError> {
625    if syntax == Some(EnvRefSyntax::Dollar) {
626        out.push_str(&text.replace('$', "$$"));
627    } else {
628        check_literal(syntax, client, text)?;
629        out.push_str(text);
630    }
631    Ok(())
632}
633
634fn check_literal(syntax: Option<EnvRefSyntax>, client: &str, text: &str) -> Result<(), CoreError> {
635    if let Some(token) = expanded_token(syntax, text) {
636        return Err(CoreError::new(
637            ErrorCode::DeliveryUnavailable,
638            format!(
639                "{client} would expand the literal `{token}` in {text:?}; it has no escape for it"
640            ),
641        ));
642    }
643    Ok(())
644}
645
646/// `value` with a leading `!` written as `$!` for Pi (`Dollar`), which
647/// would otherwise run the value as a command.
648fn guard_command(syntax: Option<EnvRefSyntax>, mut value: String) -> String {
649    if syntax == Some(EnvRefSyntax::Dollar) && value.starts_with('!') {
650        value.insert(0, '$');
651    }
652    value
653}
654
655fn sources(pieces: &[Piece]) -> Vec<Source> {
656    pieces
657        .iter()
658        .filter_map(|piece| match piece {
659            Piece::Ref(source) => Some(source.clone()),
660            Piece::Text(_) => None,
661        })
662        .collect()
663}
664
665fn is_whole(pieces: &[Piece]) -> bool {
666    matches!(pieces, [Piece::Ref(_)])
667}
668
669/// The part of literal `text` a client expanding `syntax` would replace,
670/// when the client has no escape for it: `${` (`DollarBrace`,
671/// `DollarBraceEnv`), also `$` before a name character (`DollarBrace` with
672/// `bare`), `{env:` or `{file:` (`BraceEnv`). `None` for text the client
673/// reads as written, and for Pi (`Dollar`), whose literals are escaped.
674fn expanded_token(syntax: Option<EnvRefSyntax>, text: &str) -> Option<&'static str> {
675    match syntax? {
676        EnvRefSyntax::DollarBrace { bare, .. } => {
677            if text.contains("${") {
678                Some("${")
679            } else if bare
680                && text.as_bytes().windows(2).any(|pair| {
681                    pair[0] == b'$' && (pair[1].is_ascii_alphanumeric() || pair[1] == b'_')
682                })
683            {
684                Some("$NAME")
685            } else {
686                None
687            }
688        }
689        EnvRefSyntax::DollarBraceEnv => text.contains("${").then_some("${"),
690        EnvRefSyntax::BraceEnv => ["{env:", "{file:"]
691            .into_iter()
692            .find(|token| text.contains(token)),
693        EnvRefSyntax::Dollar | EnvRefSyntax::CodexForward => None,
694    }
695}
696
697/// One argument of a command line run through the client's shell: single
698/// quotes on Unix; double quotes on Windows. Which shell a Windows client
699/// uses (`cmd.exe`, or a POSIX shell such as Git Bash) is not settled
700/// (`scripts/verify-clients.md` DX-6, DX-7), so only text both read the
701/// same inside double quotes passes: `"`, `%`, `$`, a backtick, a line
702/// break and a trailing backslash are refused.
703pub fn shell_quote(os: Os, text: &str) -> Result<String, CoreError> {
704    match os {
705        Os::Linux | Os::MacOs => Ok(format!("'{}'", text.replace('\'', r"'\''"))),
706        Os::Windows => {
707            if text.contains(['"', '%', '$', '`', '\n', '\r']) || text.ends_with('\\') {
708                return Err(CoreError::new(
709                    ErrorCode::DeliveryUnavailable,
710                    format!(
711                        "{text:?} cannot be quoted for a Windows command line (`\"`, `%`, `$`, a \
712                         backtick, a line break or a trailing backslash)"
713                    ),
714                ));
715            }
716            Ok(format!("\"{text}\""))
717        }
718    }
719}
720
721/// Renders a command template: each `{secret:KEY}` becomes `values[KEY]`.
722/// Fails on a placeholder with no value or an unterminated one.
723pub fn fill_template(
724    template: &str,
725    values: &[(String, SecretValue)],
726) -> Result<SecretValue, CoreError> {
727    let mut out = String::new();
728    let mut rest = template;
729    while let Some(start) = rest.find(PLACEHOLDER) {
730        out.push_str(&rest[..start]);
731        let after = &rest[start + PLACEHOLDER.len()..];
732        let end = after.find('}').ok_or_else(|| {
733            CoreError::new(
734                ErrorCode::InvalidRef,
735                format!("unterminated {PLACEHOLDER:?} in the template"),
736            )
737        })?;
738        let key = &after[..end];
739        let value = values
740            .iter()
741            .find(|(name, _)| name == key)
742            .map(|(_, value)| value)
743            .ok_or_else(|| {
744                CoreError::new(
745                    ErrorCode::InvalidRef,
746                    format!(
747                        "the template uses {PLACEHOLDER}{key}}} but no --ref {key}=REF is given"
748                    ),
749                )
750            })?;
751        out.push_str(value.expose());
752        rest = &after[end + 1..];
753    }
754    out.push_str(rest);
755    Ok(SecretValue::new(out))
756}
757
758/// `KEY=REF` as given to `surject exec`, `secret get` and `secret-header`:
759/// the key is a variable name, the reference a provider reference.
760pub fn parse_binding(text: &str) -> Result<(String, SecretRef), CoreError> {
761    let invalid = || {
762        CoreError::new(
763            ErrorCode::InvalidRef,
764            format!("expected NAME=REF (a variable name and a provider reference), got {text:?}"),
765        )
766    };
767    let (key, reference) = text.split_once('=').ok_or_else(invalid)?;
768    if !crate::model::ids::is_valid(crate::model::ids::IdKind::EnvVar, key) {
769        return Err(invalid());
770    }
771    Ok((key.to_owned(), SecretRef::parse(reference)?))
772}