Skip to main content

vault_core/
bundle_scope.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Bundle-local template resolution (Phase 24.1, step 4).
4//!
5//! Resolves local variables, composite parts, sibling fields and optional
6//! global references. Missing inputs, cycles and excessive derived depth are
7//! errors so a partially rendered credential cannot look valid.
8
9use serde_json::Value;
10use std::collections::HashMap;
11
12const MAX_DEPTH: usize = 4;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ScopedValue {
16    pub value: String,
17    pub secret: bool,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum ScopeError {
22    Unresolved(String),
23    Cycle(Vec<String>),
24    Depth(String),
25    Invalid(String),
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct ScopeOutput {
30    pub value: ScopedValue,
31    pub warnings: Vec<String>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct CompositeOutput {
36    pub value: String,
37    pub secret: bool,
38    pub warnings: Vec<String>,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum CompositeScopeError {
43    Scope(ScopeError),
44    Composite(crate::composite::RenderError),
45}
46
47fn string_field<'a>(entry: &'a Value, key: &str) -> Option<&'a str> {
48    entry.get(key).and_then(Value::as_str)
49}
50
51fn bool_field(entry: &Value, key: &str) -> bool {
52    entry.get(key).and_then(Value::as_bool) == Some(true)
53}
54
55fn variable<'a>(entry: &'a Value, key: &str) -> Option<&'a Value> {
56    entry
57        .get("extra_vars")
58        .and_then(Value::as_array)?
59        .iter()
60        .find(|item| string_field(item, "key") == Some(key))
61}
62
63fn entry_field(entry: &Value, key: &str) -> Option<ScopedValue> {
64    if matches!(key, "version_history" | "projectIds" | "categories") {
65        return None;
66    }
67    let role = role_key(key);
68    if role != "VALUE"
69        && entry
70            .get("primary_role")
71            .and_then(Value::as_str)
72            .is_some_and(|value| role_key(value) == role)
73    {
74        return Some(ScopedValue {
75            value: string_field(entry, "api_key")?.to_owned(),
76            secret: !bool_field(entry, "primary_public"),
77        });
78    }
79    if role != "VALUE"
80        && entry
81            .get("secret_role")
82            .and_then(Value::as_str)
83            .is_some_and(|value| role_key(value) == role)
84    {
85        return Some(ScopedValue {
86            value: string_field(entry, "api_secret")?.to_owned(),
87            secret: !bool_field(entry, "secret_public"),
88        });
89    }
90    let canonical = match key.to_ascii_uppercase().as_str() {
91        "APIKEY" | "API_KEY" | "KEY" | "TOKEN" | "ACCESS_TOKEN" | "BEARER" | "SECRET_KEY"
92        | "PASSWORD" | "PASS" | "PWD" => "api_key",
93        "SECRET" | "API_SECRET" | "CLIENT_SECRET" | "SHARED_SECRET" => "api_secret",
94        "USERNAME" | "USER" | "LOGIN" | "USER_NAME" => "username",
95        "URL" | "URI" | "ENDPOINT" | "API_URL" | "BASE_URL" => "api_url",
96        "EMAIL" | "MAIL" => "email",
97        "KEY_ID" | "KEYID" | "KID" | "ID" | "CLIENT_ID" | "APP_ID" | "ACCOUNT_ID"
98        | "APPLICATION_ID" => "key_id",
99        "PATH" | "MOUNT" | "MOUNT_PATH" | "FILE" => "mount_path",
100        _ => key,
101    };
102    let (field, secret) = match canonical {
103        "api_key" => ("api_key", !bool_field(entry, "primary_public")),
104        "api_secret" => ("api_secret", !bool_field(entry, "secret_public")),
105        _ => (
106            canonical,
107            matches!(canonical, "totp_secret" | "user_agent" | "blob_data"),
108        ),
109    };
110    if let Some(value) = string_field(entry, field) {
111        return Some(ScopedValue {
112            value: value.to_owned(),
113            secret,
114        });
115    }
116    let item = variable(entry, key).or_else(|| variable(entry, canonical))?;
117    Some(ScopedValue {
118        value: string_field(item, "value")?.to_owned(),
119        secret: item.get("public").and_then(Value::as_bool) != Some(true)
120            && item.get("secret").and_then(Value::as_bool) != Some(false),
121    })
122}
123
124fn role_key(raw: &str) -> String {
125    raw.chars()
126        .map(|c| {
127            if c.is_ascii_alphanumeric() {
128                c.to_ascii_uppercase()
129            } else {
130                '_'
131            }
132        })
133        .collect()
134}
135
136/// Resolve `{local}` and `{slot.field}`. `globals` returns a value only when
137/// the caller can resolve and read that reference; callers should mark a
138/// reference secret unless its source is explicitly public.
139pub fn resolve<F>(
140    bundle: &Value,
141    members: &[Value],
142    template: &str,
143    parts: &[Value],
144    globals: F,
145) -> Result<ScopeOutput, ScopeError>
146where
147    F: Fn(&str) -> Option<ScopedValue>,
148{
149    let mut slots = HashMap::new();
150    for member in members {
151        let slot = string_field(member, "bundle_slot")
152            .filter(|s| !s.is_empty())
153            .or_else(|| string_field(member, "provider"))
154            .unwrap_or_default();
155        if slots.insert(slot.to_owned(), member).is_some() {
156            return Err(ScopeError::Invalid(format!(
157                "duplicate bundle slot \"{slot}\""
158            )));
159        }
160    }
161    let mut locals = HashMap::new();
162    if let Some(values) = bundle.get("extra_vars").and_then(Value::as_array) {
163        for item in values {
164            if let (Some(key), Some(_)) = (string_field(item, "key"), string_field(item, "value")) {
165                locals.insert(key.to_owned(), item);
166            }
167        }
168    }
169    let own: HashMap<&str, &Value> = parts
170        .iter()
171        .filter_map(|part| Some((string_field(part, "key")?, part)))
172        .collect();
173    let mut warnings = Vec::new();
174    for name in locals.keys() {
175        if own.contains_key(name.as_str())
176            || members
177                .iter()
178                .any(|m| string_field(m, "bundle_slot") == Some(name))
179        {
180            warnings.push(format!(
181                "\"{name}\" exists at more than one scope level; the part wins over the local"
182            ));
183        }
184    }
185    let mut stack = Vec::new();
186    let value = resolve_text(template, 0, &mut stack, &locals, &own, &slots, &globals)?;
187    Ok(ScopeOutput { value, warnings })
188}
189
190/// Resolve scoped references into synthetic named parts, then pass those parts
191/// through the shared zone-aware composite renderer.
192pub fn render_composite<F>(
193    bundle: &Value,
194    members: &[Value],
195    template: &str,
196    own_parts: &[Value],
197    kind: crate::composite::Kind,
198    globals: F,
199) -> Result<CompositeOutput, CompositeScopeError>
200where
201    F: Fn(&str) -> Option<ScopedValue>,
202{
203    let mut expanded = String::new();
204    let mut parts = Vec::new();
205    let mut warnings = Vec::new();
206    let mut secret = false;
207    let mut pos = 0;
208    let mut index = 0;
209    while pos < template.len() {
210        let rest = &template[pos..];
211        if rest.starts_with("{{") || rest.starts_with("}}") {
212            expanded.push_str(&rest[..2]);
213            pos += 2;
214            continue;
215        }
216        let global_end = if rest.starts_with("${") {
217            Some(rest.find('}').ok_or_else(|| {
218                CompositeScopeError::Scope(ScopeError::Invalid(format!(
219                    "unclosed global reference at {pos}"
220                )))
221            })?)
222        } else {
223            None
224        };
225        if let Some(end) = global_end {
226            let scoped = resolve(bundle, members, &rest[..=end], own_parts, &globals)
227                .map_err(CompositeScopeError::Scope)?;
228            let key = format!("scope_{index}");
229            index += 1;
230            secret |= scoped.value.secret;
231            warnings.extend(scoped.warnings);
232            parts.push(crate::composite::Part {
233                key: key.clone(),
234                value: scoped.value.value,
235            });
236            expanded.push('{');
237            expanded.push_str(&key);
238            expanded.push('}');
239            pos += end + 1;
240            continue;
241        }
242        let ch = rest.chars().next().expect("pos is within template");
243        if ch == '}' {
244            return Err(CompositeScopeError::Scope(ScopeError::Invalid(format!(
245                "unmatched closing brace at {pos}"
246            ))));
247        }
248        if ch != '{' {
249            expanded.push(ch);
250            pos += ch.len_utf8();
251            continue;
252        }
253        let end = rest.find('}').ok_or_else(|| {
254            CompositeScopeError::Scope(ScopeError::Invalid(format!("unclosed brace at {pos}")))
255        })?;
256        let scoped = resolve(bundle, members, &rest[..=end], own_parts, &globals)
257            .map_err(CompositeScopeError::Scope)?;
258        let key = format!("scope_{index}");
259        index += 1;
260        secret |= scoped.value.secret;
261        warnings.extend(scoped.warnings);
262        parts.push(crate::composite::Part {
263            key: key.clone(),
264            value: scoped.value.value,
265        });
266        expanded.push('{');
267        expanded.push_str(&key);
268        expanded.push('}');
269        pos += end + 1;
270    }
271    let rendered = crate::composite::render(&expanded, &parts, kind)
272        .map_err(CompositeScopeError::Composite)?;
273    Ok(CompositeOutput {
274        value: rendered.text,
275        secret,
276        warnings,
277    })
278}
279
280fn resolve_text<F>(
281    text: &str,
282    depth: usize,
283    stack: &mut Vec<String>,
284    locals: &HashMap<String, &Value>,
285    own: &HashMap<&str, &Value>,
286    slots: &HashMap<String, &Value>,
287    globals: &F,
288) -> Result<ScopedValue, ScopeError>
289where
290    F: Fn(&str) -> Option<ScopedValue>,
291{
292    let mut output = String::new();
293    let mut secret = false;
294    let mut pos = 0;
295    while pos < text.len() {
296        let rest = &text[pos..];
297        if let Some(tail) = rest.strip_prefix("{{") {
298            output.push('{');
299            pos = text.len() - tail.len();
300            continue;
301        }
302        if let Some(tail) = rest.strip_prefix("}}") {
303            output.push('}');
304            pos = text.len() - tail.len();
305            continue;
306        }
307        if let Some(tail) = rest.strip_prefix("${") {
308            let close = tail.find('}').ok_or_else(|| {
309                ScopeError::Invalid(format!("unclosed global reference at {pos}"))
310            })?;
311            let name = &tail[..close];
312            let value =
313                globals(name).ok_or_else(|| ScopeError::Unresolved(format!("\u{24}{{{name}}}")))?;
314            secret |= value.secret;
315            output.push_str(&value.value);
316            pos += 2 + close + 1;
317            continue;
318        }
319        let ch = rest.chars().next().expect("pos is within text");
320        if ch == '}' {
321            return Err(ScopeError::Invalid(format!(
322                "unmatched closing brace at {pos}"
323            )));
324        }
325        if ch != '{' {
326            output.push(ch);
327            pos += ch.len_utf8();
328            continue;
329        }
330        let close = rest
331            .find('}')
332            .ok_or_else(|| ScopeError::Invalid(format!("unclosed brace at {pos}")))?;
333        let name = &rest[1..close];
334        if !valid_name(name) {
335            return Err(ScopeError::Invalid(format!("invalid reference \"{name}\"")));
336        }
337        let resolved = if let Some(part) = own.get(name) {
338            value_from_var(part)?
339        } else if let Some(local) = locals.get(name) {
340            if stack.iter().any(|item| item == name) {
341                let mut path = stack.clone();
342                path.push(name.to_owned());
343                return Err(ScopeError::Cycle(path));
344            }
345            let raw = string_field(local, "value").unwrap_or_default();
346            let kind = string_field(local, "kind").unwrap_or_default();
347            let inner = if kind == "template" {
348                if depth >= MAX_DEPTH && has_reference(raw) {
349                    return Err(ScopeError::Depth(name.to_owned()));
350                }
351                stack.push(name.to_owned());
352                let result = resolve_text(raw, depth + 1, stack, locals, own, slots, globals);
353                stack.pop();
354                result?
355            } else {
356                ScopedValue {
357                    value: raw.to_owned(),
358                    secret: false,
359                }
360            };
361            ScopedValue {
362                value: inner.value,
363                secret: inner.secret
364                    || (!bool_field(local, "public")
365                        && local.get("secret").and_then(Value::as_bool) != Some(false)),
366            }
367        } else if let Some((slot, field)) = name.split_once('.') {
368            slots
369                .get(slot)
370                .and_then(|entry| entry_field(entry, field))
371                .ok_or_else(|| ScopeError::Unresolved(name.to_owned()))?
372        } else {
373            return Err(ScopeError::Unresolved(name.to_owned()));
374        };
375        secret |= resolved.secret;
376        output.push_str(&resolved.value);
377        pos += close + 1;
378    }
379    Ok(ScopedValue {
380        value: output,
381        secret,
382    })
383}
384
385fn valid_name(name: &str) -> bool {
386    let mut parts = name.split('.');
387    let valid_ident = |s: &str| {
388        let mut chars = s.chars();
389        chars
390            .next()
391            .is_some_and(|c| c == '_' || c.is_ascii_alphabetic())
392            && chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
393    };
394    let first = parts.next().is_some_and(valid_ident);
395    first && parts.next().is_none_or(valid_ident) && parts.next().is_none()
396}
397
398fn has_reference(text: &str) -> bool {
399    let bytes = text.as_bytes();
400    bytes.windows(2).any(|w| w == b"${") || bytes.windows(2).any(|w| w[0] == b'{' && w[1] != b'{')
401}
402
403fn value_from_var(value: &Value) -> Result<ScopedValue, ScopeError> {
404    let raw = string_field(value, "value")
405        .ok_or_else(|| ScopeError::Invalid("part has no string value".to_owned()))?;
406    Ok(ScopedValue {
407        value: raw.to_owned(),
408        secret: value.get("public").and_then(Value::as_bool) != Some(true)
409            && value.get("secret").and_then(Value::as_bool) != Some(false),
410    })
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416    use serde_json::json;
417
418    #[test]
419    fn matches_the_shared_typescript_parity_fixture() {
420        let fixture: Value = serde_json::from_str(include_str!(
421            "../../tests/fixtures/parity/bundle-scope.json"
422        ))
423        .unwrap();
424        for case in fixture["cases"].as_array().unwrap() {
425            let members = case["members"].as_array().unwrap();
426            let out = resolve(
427                &case["bundle"],
428                members,
429                case["template"].as_str().unwrap(),
430                &[],
431                |_| None,
432            )
433            .unwrap_or_else(|err| panic!("{}: {err:?}", case["name"]));
434            assert_eq!(out.value.value, case["expected"]["value"].as_str().unwrap());
435            assert_eq!(
436                out.value.secret,
437                case["expected"]["secret"].as_bool().unwrap()
438            );
439        }
440        for case in fixture["composites"].as_array().unwrap() {
441            let out = render_composite(
442                &case["bundle"],
443                case["members"].as_array().unwrap(),
444                case["template"].as_str().unwrap(),
445                case["own_parts"].as_array().unwrap(),
446                crate::composite::Kind::parse(case["kind"].as_str().unwrap()),
447                |_| None,
448            )
449            .unwrap_or_else(|err| panic!("{}: {err:?}", case["name"]));
450            assert_eq!(out.value, case["expected"]["value"].as_str().unwrap());
451            assert_eq!(out.secret, case["expected"]["secret"].as_bool().unwrap());
452        }
453    }
454
455    #[test]
456    fn resolves_siblings_and_propagates_taint() {
457        let bundle = json!({"secretType":"bundle", "extra_vars":[{"key":"prefix","value":">","public":true}]});
458        let member = json!({"provider":"Discord", "bundle_slot":"discord", "api_key":"token", "extra_vars":[{"key":"id","value":"9007199254740993","public":true}]});
459        let out = resolve(
460            &bundle,
461            &[member],
462            "{prefix}{discord.id}:{discord.key}",
463            &[],
464            |_| None,
465        )
466        .unwrap();
467        assert_eq!(
468            out.value,
469            ScopedValue {
470                value: ">9007199254740993:token".into(),
471                secret: true
472            }
473        );
474    }
475
476    #[test]
477    fn unresolved_cycles_and_depth_refuse_rendering() {
478        let missing = resolve(&json!({}), &[], "{missing}", &[], |_| None).unwrap_err();
479        assert_eq!(missing, ScopeError::Unresolved("missing".into()));
480        let cycle = json!({"extra_vars":[{"key":"a","value":"{b}","kind":"template"},{"key":"b","value":"{a}","kind":"template"}]});
481        assert!(matches!(
482            resolve(&cycle, &[], "{a}", &[], |_| None),
483            Err(ScopeError::Cycle(_))
484        ));
485        let deep = json!({"extra_vars":[
486            {"key":"a","value":"{b}","kind":"template"}, {"key":"b","value":"{c}","kind":"template"},
487            {"key":"c","value":"{d}","kind":"template"}, {"key":"d","value":"{e}","kind":"template"},
488            {"key":"e","value":"{f}","kind":"template"}, {"key":"f","value":"end","kind":"template"}
489        ]});
490        assert!(matches!(
491            resolve(&deep, &[], "{a}", &[], |_| None),
492            Err(ScopeError::Depth(_))
493        ));
494    }
495}