Skip to main content

next_rust_core/
env.rs

1//! `.env` loading with an explicit server/public split.
2//!
3//! Files are loaded in increasing priority:
4//!
5//! 1. `.env`
6//! 2. `.env.{environment}` (e.g. `.env.production`)
7//! 3. `.env.local` (skipped when environment is `test`)
8//! 4. `.env.{environment}.local`
9//!
10//! Variables already present in the process environment always win, so
11//! platform-provided secrets are never overwritten by files.
12//!
13//! Only variables whose name starts with the public prefix (by default
14//! `NEXT_RUST_PUBLIC_`) are returned by [`EnvVars::public`]. Nothing else is
15//! ever made available to client-visible output.
16
17use std::collections::BTreeMap;
18use std::path::Path;
19
20use crate::mode::Environment;
21
22#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct EnvVars {
24    vars: BTreeMap<String, String>,
25    public_prefix: String,
26}
27
28impl EnvVars {
29    /// Read `.env` files from `root` without modifying the process environment.
30    pub fn load(root: &Path, environment: Environment, public_prefix: &str) -> std::io::Result<Self> {
31        let env = environment.as_str();
32        let mut files = vec![".env".to_owned(), format!(".env.{env}")];
33        if environment != Environment::Test {
34            files.push(".env.local".to_owned());
35        }
36        files.push(format!(".env.{env}.local"));
37
38        let mut vars = BTreeMap::new();
39        for file in files {
40            let path = root.join(&file);
41            match std::fs::read_to_string(&path) {
42                Ok(text) => vars.extend(parse(&text)),
43                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
44                Err(e) => return Err(e),
45            }
46        }
47        for (k, v) in vars.iter_mut() {
48            if let Ok(existing) = std::env::var(k) {
49                *v = existing;
50            }
51        }
52        Ok(Self { vars, public_prefix: public_prefix.to_owned() })
53    }
54
55    /// Export loaded values into the process environment (only for keys that
56    /// are not already set). Call once at startup before spawning threads.
57    pub fn apply_to_process(&self) {
58        for (k, v) in &self.vars {
59            if std::env::var_os(k).is_none() {
60                // SAFETY: called during single-threaded startup, see docs.
61                unsafe_set_var(k, v);
62            }
63        }
64    }
65
66    pub fn get(&self, key: &str) -> Option<&str> {
67        self.vars.get(key).map(String::as_str)
68    }
69
70    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
71        self.vars.iter().map(|(k, v)| (k.as_str(), v.as_str()))
72    }
73
74    /// Variables that are safe to expose to clients.
75    pub fn public(&self) -> BTreeMap<String, String> {
76        let mut out: BTreeMap<String, String> = self
77            .vars
78            .iter()
79            .filter(|(k, _)| k.starts_with(&self.public_prefix))
80            .map(|(k, v)| (k.clone(), v.clone()))
81            .collect();
82        for (k, v) in std::env::vars() {
83            if k.starts_with(&self.public_prefix) {
84                out.insert(k, v);
85            }
86        }
87        out
88    }
89
90    pub fn is_public(&self, key: &str) -> bool {
91        key.starts_with(&self.public_prefix)
92    }
93}
94
95#[allow(unsafe_code)]
96fn unsafe_set_var(k: &str, v: &str) {
97    // `set_var` is `unsafe` since edition 2024 because it races with other
98    // threads reading the environment. The framework only calls this from
99    // `main` before the async runtime starts.
100    unsafe { std::env::set_var(k, v) }
101}
102
103/// Parse dotenv syntax.
104///
105/// Supports `KEY=value`, `export KEY=value`, `# comments`, single quotes
106/// (literal), double quotes (with `\n`, `\t`, `\"`, `\\` escapes and
107/// multi-line values) and inline comments after unquoted values.
108pub fn parse(text: &str) -> BTreeMap<String, String> {
109    let mut out = BTreeMap::new();
110    let mut lines = text.lines();
111    while let Some(raw) = lines.next() {
112        let line = raw.trim();
113        if line.is_empty() || line.starts_with('#') {
114            continue;
115        }
116        let line = line.strip_prefix("export ").unwrap_or(line);
117        let Some((key, value)) = line.split_once('=') else { continue };
118        let key = key.trim();
119        if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') {
120            continue;
121        }
122        let value = value.trim_start();
123        let parsed = if let Some(rest) = value.strip_prefix('"') {
124            let mut buf = rest.to_owned();
125            // Multi-line double-quoted values.
126            while !closes_double_quote(&buf) {
127                match lines.next() {
128                    Some(next) => {
129                        buf.push('\n');
130                        buf.push_str(next);
131                    }
132                    None => break,
133                }
134            }
135            unescape_double(&buf)
136        } else if let Some(rest) = value.strip_prefix('\'') {
137            rest.split_once('\'').map(|(v, _)| v.to_owned()).unwrap_or_else(|| rest.to_owned())
138        } else {
139            let v = match value.find(" #") {
140                Some(i) => &value[..i],
141                None => value,
142            };
143            v.trim().to_owned()
144        };
145        out.insert(key.to_owned(), parsed);
146    }
147    out
148}
149
150fn closes_double_quote(s: &str) -> bool {
151    let mut escaped = false;
152    for c in s.chars() {
153        match c {
154            '\\' if !escaped => escaped = true,
155            '"' if !escaped => return true,
156            _ => escaped = false,
157        }
158    }
159    false
160}
161
162fn unescape_double(s: &str) -> String {
163    let mut out = String::with_capacity(s.len());
164    let mut chars = s.chars();
165    while let Some(c) = chars.next() {
166        match c {
167            '\\' => match chars.next() {
168                Some('n') => out.push('\n'),
169                Some('t') => out.push('\t'),
170                Some('r') => out.push('\r'),
171                Some(other) => out.push(other),
172                None => {}
173            },
174            '"' => break,
175            c => out.push(c),
176        }
177    }
178    out
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn parses_dotenv() {
187        let vars = parse(
188            "# comment\nA=1\nexport B = two # trailing\nC=\"line\\nnext\"\nD='lit $x \\n'\nE=\"multi\nline\"\nbad line\n",
189        );
190        assert_eq!(vars["A"], "1");
191        assert_eq!(vars["B"], "two");
192        assert_eq!(vars["C"], "line\nnext");
193        assert_eq!(vars["D"], "lit $x \\n");
194        assert_eq!(vars["E"], "multi\nline");
195        assert_eq!(vars.len(), 5);
196    }
197
198    #[test]
199    fn layering_and_public_split() {
200        let dir = std::env::temp_dir().join(format!("nr-env-{}", std::process::id()));
201        std::fs::create_dir_all(&dir).unwrap();
202        std::fs::write(dir.join(".env"), "DATABASE_URL=base\nNEXT_RUST_PUBLIC_SITE=a\n").unwrap();
203        std::fs::write(dir.join(".env.production"), "DATABASE_URL=prod\n").unwrap();
204        std::fs::write(dir.join(".env.local"), "NEXT_RUST_PUBLIC_SITE=local\n").unwrap();
205        let env = EnvVars::load(&dir, Environment::Production, "NEXT_RUST_PUBLIC_").unwrap();
206        assert_eq!(env.get("DATABASE_URL"), Some("prod"));
207        let public = env.public();
208        assert_eq!(public.get("NEXT_RUST_PUBLIC_SITE").map(String::as_str), Some("local"));
209        assert!(!public.contains_key("DATABASE_URL"));
210        // .env.local is ignored for tests
211        let env = EnvVars::load(&dir, Environment::Test, "NEXT_RUST_PUBLIC_").unwrap();
212        assert_eq!(env.get("NEXT_RUST_PUBLIC_SITE"), Some("a"));
213        std::fs::remove_dir_all(&dir).unwrap();
214    }
215}