Skip to main content

surjection_core/secrets/
grammar.rs

1//! Reference grammar (SPEC 11.2).
2//!
3//! - Templates: every string field of a server definition may hold
4//!   `${env:NAME}`, `${secret:ALIAS}`, `${home}`, `${project}`,
5//!   `${surjection_home}`, and `$${` for a literal `${`.
6//! - Provider references: the whole-value `ref` of a `secrets.toml` alias
7//!   (`env:NAME`, `op://vault/item/field`, `op-env://<id>/<NAME>`,
8//!   `keyring://<service>/<account>`). They never appear inline in a
9//!   template, which keeps the template parser trivial and a literal
10//!   `op://` in an argument just text.
11
12use std::fmt;
13
14use crate::error::{CoreError, ErrorCode};
15use crate::model::ids::{self, IdKind};
16use crate::secrets::providers::ProviderKind;
17
18/// A parsed provider reference (the `ref` of a catalog entry).
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum SecretRef {
21    /// `env:NAME`: a process environment variable.
22    Env { name: String },
23    /// `op://vault/item[/section]/field[?query]`: a 1Password item field.
24    OnePassword {
25        vault: String,
26        item: String,
27        section: Option<String>,
28        field: String,
29        query: Option<String>,
30    },
31    /// `op-env://<environment-id>/<NAME>`: a 1Password Environment variable.
32    OnePasswordEnvironment { environment: String, name: String },
33    /// `keyring://<service>/<account>`: an OS keyring entry.
34    Keyring { service: String, account: String },
35}
36
37impl SecretRef {
38    pub fn parse(text: &str) -> Result<Self, CoreError> {
39        let invalid = |detail: &str| {
40            Err(CoreError::new(
41                ErrorCode::InvalidRef,
42                format!("invalid secret reference {text:?}: {detail}"),
43            ))
44        };
45        if let Some(name) = text.strip_prefix("env:") {
46            if !ids::is_valid(IdKind::EnvVar, name) {
47                return invalid("`env:` needs an environment variable name");
48            }
49            return Ok(Self::Env {
50                name: name.to_owned(),
51            });
52        }
53        if let Some(rest) = text.strip_prefix("op-env://") {
54            let Some((environment, name)) = rest.split_once('/') else {
55                return invalid("expected op-env://<environment-id>/<NAME>");
56            };
57            if !is_op_environment_id(environment) || !ids::is_valid(IdKind::EnvVar, name) {
58                return invalid("expected op-env://<environment-id>/<NAME>");
59            }
60            return Ok(Self::OnePasswordEnvironment {
61                environment: environment.to_owned(),
62                name: name.to_owned(),
63            });
64        }
65        if let Some(rest) = text.strip_prefix("op://") {
66            let (path, query) = match rest.split_once('?') {
67                Some((path, query)) => (path, Some(query)),
68                None => (rest, None),
69            };
70            let segments: Vec<&str> = path.split('/').collect();
71            if segments.iter().any(|segment| segment.trim().is_empty()) {
72                return invalid("op:// segments must not be empty");
73            }
74            if let Some(query) = query {
75                let well_formed = query.split('&').all(|pair| {
76                    pair.split_once('=')
77                        .is_some_and(|(key, value)| !key.is_empty() && !value.is_empty())
78                });
79                if !well_formed {
80                    return invalid("op:// query must be key=value pairs");
81                }
82            }
83            let query = query.map(str::to_owned);
84            return match segments.as_slice() {
85                [vault, item, field] => Ok(Self::OnePassword {
86                    vault: (*vault).to_owned(),
87                    item: (*item).to_owned(),
88                    section: None,
89                    field: (*field).to_owned(),
90                    query,
91                }),
92                [vault, item, section, field] => Ok(Self::OnePassword {
93                    vault: (*vault).to_owned(),
94                    item: (*item).to_owned(),
95                    section: Some((*section).to_owned()),
96                    field: (*field).to_owned(),
97                    query,
98                }),
99                _ => invalid("expected op://vault/item/field or op://vault/item/section/field"),
100            };
101        }
102        if let Some(rest) = text.strip_prefix("keyring://") {
103            return match rest.split_once('/') {
104                Some((service, account)) if !service.is_empty() && !account.is_empty() => {
105                    Ok(Self::Keyring {
106                        service: service.to_owned(),
107                        account: account.to_owned(),
108                    })
109                }
110                _ => invalid("expected keyring://<service>/<account>"),
111            };
112        }
113        invalid("expected env:, op://, op-env:// or keyring://")
114    }
115
116    /// The provider that resolves this reference.
117    pub fn provider(&self) -> ProviderKind {
118        match self {
119            SecretRef::Env { .. } => ProviderKind::Env,
120            SecretRef::Keyring { .. } => ProviderKind::Keyring,
121            SecretRef::OnePassword { .. } | SecretRef::OnePasswordEnvironment { .. } => {
122                ProviderKind::OnePassword
123            }
124        }
125    }
126}
127
128/// The canonical text, which [`SecretRef::parse`] reads back unchanged.
129impl fmt::Display for SecretRef {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        match self {
132            SecretRef::Env { name } => write!(f, "env:{name}"),
133            SecretRef::OnePassword {
134                vault,
135                item,
136                section,
137                field,
138                query,
139            } => {
140                write!(f, "op://{vault}/{item}/")?;
141                if let Some(section) = section {
142                    write!(f, "{section}/")?;
143                }
144                f.write_str(field)?;
145                match query {
146                    Some(query) => write!(f, "?{query}"),
147                    None => Ok(()),
148                }
149            }
150            SecretRef::OnePasswordEnvironment { environment, name } => {
151                write!(f, "op-env://{environment}/{name}")
152            }
153            SecretRef::Keyring { service, account } => write!(f, "keyring://{service}/{account}"),
154        }
155    }
156}
157
158/// 1Password Environment ids are lower-case alphanumeric.
159pub fn is_op_environment_id(value: &str) -> bool {
160    !value.is_empty()
161        && value
162            .bytes()
163            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
164}
165
166/// A value for `op --account`: a sign-in address (`example.1password.com`),
167/// an account shorthand, an account or user id, or an email address. Up to
168/// 128 characters of letters, digits, `.`, `-`, `_` and `@`, not starting
169/// with `-` (it is passed as an argument).
170pub fn is_op_account(value: &str) -> bool {
171    !value.is_empty()
172        && value.len() <= 128
173        && !value.starts_with('-')
174        && value
175            .bytes()
176            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'@'))
177}
178
179/// A non-secret path variable usable in templates.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum PathVar {
182    /// `${home}`
183    Home,
184    /// `${project}`
185    Project,
186    /// `${surjection_home}`
187    SurjectionHome,
188}
189
190/// One piece of a template string.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub enum TemplatePart {
193    /// Literal text, with `$${` already unescaped to `${`.
194    Literal(String),
195    /// `${env:NAME}`
196    Env(String),
197    /// `${secret:ALIAS}`
198    Secret(String),
199    /// `${home}`, `${project}`, `${surjection_home}`
200    Var(PathVar),
201}
202
203/// Parses a string field of a server definition (SPEC 11.2). Provider URIs
204/// are not allowed inside `${...}`; they go through a `secrets.toml` alias.
205pub fn parse_template(text: &str) -> Result<Vec<TemplatePart>, CoreError> {
206    let invalid = |detail: String| {
207        Err(CoreError::new(
208            ErrorCode::InvalidRef,
209            format!("invalid template {text:?}: {detail}"),
210        ))
211    };
212    let mut parts = Vec::new();
213    let mut literal = String::new();
214    let mut rest = text;
215    while let Some(start) = rest.find("${") {
216        if rest[..start].ends_with('$') {
217            // `$${` is a literal `${`.
218            literal.push_str(&rest[..start - 1]);
219            literal.push_str("${");
220            rest = &rest[start + 2..];
221            continue;
222        }
223        literal.push_str(&rest[..start]);
224        let after = &rest[start + 2..];
225        let Some(end) = after.find('}') else {
226            return invalid("unterminated `${`".to_owned());
227        };
228        let token = &after[..end];
229        let part = if let Some(name) = token.strip_prefix("env:") {
230            if !ids::is_valid(IdKind::EnvVar, name) {
231                return invalid(format!("`${{{token}}}` needs an environment variable name"));
232            }
233            TemplatePart::Env(name.to_owned())
234        } else if let Some(alias) = token.strip_prefix("secret:") {
235            if !ids::is_valid(IdKind::SecretAlias, alias) {
236                return invalid(format!("`${{{token}}}` needs a secret alias"));
237            }
238            TemplatePart::Secret(alias.to_owned())
239        } else {
240            match token {
241                "home" => TemplatePart::Var(PathVar::Home),
242                "project" => TemplatePart::Var(PathVar::Project),
243                // `${loadout_home}`: the spelling Loadout 1.0.x wrote, still
244                // written into store files (Appendix C.1).
245                "surjection_home" | "loadout_home" => TemplatePart::Var(PathVar::SurjectionHome),
246                _ => {
247                    return invalid(format!(
248                        "unknown `${{{token}}}`; use ${{env:NAME}}, ${{secret:ALIAS}}, \
249                         ${{home}}, ${{project}}, ${{surjection_home}} or $${{ for a literal"
250                    ));
251                }
252            }
253        };
254        if !literal.is_empty() {
255            parts.push(TemplatePart::Literal(std::mem::take(&mut literal)));
256        }
257        parts.push(part);
258        rest = &after[end + 1..];
259    }
260    literal.push_str(rest);
261    if !literal.is_empty() {
262        parts.push(TemplatePart::Literal(literal));
263    }
264    Ok(parts)
265}
266
267/// Whether `text` parses and holds at least one `${env:..}` or
268/// `${secret:..}` reference.
269pub fn holds_reference(text: &str) -> bool {
270    parse_template(text).is_ok_and(|parts| {
271        parts
272            .iter()
273            .any(|part| matches!(part, TemplatePart::Env(_) | TemplatePart::Secret(_)))
274    })
275}
276
277/// The literal pieces of `text` (between references and path variables);
278/// `text` itself when it does not parse. This is what a classifier looks
279/// at in a value that also holds references.
280pub fn literal_parts(text: &str) -> Vec<String> {
281    match parse_template(text) {
282        Ok(parts) => parts
283            .into_iter()
284            .filter_map(|part| match part {
285                TemplatePart::Literal(literal) => Some(literal),
286                _ => None,
287            })
288            .collect(),
289        Err(_) => vec![text.to_owned()],
290    }
291}