Skip to main content

agentmux_srv_core/backend/vault/import/
env.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `.env` files and shell `export` lines: each `NAME=value` is an API key, with
5//! the variable name as its label and suggested environment variable
6//! (spec ยง8.4).
7
8use super::{Imported, Incoming, ReadError, Source, MAX_ITEMS};
9
10/// A line's `NAME` and raw value, or `None` for a blank line, a comment or
11/// anything else.
12fn split_line(line: &str) -> Option<(&str, &str)> {
13    let line = line.trim();
14    if line.is_empty() || line.starts_with('#') {
15        return None;
16    }
17    let line = line.strip_prefix("export ").map(str::trim_start).unwrap_or(line);
18    let (name, value) = line.split_once('=')?;
19    let name = name.trim();
20    let mut chars = name.chars();
21    let first = chars.next()?;
22    (first.is_ascii_alphabetic() || first == '_').then_some(())?;
23    chars.all(|c| c.is_ascii_alphanumeric() || c == '_').then_some(())?;
24    Some((name, value.trim()))
25}
26
27/// The value of a line: quoted (single quotes are literal, double quotes take
28/// `\n`, `\t`, `\"` and `\\`), or bare up to a ` #` comment.
29fn value_of(raw: &str) -> String {
30    let mut chars = raw.chars();
31    match chars.next() {
32        Some(q @ ('"' | '\'')) => {
33            let mut out = String::new();
34            let mut escaped = false;
35            for c in chars {
36                if q == '"' && escaped {
37                    out.push(match c {
38                        'n' => '\n',
39                        't' => '\t',
40                        other => other,
41                    });
42                    escaped = false;
43                } else if q == '"' && c == '\\' {
44                    escaped = true;
45                } else if c == q {
46                    break;
47                } else {
48                    out.push(c);
49                }
50            }
51            out
52        }
53        _ => raw.split(" #").next().unwrap_or("").trim().to_string(),
54    }
55}
56
57/// Whether text is a `.env` file: at least one `NAME=value` line, and every
58/// non-blank, non-comment line is one.
59pub fn looks_like_env(text: &str) -> bool {
60    let mut any = false;
61    for line in text.lines().filter(|l| !l.trim().is_empty() && !l.trim().starts_with('#')).take(200) {
62        if split_line(line).is_none() {
63            return false;
64        }
65        any = true;
66    }
67    any
68}
69
70pub fn read(text: &str) -> Result<Imported, ReadError> {
71    let mut entries = Vec::new();
72    let mut skipped = Vec::new();
73    let mut seen = std::collections::HashSet::new();
74    for line in text.lines() {
75        let Some((name, raw)) = split_line(line) else { continue };
76        if entries.len() + skipped.len() >= MAX_ITEMS {
77            return Err(format!("this file has more than {MAX_ITEMS} variables, more than the Vault imports").into());
78        }
79        let value = value_of(raw);
80        if value.is_empty() {
81            skipped.push((name.to_string(), "it has no value".to_string()));
82            continue;
83        }
84        if !seen.insert(name.to_string()) {
85            // The last assignment is the one that counts in a shell: the later one wins.
86            entries.retain(|e: &Incoming| e.label != name);
87        }
88        entries.push(Incoming::new("api-key", name).part("value", &value).field("env_name", name));
89    }
90    if entries.is_empty() && skipped.is_empty() {
91        return Err("no NAME=value lines were found".into());
92    }
93    Ok(Imported { source: Source::Env, entries, skipped, plaintext: true })
94}