Skip to main content

surjection_core/eject/
rewrite.rs

1//! One owned entry made self-contained: the `surject exec` launcher
2//! unwrapped, `!<surjection> secret get` hooks and Claude Code's
3//! `headersHelper` running `<surjection> secret-header` replaced by the
4//! client's own variable references, through the client's mapper so every
5//! other field reads back as it was.
6
7use std::collections::BTreeMap;
8use std::path::Path;
9
10use serde::Serialize;
11
12use crate::adapters::AdapterSpec;
13use crate::adapters::caps::{Caps, EnvRefSyntax, FieldSet};
14use crate::adapters::mapper::{
15    EntryMapper, Launch, RemoteLaunch, RenderedServer, ServerDef, StdioLaunch, WriteCx,
16};
17use crate::brand;
18use crate::env::Os;
19use crate::error::{CoreError, ErrorCode};
20use crate::formats::NativeValue;
21use crate::model::server::Transport;
22use crate::secrets::catalog::Catalog;
23use crate::secrets::delivery::env_syntax;
24use crate::secrets::grammar::SecretRef;
25use crate::secrets::render::{PLACEHOLDER, Spell, parse_binding, spell};
26
27/// An environment variable the user sets for an ejected entry.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
29pub struct EnvNeed {
30    /// The variable name.
31    pub name: String,
32    /// The catalog alias it stands for, when there is one.
33    pub secret: Option<String>,
34    /// The reference the value comes from (`op://...`, `keyring://...`,
35    /// `env:NAME`): two entries needing one name for different references
36    /// are a conflict.
37    pub reference: String,
38}
39
40/// A value the client cannot read from the environment: the user pastes it
41/// into the entry. The value is never written by Surjection.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
43pub struct ManualSecret {
44    /// `env` or `headers`.
45    pub field: &'static str,
46    /// The env key or header name.
47    pub key: String,
48    /// The alias, or the reference when no alias names it.
49    pub secret: String,
50    /// The variable name this value would have used, when an earlier entry
51    /// already uses that name for a different secret.
52    pub conflicts_with: Option<String>,
53}
54
55/// What eject does with one entry.
56#[derive(Debug, Clone)]
57pub(crate) enum Analysis {
58    /// No Surjection reference.
59    Keep { uses_data_folder: bool },
60    Rewrite {
61        value: NativeValue,
62        needs_env: Vec<EnvNeed>,
63        manual: Vec<ManualSecret>,
64        uses_data_folder: bool,
65    },
66    /// Depends on Surjection but cannot be rewritten safely.
67    Manual(CoreError),
68}
69
70/// A part of a value delivered through Surjection.
71#[derive(Debug, Clone)]
72enum Part {
73    Text(String),
74    /// A reference; `key` is its binding (`--ref KEY=REF`), if any.
75    Ref {
76        key: Option<String>,
77        reference: SecretRef,
78    },
79}
80
81/// Variable names handed out so far in one eject, with the reference and
82/// label each stands for.
83pub(crate) type Taken = std::cell::RefCell<BTreeMap<String, (String, String)>>;
84
85pub(crate) struct Rewriter<'a> {
86    pub spec: &'static AdapterSpec,
87    pub os: Os,
88    pub catalog: &'a Catalog,
89    /// The `surject` binary entries start, when known.
90    pub launcher: Option<&'a Path>,
91    pub surjection_home: &'a Path,
92    /// Names earlier entries of this eject use.
93    pub taken: &'a Taken,
94}
95
96#[derive(Default)]
97struct Needs {
98    env: Vec<EnvNeed>,
99    manual: Vec<ManualSecret>,
100}
101
102impl Needs {
103    fn env(&mut self, name: &str, secret: Option<String>, reference: &str) {
104        if !self.env.iter().any(|need| need.name == name) {
105            self.env.push(EnvNeed {
106                name: name.to_owned(),
107                secret,
108                reference: reference.to_owned(),
109            });
110        }
111    }
112}
113
114impl Rewriter<'_> {
115    fn caps(&self) -> &'static Caps {
116        &self.spec.mcp.as_ref().expect("an MCP client").caps
117    }
118
119    fn mapper(&self) -> &'static dyn EntryMapper {
120        self.spec.mcp.as_ref().expect("an MCP client").mapper
121    }
122
123    /// What eject does with entry `key` holding `value`.
124    pub(crate) fn analyze(&self, key: &str, value: &NativeValue) -> Analysis {
125        let uses_data_folder = any_string(value, &|text| self.mentions_home(text));
126        let mapper = self.mapper();
127        let def = match mapper.from_native(key, value) {
128            Ok(def) => def,
129            Err(_) if any_string(value, &|text| self.mentions_launcher(text)) => {
130                return Analysis::Manual(manual(format!(
131                    "the entry starts `{}` but {} cannot read it back",
132                    brand::BIN_NAME,
133                    brand::PRODUCT_NAME
134                )));
135            }
136            Err(_) => return Analysis::Keep { uses_data_folder },
137        };
138        if !self.depends(&def) {
139            return Analysis::Keep { uses_data_folder };
140        }
141        let cx = WriteCx {
142            os: self.os,
143            existing: Some(value),
144        };
145        // The entry must read back exactly before anything in it changes.
146        let same = self
147            .rendered(key, def.clone())
148            .and_then(|server| mapper.to_native(&server, &cx).map_err(CoreError::from));
149        if !matches!(&same, Ok(same) if mapper.canonical(same) == mapper.canonical(value)) {
150            return Analysis::Manual(manual(format!(
151                "{} cannot rewrite this entry without changing other fields",
152                brand::PRODUCT_NAME
153            )));
154        }
155        let mut needs = Needs::default();
156        let rewritten = self
157            .transform(def, &mut needs)
158            .and_then(|def| self.rendered(key, def))
159            .and_then(|server| mapper.to_native(&server, &cx).map_err(CoreError::from));
160        let value = match rewritten {
161            Ok(value) => value,
162            Err(err) => return Analysis::Manual(err),
163        };
164        if any_string(&value, &|text| self.mentions_launcher(text)) {
165            return Analysis::Manual(manual(format!(
166                "the entry still starts `{}` after the rewrite",
167                brand::BIN_NAME
168            )));
169        }
170        Analysis::Rewrite {
171            uses_data_folder: any_string(&value, &|text| self.mentions_home(text)),
172            value,
173            needs_env: needs.env,
174            manual: needs.manual,
175        }
176    }
177
178    /// Whether the entry starts `surject` (the launcher, a hook, a
179    /// `headersHelper`).
180    fn depends(&self, def: &ServerDef) -> bool {
181        let fields = &def.fields;
182        let launched = fields
183            .command
184            .as_deref()
185            .is_some_and(|c| self.is_launcher(c))
186            && fields
187                .args
188                .as_deref()
189                .and_then(<[String]>::first)
190                .is_some_and(|arg| arg == "exec");
191        let hook = [&fields.env, &fields.headers]
192            .into_iter()
193            .flat_map(|map| map.iter().flatten())
194            .any(|(_, value)| self.is_hook(value).is_some());
195        let helper = def
196            .headers_helper
197            .as_deref()
198            .is_some_and(|helper| self.starts_launcher(helper));
199        launched || hook || helper
200    }
201
202    /// The command text of a `!<surjection> ...` value.
203    fn is_hook<'v>(&self, value: &'v str) -> Option<&'v str> {
204        value
205            .strip_prefix('!')
206            .filter(|command| self.starts_launcher(command))
207    }
208
209    fn transform(&self, mut def: ServerDef, needs: &mut Needs) -> Result<ServerDef, CoreError> {
210        let caps = self.caps();
211        let fields = &mut def.fields;
212        let launched = fields
213            .command
214            .as_deref()
215            .is_some_and(|c| self.is_launcher(c))
216            && fields
217                .args
218                .as_deref()
219                .and_then(<[String]>::first)
220                .is_some_and(|arg| arg == "exec");
221        if launched {
222            let args = fields.args.take().unwrap_or_default();
223            let exec = parse_exec(&args[1..])?;
224            fields.command = Some(exec.command);
225            fields.args = Some(exec.args);
226            let env = fields.env.get_or_insert_with(BTreeMap::new);
227            for (key, reference) in exec.refs {
228                if caps.env_ref == Some(EnvRefSyntax::CodexForward) {
229                    // Forwarded under its own name: the user sets KEY.
230                    let alias = self.alias_of(&reference).map(|(_, alias)| alias);
231                    let text = reference.to_string();
232                    match self.conflict(&key, &text) {
233                        Some(name) => {
234                            env.remove(&key);
235                            needs.manual.push(ManualSecret {
236                                field: "env",
237                                key: key.clone(),
238                                secret: self.label(&reference),
239                                conflicts_with: Some(name),
240                            });
241                        }
242                        None => {
243                            env.insert(key.clone(), format!("${{env:{key}}}"));
244                            self.take(&key, &text, &self.label(&reference));
245                            needs.env(&key, alias, &text);
246                        }
247                    }
248                } else {
249                    let parts = vec![Part::Ref {
250                        key: Some(key.clone()),
251                        reference,
252                    }];
253                    self.set(env, &key, &parts, FieldSet::ENV, needs)?;
254                }
255            }
256            if env.is_empty() {
257                fields.env = None;
258            }
259        }
260        for (field, map) in [
261            (FieldSet::ENV, &mut fields.env),
262            (FieldSet::HEADERS, &mut fields.headers),
263        ] {
264            let Some(map) = map else {
265                continue;
266            };
267            let hooks: Vec<(String, String)> = map
268                .iter()
269                .filter_map(|(key, value)| {
270                    self.is_hook(value)
271                        .map(|command| (key.clone(), command.to_owned()))
272                })
273                .collect();
274            for (key, command) in hooks {
275                let words = shell_words(&command).ok_or_else(|| unparsed(&command))?;
276                let parts = parse_secret_get(&words[1..])?;
277                // A bare reference is bound to the env key it fills.
278                let parts = match (field, parts.as_slice()) {
279                    (
280                        FieldSet::ENV,
281                        [
282                            Part::Ref {
283                                key: None,
284                                reference,
285                            },
286                        ],
287                    ) => vec![Part::Ref {
288                        key: Some(key.clone()),
289                        reference: reference.clone(),
290                    }],
291                    _ => parts,
292                };
293                self.set(map, &key, &parts, field, needs)?;
294            }
295        }
296        if let Some(helper) = def.headers_helper.take() {
297            if self.starts_launcher(&helper) {
298                let words = shell_words(&helper).ok_or_else(|| unparsed(&helper))?;
299                let headers = parse_secret_header(&words[1..])?;
300                let map = def.fields.headers.get_or_insert_with(BTreeMap::new);
301                for (name, parts) in headers {
302                    self.set(map, &name, &parts, FieldSet::HEADERS, needs)?;
303                }
304            } else {
305                def.headers_helper = Some(helper);
306            }
307        }
308        Ok(def)
309    }
310
311    /// Sets `map[key]` to `parts` in the client's syntax, or leaves the key
312    /// out and records a manual secret when the client cannot expand them
313    /// there (or a name they need already stands for another secret). Fails
314    /// (the entry stays as it is, `manual`) when the client would expand
315    /// part of the literal text.
316    fn set(
317        &self,
318        map: &mut BTreeMap<String, String>,
319        key: &str,
320        parts: &[Part],
321        field: FieldSet,
322        needs: &mut Needs,
323    ) -> Result<(), CoreError> {
324        let field_name = if field == FieldSet::HEADERS {
325            "headers"
326        } else {
327            "env"
328        };
329        // (variable, alias, reference text, label)
330        let mut names: Vec<(String, Option<String>, String, String)> = Vec::new();
331        let mut missing: Option<String> = None;
332        for part in parts {
333            if let Part::Ref { key, reference } = part {
334                match self.variable(reference, key.as_deref()) {
335                    Some((name, alias)) => {
336                        names.push((name, alias, reference.to_string(), self.label(reference)))
337                    }
338                    None => {
339                        missing.get_or_insert_with(|| self.label(reference));
340                    }
341                }
342            }
343        }
344        let conflict = names
345            .iter()
346            .find_map(|(name, _, reference, _)| self.conflict(name, reference));
347        if missing.is_none() && conflict.is_none() {
348            let mut index = 0;
349            let pieces: Vec<Spell<'_>> = parts
350                .iter()
351                .map(|part| match part {
352                    Part::Text(text) => Spell::Text(text),
353                    Part::Ref { .. } => {
354                        index += 1;
355                        Spell::Variable(&names[index - 1].0)
356                    }
357                })
358                .collect();
359            match spell(self.caps(), self.spec.display_name, field, &pieces) {
360                Ok(value) => {
361                    map.insert(key.to_owned(), value);
362                    for (name, alias, reference, label) in names {
363                        self.take(&name, &reference, &label);
364                        needs.env(&name, alias, &reference);
365                    }
366                    return Ok(());
367                }
368                // The client expands variables here, so it is the literal
369                // text around them it cannot hold: leave the entry as it is.
370                Err(err) if env_syntax(self.caps(), field).is_some() => {
371                    return Err(manual(format!(
372                        "{}; the entry still starts `{}`",
373                        err.message(),
374                        brand::BIN_NAME
375                    )));
376                }
377                Err(_) => {}
378            }
379        }
380        map.remove(key);
381        let secret = missing.unwrap_or_else(|| {
382            parts
383                .iter()
384                .find_map(|part| match part {
385                    Part::Ref { reference, .. } => Some(self.label(reference)),
386                    Part::Text(_) => None,
387                })
388                .unwrap_or_default()
389        });
390        needs.manual.push(ManualSecret {
391            field: field_name,
392            key: key.to_owned(),
393            secret,
394            conflicts_with: conflict,
395        });
396        Ok(())
397    }
398
399    /// `name` when an earlier entry of this eject uses it for a reference
400    /// other than `reference`.
401    fn conflict(&self, name: &str, reference: &str) -> Option<String> {
402        self.taken
403            .borrow()
404            .get(name)
405            .filter(|(taken, _)| taken != reference)
406            .map(|_| name.to_owned())
407    }
408
409    fn take(&self, name: &str, reference: &str, label: &str) {
410        self.taken
411            .borrow_mut()
412            .entry(name.to_owned())
413            .or_insert_with(|| (reference.to_owned(), label.to_owned()));
414    }
415
416    /// The variable a reference becomes, and its alias: `env:NAME` keeps
417    /// `NAME`; a reference this machine's catalog names becomes the alias's
418    /// `env_name` (else the alias); any other the binding key.
419    fn variable(
420        &self,
421        reference: &SecretRef,
422        key: Option<&str>,
423    ) -> Option<(String, Option<String>)> {
424        if let SecretRef::Env { name } = reference {
425            return Some((name.clone(), None));
426        }
427        if let Some((name, alias)) = self.alias_of(reference) {
428            return Some((name, Some(alias)));
429        }
430        let key =
431            key.filter(|key| crate::model::ids::is_valid(crate::model::ids::IdKind::EnvVar, key))?;
432        Some((key.to_owned(), None))
433    }
434
435    /// The `env_name` and alias of the catalog alias with this reference.
436    fn alias_of(&self, reference: &SecretRef) -> Option<(String, String)> {
437        self.catalog
438            .iter()
439            .find(|alias| alias.parsed().ok().as_ref() == Some(reference))
440            .map(|alias| (alias.env_name().to_owned(), alias.alias.clone()))
441    }
442
443    /// How messages name a reference: its alias, else the reference.
444    fn label(&self, reference: &SecretRef) -> String {
445        self.alias_of(reference)
446            .map_or_else(|| reference.to_string(), |(_, alias)| alias)
447    }
448
449    /// The entry as a [`RenderedServer`], with Codex's forwarded variables
450    /// (read back as `${env:NAME}`) forwarded again.
451    fn rendered(&self, key: &str, def: ServerDef) -> Result<RenderedServer, CoreError> {
452        let forwards = self.caps().env_ref == Some(EnvRefSyntax::CodexForward);
453        let fields = def.fields;
454        let transport = fields
455            .transport
456            .ok_or_else(|| CoreError::new(ErrorCode::MissingField, "`transport` is required"))?;
457        let launch = match transport {
458            Transport::Stdio => {
459                let mut env = fields.env.unwrap_or_default();
460                let mut forward_env = Vec::new();
461                if forwards {
462                    env.retain(|name, value| {
463                        if whole_env_ref(value) == Some(name.as_str()) {
464                            forward_env.push(name.clone());
465                            false
466                        } else {
467                            true
468                        }
469                    });
470                }
471                Launch::Stdio(StdioLaunch {
472                    command: fields.command.unwrap_or_default(),
473                    args: fields.args.unwrap_or_default(),
474                    env,
475                    forward_env,
476                    cwd: fields.cwd,
477                })
478            }
479            Transport::Http | Transport::Sse => {
480                let mut headers = fields.headers.unwrap_or_default();
481                let mut bearer_env = None;
482                let mut headers_env = BTreeMap::new();
483                if forwards {
484                    headers.retain(|name, value| {
485                        if name == "Authorization"
486                            && let Some(variable) =
487                                value.strip_prefix("Bearer ").and_then(whole_env_ref)
488                        {
489                            bearer_env = Some(variable.to_owned());
490                            return false;
491                        }
492                        if let Some(variable) = whole_env_ref(value) {
493                            headers_env.insert(name.clone(), variable.to_owned());
494                            return false;
495                        }
496                        true
497                    });
498                }
499                let remote = RemoteLaunch {
500                    url: fields.url.unwrap_or_default(),
501                    headers,
502                    headers_helper: def.headers_helper,
503                    bearer_env,
504                    headers_env,
505                };
506                match transport {
507                    Transport::Http => Launch::Http(remote),
508                    _ => Launch::Sse(remote),
509                }
510            }
511        };
512        Ok(RenderedServer {
513            name: key.to_owned(),
514            launch,
515            enabled: !def.disabled,
516            tools: def.tools,
517            passthrough: def.passthrough,
518        })
519    }
520
521    /// Whether `command` is the `surject` binary: the launcher path, or a
522    /// file named `surject` (`surject.exe`).
523    fn is_launcher(&self, command: &str) -> bool {
524        if self
525            .launcher
526            .is_some_and(|launcher| same_text(&launcher.to_string_lossy(), command))
527        {
528            return true;
529        }
530        let name = command.rsplit(['/', '\\']).next().unwrap_or(command);
531        let stem = name
532            .get(name.len().saturating_sub(4)..)
533            .filter(|suffix| suffix.eq_ignore_ascii_case(".exe"))
534            .map_or(name, |_| &name[..name.len() - 4]);
535        stem.eq_ignore_ascii_case(brand::BIN_NAME)
536    }
537
538    /// Whether a command line starts the `surject` binary.
539    fn starts_launcher(&self, command: &str) -> bool {
540        shell_words(command)
541            .and_then(|words| words.into_iter().next())
542            .is_some_and(|first| self.is_launcher(&first))
543    }
544
545    /// Whether `text` starts the `surject` binary (as a command or hook) or
546    /// names the launcher path.
547    fn mentions_launcher(&self, text: &str) -> bool {
548        self.is_launcher(text)
549            || self.starts_launcher(text.strip_prefix('!').unwrap_or(text))
550            || self
551                .launcher
552                .is_some_and(|launcher| contains_path(text, launcher))
553    }
554
555    /// Whether `text` holds a path into the data folder.
556    fn mentions_home(&self, text: &str) -> bool {
557        contains_path(text, self.surjection_home)
558    }
559}
560
561/// `${env:NAME}` alone: `NAME`.
562fn whole_env_ref(value: &str) -> Option<&str> {
563    let name = value.strip_prefix("${env:")?.strip_suffix('}')?;
564    crate::model::ids::is_valid(crate::model::ids::IdKind::EnvVar, name).then_some(name)
565}
566
567fn same_text(a: &str, b: &str) -> bool {
568    if cfg!(windows) {
569        a.eq_ignore_ascii_case(b)
570    } else {
571        a == b
572    }
573}
574
575/// Whether `text` holds `path`, with either separator (case-insensitive on
576/// Windows).
577fn contains_path(text: &str, path: &Path) -> bool {
578    let path = path.to_string_lossy();
579    if path.is_empty() {
580        return false;
581    }
582    let (text, path) = if cfg!(windows) {
583        (text.to_lowercase(), path.to_lowercase())
584    } else {
585        (text.to_owned(), path.into_owned())
586    };
587    let text = text.replace('\\', "/");
588    text.contains(&path.replace('\\', "/"))
589}
590
591/// Calls `f` on every string in `value`; whether one matched.
592fn any_string(value: &NativeValue, f: &dyn Fn(&str) -> bool) -> bool {
593    match value {
594        NativeValue::String(text) => f(text),
595        NativeValue::Array(items) => items.iter().any(|item| any_string(item, f)),
596        NativeValue::Object(map) => map.iter().any(|(_, item)| any_string(item, f)),
597        _ => false,
598    }
599}
600
601fn manual(message: String) -> CoreError {
602    CoreError::new(ErrorCode::NeedsManualSecret, message)
603}
604
605fn unparsed(command: &str) -> CoreError {
606    let _ = command;
607    manual(format!(
608        "the `{}` command in the entry cannot be read",
609        brand::BIN_NAME
610    ))
611}
612
613/// `surject exec` arguments after `exec`.
614struct Exec {
615    refs: Vec<(String, SecretRef)>,
616    command: String,
617    args: Vec<String>,
618}
619
620fn parse_exec(args: &[String]) -> Result<Exec, CoreError> {
621    let bad = || {
622        manual(format!(
623            "the `{} exec` arguments cannot be read",
624            brand::BIN_NAME
625        ))
626    };
627    let mut refs = Vec::new();
628    let mut environment: Option<String> = None;
629    let mut maps: Vec<(String, String)> = Vec::new();
630    let mut rest = args.iter();
631    loop {
632        let arg = rest.next().ok_or_else(bad)?;
633        let (flag, inline) = match arg.split_once('=') {
634            Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_owned())),
635            _ => (arg.as_str(), None),
636        };
637        let mut value = || {
638            inline
639                .clone()
640                .or_else(|| rest.next().cloned())
641                .ok_or_else(bad)
642        };
643        match flag {
644            "--" => break,
645            "--ref" => {
646                let (key, reference) = parse_binding(&value()?).map_err(|_| bad())?;
647                refs.push((key, reference));
648            }
649            "--op-account" => {
650                value()?;
651            }
652            "--op-env" => environment = Some(value()?),
653            "--map" => {
654                let map = value()?;
655                let (key, name) = map.split_once('=').ok_or_else(bad)?;
656                maps.push((key.to_owned(), name.to_owned()));
657            }
658            _ => return Err(bad()),
659        }
660    }
661    for (key, name) in maps {
662        let environment = environment.clone().ok_or_else(bad)?;
663        refs.push((key, SecretRef::OnePasswordEnvironment { environment, name }));
664    }
665    let command = rest.next().ok_or_else(bad)?.clone();
666    Ok(Exec {
667        refs,
668        command,
669        args: rest.cloned().collect(),
670    })
671}
672
673/// `secret get` arguments (the words after the binary).
674fn parse_secret_get(words: &[String]) -> Result<Vec<Part>, CoreError> {
675    let bad = || {
676        manual(format!(
677            "the `{} secret get` hook cannot be read",
678            brand::BIN_NAME
679        ))
680    };
681    let [secret, get, rest @ ..] = words else {
682        return Err(bad());
683    };
684    if secret != "secret" || get != "get" {
685        return Err(bad());
686    }
687    let mut refs: Vec<String> = Vec::new();
688    let mut template: Option<String> = None;
689    let mut rest = rest.iter();
690    while let Some(flag) = rest.next() {
691        let value = rest.next().ok_or_else(bad)?;
692        match flag.as_str() {
693            "--ref" => refs.push(value.clone()),
694            "--template" => template = Some(value.clone()),
695            "--op-account" => {}
696            _ => return Err(bad()),
697        }
698    }
699    match template {
700        None => {
701            let [reference] = refs.as_slice() else {
702                return Err(bad());
703            };
704            let reference = SecretRef::parse(reference).map_err(|_| bad())?;
705            Ok(vec![Part::Ref {
706                key: None,
707                reference,
708            }])
709        }
710        Some(template) => {
711            let bindings = refs
712                .iter()
713                .map(|binding| parse_binding(binding))
714                .collect::<Result<Vec<_>, _>>()
715                .map_err(|_| bad())?;
716            split_template(&template, &bindings).ok_or_else(bad)
717        }
718    }
719}
720
721/// `secret-header` arguments (the words after the binary): each header and
722/// its value as parts.
723fn parse_secret_header(words: &[String]) -> Result<Vec<(String, Vec<Part>)>, CoreError> {
724    let bad = || {
725        manual(format!(
726            "the `{} secret-header` helper cannot be read",
727            brand::BIN_NAME
728        ))
729    };
730    let [command, rest @ ..] = words else {
731        return Err(bad());
732    };
733    if command != "secret-header" {
734        return Err(bad());
735    }
736    let mut bindings = Vec::new();
737    let mut headers: Vec<(String, String)> = Vec::new();
738    let mut rest = rest.iter();
739    while let Some(word) = rest.next() {
740        match word.as_str() {
741            "--ref" => {
742                let binding = rest.next().ok_or_else(bad)?;
743                bindings.push(parse_binding(binding).map_err(|_| bad())?);
744            }
745            "--op-account" => {
746                rest.next().ok_or_else(bad)?;
747            }
748            header => {
749                let (name, template) = header.split_once('=').ok_or_else(bad)?;
750                headers.push((name.to_owned(), template.to_owned()));
751            }
752        }
753    }
754    headers
755        .into_iter()
756        .map(|(name, template)| {
757            split_template(&template, &bindings)
758                .map(|parts| (name, parts))
759                .ok_or_else(bad)
760        })
761        .collect()
762}
763
764/// A command template (`{secret:KEY}` placeholders) as parts.
765fn split_template(template: &str, bindings: &[(String, SecretRef)]) -> Option<Vec<Part>> {
766    let mut parts = Vec::new();
767    let mut rest = template;
768    while let Some(start) = rest.find(PLACEHOLDER) {
769        if start > 0 {
770            parts.push(Part::Text(rest[..start].to_owned()));
771        }
772        let after = &rest[start + PLACEHOLDER.len()..];
773        let end = after.find('}')?;
774        let key = &after[..end];
775        let reference = bindings
776            .iter()
777            .find(|(name, _)| name == key)
778            .map(|(_, reference)| reference.clone())?;
779        parts.push(Part::Ref {
780            key: Some(key.to_owned()),
781            reference,
782        });
783        rest = &after[end + 1..];
784    }
785    if !rest.is_empty() {
786        parts.push(Part::Text(rest.to_owned()));
787    }
788    Some(parts)
789}
790
791/// Splits a command line the way [`crate::secrets::render::shell_quote`]
792/// quotes it: single quotes (with `'\''`) and double quotes; `None` for an
793/// unterminated quote.
794fn shell_words(text: &str) -> Option<Vec<String>> {
795    let mut words = Vec::new();
796    let mut current = String::new();
797    let mut in_word = false;
798    let mut chars = text.chars().peekable();
799    while let Some(c) = chars.next() {
800        match c {
801            '\'' | '"' => {
802                in_word = true;
803                loop {
804                    match chars.next()? {
805                        close if close == c => break,
806                        other => current.push(other),
807                    }
808                }
809            }
810            '\\' if chars.peek() == Some(&'\'') => {
811                in_word = true;
812                current.push(chars.next()?);
813            }
814            c if c.is_whitespace() => {
815                if in_word {
816                    words.push(std::mem::take(&mut current));
817                    in_word = false;
818                }
819            }
820            c => {
821                in_word = true;
822                current.push(c);
823            }
824        }
825    }
826    if in_word {
827        words.push(current);
828    }
829    Some(words)
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835
836    fn words(text: &str) -> Vec<String> {
837        shell_words(text).unwrap()
838    }
839
840    #[test]
841    fn shell_words_read_both_quote_styles() {
842        assert_eq!(
843            words(r#""C:\Program Files\Surjection\surject.exe" secret get --ref "op://v/i/f""#),
844            [
845                "C:\\Program Files\\Surjection\\surject.exe",
846                "secret",
847                "get",
848                "--ref",
849                "op://v/i/f"
850            ]
851        );
852        assert_eq!(
853            words(r"'/opt/it'\''s/surjection' secret-header 'Authorization=Bearer {secret:A}'"),
854            [
855                "/opt/it's/surjection",
856                "secret-header",
857                "Authorization=Bearer {secret:A}"
858            ]
859        );
860        assert!(shell_words("'open").is_none());
861    }
862
863    #[test]
864    fn exec_arguments_split_into_refs_and_the_command() {
865        let args: Vec<String> = [
866            "--op-account",
867            "me",
868            "--ref",
869            "TOKEN=op://v/i/f",
870            "--op-env",
871            "abc",
872            "--map",
873            "DB=DB_URL",
874            "--",
875            "npx",
876            "-y",
877            "server",
878        ]
879        .map(str::to_owned)
880        .to_vec();
881        let exec = parse_exec(&args).unwrap();
882        assert_eq!(exec.command, "npx");
883        assert_eq!(exec.args, ["-y", "server"]);
884        assert_eq!(exec.refs.len(), 2);
885        assert_eq!(exec.refs[0].0, "TOKEN");
886        assert_eq!(
887            exec.refs[1].1,
888            SecretRef::OnePasswordEnvironment {
889                environment: "abc".to_owned(),
890                name: "DB_URL".to_owned()
891            }
892        );
893        assert!(parse_exec(&["--ref".to_owned()]).is_err());
894    }
895
896    #[test]
897    fn templates_keep_their_literal_text() {
898        let reference = SecretRef::parse("keyring://surjection/A").unwrap();
899        let parts =
900            split_template("Bearer {secret:A}!", &[("A".to_owned(), reference.clone())]).unwrap();
901        assert!(matches!(&parts[0], Part::Text(text) if text == "Bearer "));
902        assert!(matches!(&parts[1], Part::Ref { key: Some(key), .. } if key == "A"));
903        assert!(matches!(&parts[2], Part::Text(text) if text == "!"));
904        assert!(split_template("{secret:B}", &[("A".to_owned(), reference)]).is_none());
905    }
906
907    fn claude_helper(header: &str) -> NativeValue {
908        let mut entry = crate::formats::NativeMap::new();
909        entry.insert("type", "http".into());
910        entry.insert("url", "https://mcp.example.test/mcp".into());
911        entry.insert(
912            "headersHelper",
913            format!(
914                "'/opt/surjection/bin/surject' secret-header --ref 'K=keyring://surjection/K' '{header}'"
915            )
916            .into(),
917        );
918        NativeValue::Object(entry)
919    }
920
921    fn analyze(header: &str) -> Analysis {
922        let catalog = Catalog::default();
923        let taken = Taken::default();
924        let rewriter = Rewriter {
925            spec: crate::adapters::adapter("claude-code").unwrap(),
926            os: Os::Linux,
927            catalog: &catalog,
928            launcher: None,
929            surjection_home: Path::new("/surjection-home"),
930            taken: &taken,
931        };
932        rewriter.analyze("linear", &claude_helper(header))
933    }
934
935    #[test]
936    fn a_literal_the_client_would_expand_leaves_the_entry_as_it_is() {
937        // Claude Code expands `${` in headers and has no escape for it.
938        let Analysis::Manual(err) = analyze("Authorization=a${b}{secret:K}") else {
939            panic!("expected manual");
940        };
941        assert!(err.message().contains("surject"), "{err}");
942        // Without the literal, the same header is rewritten.
943        let Analysis::Rewrite { value, .. } = analyze("Authorization=Bearer {secret:K}") else {
944            panic!("expected a rewrite");
945        };
946        let headers = value.as_object().unwrap().get("headers").unwrap();
947        assert_eq!(
948            headers.as_object().unwrap().get("Authorization"),
949            Some(&NativeValue::from("Bearer ${K}"))
950        );
951    }
952}