Skip to main content

surjection_core/secrets/
extract.rs

1//! Secret extraction on import, adopt and migration (SPEC 11.7), shared by
2//! the SkillDock migration ([`crate::migrate`]) and the import of client
3//! entries ([`crate::apply::import`]).
4//!
5//! An [`Extractor`] replaces each sensitive literal of a server definition
6//! (`args`, the URL, `env` and `headers` values) by a `${secret:<alias>}`
7//! reference and keeps the value in memory only ([`Extracted::value`]).
8//! [`stage_choices`] turns the destinations the user chose into
9//! `secrets.toml` aliases: the OS keyring (the value is written there, never
10//! to the store), a 1Password reference or an environment variable.
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use crate::apply::ApplyEnv;
15use crate::brand;
16use crate::error::{CoreError, ErrorCode};
17use crate::model::ids::{self, IdKind};
18use crate::model::server::ServerFields;
19use crate::secrets::SecretValue;
20use crate::secrets::catalog::{self, AliasUpdate, SetScope};
21use crate::secrets::classify::{
22    Reason, classify_args_import, classify_import, find_in_text, is_sensitive_argument_name,
23};
24use crate::secrets::grammar::SecretRef;
25use crate::secrets::providers::Resolver;
26use crate::secrets::providers::onepassword::OpCli;
27use crate::store::Transaction;
28
29/// Secret aliases in use; [`Aliases::new_alias`] picks free ones.
30#[derive(Debug, Clone, Default)]
31pub struct Aliases {
32    taken: BTreeSet<String>,
33}
34
35impl Aliases {
36    pub fn new(taken: impl IntoIterator<Item = String>) -> Self {
37        Self {
38            taken: taken.into_iter().collect(),
39        }
40    }
41
42    /// `<SERVER>_<KEY>` in upper case with `_` for anything else, free of
43    /// every alias seen so far (`_2`, `_3` when taken).
44    pub fn new_alias(&mut self, server: &str, key: &str) -> String {
45        let mut base: String = format!("{server}_{key}")
46            .chars()
47            .map(|ch| {
48                if ch.is_ascii_alphanumeric() {
49                    ch.to_ascii_uppercase()
50                } else {
51                    '_'
52                }
53            })
54            .collect();
55        while base.contains("__") {
56            base = base.replace("__", "_");
57        }
58        let mut base = base.trim_matches('_').to_owned();
59        if base.is_empty() || base.as_bytes()[0].is_ascii_digit() {
60            base.insert(0, '_');
61        }
62        base.truncate(60);
63        let mut alias = base.clone();
64        let mut n = 2;
65        while self.taken.contains(&alias) || !ids::is_valid(IdKind::SecretAlias, &alias) {
66            alias = format!("{base}_{n}");
67            n += 1;
68        }
69        self.taken.insert(alias.clone());
70        alias
71    }
72}
73
74/// One plaintext value routed to secret extraction. The value is not part
75/// of it: the store gets a `${secret:<alias>}` reference in its place.
76#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
77pub struct Extraction {
78    pub server: String,
79    /// `env.NAME`, `headers.NAME`, `args[N]` (1-based) or `url`.
80    pub field: String,
81    pub alias: String,
82    /// Why it counts as sensitive ([`Reason::as_str`]).
83    pub reason: &'static str,
84    /// The default destination (`keyring://surjection/<alias>`); the wizard
85    /// also offers 1Password or an environment variable.
86    pub suggested_ref: String,
87}
88
89/// An [`Extraction`] with the value it replaced, in memory only
90/// ([`SecretValue`] has no `Display` or `Serialize`, and a redacted
91/// `Debug`).
92#[derive(Debug, Clone)]
93pub struct Extracted {
94    pub extraction: Extraction,
95    pub value: SecretValue,
96}
97
98/// `${secret:<alias>}`.
99pub fn reference(alias: &str) -> String {
100    format!("${{secret:{alias}}}")
101}
102
103/// Replaces the sensitive literals of one server's fields by references.
104pub struct Extractor<'a> {
105    server: &'a str,
106    aliases: &'a mut Aliases,
107    found: Vec<Extracted>,
108}
109
110impl<'a> Extractor<'a> {
111    /// Extracts for store server `server` (aliases are `<SERVER>_<KEY>`).
112    pub fn new(server: &'a str, aliases: &'a mut Aliases) -> Self {
113        Self {
114            server,
115            aliases,
116            found: Vec::new(),
117        }
118    }
119
120    /// What was extracted, in field order.
121    pub fn finish(self) -> Vec<Extracted> {
122        self.found
123    }
124
125    fn push(&mut self, field: String, key: &str, reason: Reason, value: &str) -> String {
126        let alias = self.aliases.new_alias(self.server, key);
127        self.found.push(Extracted {
128            extraction: Extraction {
129                server: self.server.to_owned(),
130                field,
131                alias: alias.clone(),
132                reason: reason.as_str(),
133                suggested_ref: format!("keyring://{}/{alias}", brand::KEYRING_SERVICE),
134            },
135            value: SecretValue::new(value),
136        });
137        alias
138    }
139
140    /// Arguments with each sensitive one (or the value part of
141    /// `--flag=value`) replaced by a reference.
142    pub fn args(&mut self, mut args: Vec<String>) -> Vec<String> {
143        let flagged = classify_args_import(&args);
144        for (index, reason) in flagged.into_iter().enumerate() {
145            let Some(reason) = reason else {
146                continue;
147            };
148            let arg = args[index].clone();
149            let (prefix, key, value) = match arg.split_once('=') {
150                Some((flag, value)) if flag.starts_with('-') => (
151                    format!("{flag}="),
152                    flag.trim_start_matches('-').to_owned(),
153                    value.to_owned(),
154                ),
155                _ => {
156                    let previous = index
157                        .checked_sub(1)
158                        .map(|i| args[i].as_str())
159                        .filter(|prev| prev.starts_with('-') && is_sensitive_argument_name(prev));
160                    (
161                        String::new(),
162                        previous.map_or_else(
163                            || format!("arg{}", index + 1),
164                            |flag| flag.trim_start_matches('-').to_owned(),
165                        ),
166                        arg.clone(),
167                    )
168                }
169            };
170            let alias = self.push(format!("args[{}]", index + 1), &key, reason, &value);
171            args[index] = format!("{prefix}{}", reference(&alias));
172        }
173        args
174    }
175
176    /// The URL with each credential part (userinfo, token query parameter,
177    /// token-shaped text) replaced by a reference. A URL the classifier
178    /// flags without a part to cut out is `needs_secret_extraction` (edit
179    /// it by hand).
180    pub fn url(&mut self, url: String) -> Result<String, CoreError> {
181        let Some(reason) = classify_import(None, &url) else {
182            return Ok(url);
183        };
184        let hits = find_in_text(&url);
185        if hits.is_empty() {
186            return Err(CoreError::new(
187                ErrorCode::NeedsSecretExtraction,
188                format!(
189                    "the URL may hold a secret ({}); edit it by hand",
190                    reason.describe()
191                ),
192            ));
193        }
194        // Aliases and the listing follow URL order; the text is cut from
195        // the end so earlier ranges stay valid.
196        let mut aliases = Vec::with_capacity(hits.len());
197        for (n, hit) in hits.iter().enumerate() {
198            let key = if hits.len() == 1 {
199                "url".to_owned()
200            } else {
201                format!("url{}", n + 1)
202            };
203            let value = url[hit.range.clone()].to_owned();
204            aliases.push(self.push("url".to_owned(), &key, hit.reason, &value));
205        }
206        let mut out = url;
207        for (hit, alias) in hits.iter().zip(&aliases).rev() {
208            out.replace_range(hit.range.clone(), &reference(alias));
209        }
210        Ok(out)
211    }
212
213    /// An `env` or `headers` map (`label`) with each sensitive value
214    /// replaced by a reference; an `Authorization: Bearer` style scheme in
215    /// a header stays around the reference.
216    pub fn map(&mut self, label: &str, map: BTreeMap<String, String>) -> BTreeMap<String, String> {
217        let mut out = BTreeMap::new();
218        for (name, value) in map {
219            let value = match classify_import(Some(&name), &value) {
220                Some(reason) => {
221                    let scheme = value.split_once(' ').filter(|(scheme, _)| {
222                        label == "headers"
223                            && matches!(
224                                scheme.to_ascii_lowercase().as_str(),
225                                "bearer" | "basic" | "token"
226                            )
227                    });
228                    match scheme {
229                        Some((scheme, secret)) => {
230                            let alias = self.push(format!("{label}.{name}"), &name, reason, secret);
231                            format!("{scheme} {}", reference(&alias))
232                        }
233                        None => {
234                            let alias = self.push(format!("{label}.{name}"), &name, reason, &value);
235                            reference(&alias)
236                        }
237                    }
238                }
239                None => value,
240            };
241            out.insert(name, value);
242        }
243        out
244    }
245
246    /// Every sensitive literal of `fields` (`args`, the URL, `env` and
247    /// `headers` values) replaced by a reference, in that order.
248    pub fn fields(&mut self, fields: &mut ServerFields) -> Result<(), CoreError> {
249        if let Some(args) = fields.args.take() {
250            fields.args = Some(self.args(args));
251        }
252        if let Some(url) = fields.url.take() {
253            fields.url = Some(self.url(url)?);
254        }
255        if let Some(env) = fields.env.take() {
256            fields.env = Some(self.map("env", env));
257        }
258        if let Some(headers) = fields.headers.take() {
259            fields.headers = Some(self.map("headers", headers));
260        }
261        Ok(())
262    }
263}
264
265/// Where one extracted value goes (SPEC 11.7).
266pub enum ExtractionTarget {
267    /// The OS keyring, as `keyring://surjection/<alias>`; the value goes one
268    /// way and is never stored or returned.
269    Keyring(SecretValue),
270    /// A 1Password or environment reference (`op://...`, `op-env://...`,
271    /// `env:NAME`).
272    Reference(SecretRef),
273}
274
275/// The destination of one extraction, by alias.
276pub struct ExtractionChoice {
277    pub alias: String,
278    pub target: ExtractionTarget,
279}
280
281/// Stages each choice as a `secrets.toml` alias in `tx`. Keyring values
282/// are written through the resolver first, which remembers them, so the
283/// leak scanner refuses the commit should one reach a store file. A
284/// keyring reference given instead of a value is `invalid_value`.
285pub fn stage_choices(
286    tx: &mut Transaction<'_>,
287    ax: &ApplyEnv<'_>,
288    choices: &[ExtractionChoice],
289) -> Result<(), CoreError> {
290    if choices.is_empty() {
291        return Ok(());
292    }
293    if choices.iter().any(|choice| {
294        matches!(
295            choice.target,
296            ExtractionTarget::Reference(SecretRef::Keyring { .. })
297        )
298    }) {
299        return Err(CoreError::new(
300            ErrorCode::InvalidValue,
301            "a keyring destination takes the value, not a reference",
302        ));
303    }
304    let resolver = Resolver::new(
305        ax.env,
306        ax.delivery.keyring(),
307        &OpCli::NotFound,
308        tx.store().secret_memory().clone(),
309    );
310    for choice in choices {
311        let reference = match &choice.target {
312            ExtractionTarget::Keyring(value) => {
313                resolver
314                    .set_keyring(brand::KEYRING_SERVICE, &choice.alias, value)
315                    .map_err(|resolution| {
316                        resolution.into_error(&format!("cannot store {}", choice.alias))
317                    })?;
318                SecretRef::Keyring {
319                    service: brand::KEYRING_SERVICE.to_owned(),
320                    account: choice.alias.clone(),
321                }
322            }
323            ExtractionTarget::Reference(reference) => reference.clone(),
324        };
325        let update = AliasUpdate {
326            reference,
327            description: None,
328            env_name: None,
329        };
330        catalog::stage_set(tx, &choice.alias, &update, SetScope::Store)?;
331    }
332    tx.add_entity("secrets".to_owned());
333    Ok(())
334}
335
336fn invalid(message: &str) -> CoreError {
337    CoreError::new(ErrorCode::InvalidValue, message.to_owned())
338}
339
340/// A 1Password item reference, `op://vault/item/field` or
341/// `op://vault/item/section/field`, checked: three or four non-empty parts.
342pub fn onepassword_reference(text: &str) -> Result<SecretRef, CoreError> {
343    let text = text.trim();
344    let parts: Vec<&str> = text
345        .strip_prefix("op://")
346        .map(|rest| rest.split('/').collect())
347        .unwrap_or_default();
348    if !(3..=4).contains(&parts.len()) || parts.iter().any(|part| part.trim().is_empty()) {
349        return Err(invalid("a 1Password reference is op://vault/item/field"));
350    }
351    match SecretRef::parse(text)? {
352        reference @ SecretRef::OnePassword { .. } => Ok(reference),
353        _ => Err(invalid("a 1Password reference is op://vault/item/field")),
354    }
355}
356
357/// An environment variable reference (`env:NAME`), the name checked.
358pub fn env_reference(name: &str) -> Result<SecretRef, CoreError> {
359    let name = name.trim();
360    ids::check(IdKind::EnvVar, name)?;
361    SecretRef::parse(&format!("env:{name}"))
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    fn values(found: &[Extracted]) -> Vec<(&str, &str, &str)> {
369        found
370            .iter()
371            .map(|e| {
372                (
373                    e.extraction.field.as_str(),
374                    e.extraction.alias.as_str(),
375                    e.value.expose(),
376                )
377            })
378            .collect()
379    }
380
381    #[test]
382    fn extracts_each_literal_with_its_value() {
383        let mut aliases = Aliases::new(["DOCS_API_KEY".to_owned()]);
384        let mut extractor = Extractor::new("docs", &mut aliases);
385        let args = extractor.args(vec![
386            "-y".to_owned(),
387            "--token=planted-arg".to_owned(),
388            "--password".to_owned(),
389            "planted-next".to_owned(),
390        ]);
391        let env = extractor.map(
392            "env",
393            BTreeMap::from([
394                ("API_KEY".to_owned(), "planted-env".to_owned()),
395                ("LOG_LEVEL".to_owned(), "info".to_owned()),
396            ]),
397        );
398        let headers = extractor.map(
399            "headers",
400            BTreeMap::from([(
401                "Authorization".to_owned(),
402                "Bearer planted-header".to_owned(),
403            )]),
404        );
405        let found = extractor.finish();
406        assert_eq!(
407            args,
408            [
409                "-y",
410                "--token=${secret:DOCS_TOKEN}",
411                "--password",
412                "${secret:DOCS_PASSWORD}"
413            ]
414        );
415        assert_eq!(env["API_KEY"], "${secret:DOCS_API_KEY_2}");
416        assert_eq!(env["LOG_LEVEL"], "info");
417        assert_eq!(
418            headers["Authorization"],
419            "Bearer ${secret:DOCS_AUTHORIZATION}"
420        );
421        assert_eq!(
422            values(&found),
423            [
424                ("args[2]", "DOCS_TOKEN", "planted-arg"),
425                ("args[4]", "DOCS_PASSWORD", "planted-next"),
426                ("env.API_KEY", "DOCS_API_KEY_2", "planted-env"),
427                (
428                    "headers.Authorization",
429                    "DOCS_AUTHORIZATION",
430                    "planted-header"
431                ),
432            ]
433        );
434        assert!(!format!("{found:?}").contains("planted"), "{found:?}");
435    }
436
437    #[test]
438    fn references_are_checked() {
439        assert!(onepassword_reference("op://Vault/Item/field").is_ok());
440        assert!(onepassword_reference("op://Vault/Item/section/field").is_ok());
441        for bad in [
442            "op://Vault/Item",
443            "op://Vault//field",
444            "env:X",
445            "keyring://a/b",
446        ] {
447            assert_eq!(
448                onepassword_reference(bad).unwrap_err().code(),
449                ErrorCode::InvalidValue,
450                "{bad}"
451            );
452        }
453        assert_eq!(
454            env_reference(" GITHUB_PAT ").unwrap(),
455            SecretRef::Env {
456                name: "GITHUB_PAT".to_owned()
457            }
458        );
459        assert!(env_reference("not a name").is_err());
460    }
461}