Skip to main content

rws_http/entry_point/config_file/
mod.rs

1use std::collections::HashMap;
2use std::env;
3use std::io::{BufRead, Cursor};
4use crate::entry_point::command_line_args::CommandLineArgument;
5use file_ext::FileExt;
6
7#[doc(hidden)]
8pub mod toml_str;
9use toml_str::{unquote, Quotes};
10
11#[cfg(test)]
12mod tests;
13
14/// Settings that have an `RWS_CONFIG_*` variable but no command-line flag.
15/// In `rws.config.toml` they're written like any other key — the variable
16/// name is the table path plus key, upper-cased: `[rate_limit] max_requests`
17/// → `RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS`. Settings that do have a flag are
18/// taken from `CommandLineArgument::get_command_line_arg_list()` instead.
19/// `tests.rs` checks this list against every `RWS_CONFIG_*` name in `src/`.
20pub const SETTINGS_WITHOUT_FLAG: &[&str] = &[
21    "RWS_CONFIG_CACHE_STATUS",
22    "RWS_CONFIG_TLS_INTERNAL_DIR",
23    "RWS_CONFIG_TLS_INTERNAL_NAMES",
24    "RWS_CONFIG_ERROR_FORMAT",
25    "RWS_CONFIG_TLS_CLIENT_CRL_FILE",
26    "RWS_CONFIG_TLS_CLIENT_CRL_STRICT",
27    "RWS_CONFIG_FORWARDED_HEADER",
28    "RWS_CONFIG_TRUSTED_PROXIES",
29    "RWS_CONFIG_PROXY_NAME",
30    "RWS_CONFIG_PROXY_STATUS",
31    "RWS_CONFIG_PROXY_STATUS_NEXT_HOP",
32    "RWS_CONFIG_ACME_ACCOUNT_KEY_PATH",
33    "RWS_CONFIG_ADMIN_ALLOWED_ORIGINS",
34    "RWS_CONFIG_ADMIN_USERS",
35    "RWS_CONFIG_CLUSTER_NODE",
36    "RWS_CONFIG_FLEET_SOURCE",
37    "RWS_CONFIG_FLEET_INTERVAL_SECS",
38    "RWS_CONFIG_FLEET_PUBLIC_KEY",
39    "RWS_CONFIG_FLEET_INSECURE",
40    "RWS_CONFIG_FLEET_REPORT_URL",
41    "RWS_CONFIG_FLEET_S3_ENDPOINT",
42    "RWS_CONFIG_CLUSTER_REDIS",
43    "RWS_CONFIG_CLUSTER_REDIS_PASSWORD",
44    "RWS_CONFIG_CLUSTER_PREFIX",
45    "RWS_CONFIG_ADMIN_AUDIT_LOG",
46    "RWS_CONFIG_ADMIN_OIDC_ISSUER",
47    "RWS_CONFIG_ADMIN_OIDC_PROVIDER",
48    "RWS_CONFIG_ADMIN_OIDC_TENANT",
49    "RWS_CONFIG_ADMIN_OIDC_CLIENT_ID",
50    "RWS_CONFIG_ADMIN_OIDC_CLIENT_SECRET_ENV",
51    "RWS_CONFIG_ADMIN_OIDC_COOKIE_SECRET_ENV",
52    "RWS_CONFIG_ADMIN_OIDC_ROLES",
53    "RWS_CONFIG_ADMIN_OIDC_ROLE_CLAIM",
54    "RWS_CONFIG_ADMIN_LISTEN",
55    "RWS_CONFIG_ADMIN_TOKEN_ENV",
56    "RWS_CONFIG_ACME_RENEW_BEFORE_DAYS",
57    "RWS_CONFIG_ACME_RENEW_CHECK_INTERVAL_SECS",
58    "RWS_CONFIG_CIRCUIT_BREAKER_FAILURE_THRESHOLD",
59    "RWS_CONFIG_CIRCUIT_BREAKER_MAX_HALF_OPEN_PROBES",
60    "RWS_CONFIG_CIRCUIT_BREAKER_RECOVERY_SECS",
61    "RWS_CONFIG_CLIENT_HINTS",
62    "RWS_CONFIG_CSP",
63    "RWS_CONFIG_ACME_DNS_TSIG_SECRET",
64    "RWS_CONFIG_ACME_REDIS_PASSWORD",
65    "RWS_CONFIG_ACME_DNS_API_TOKEN",
66    "RWS_CONFIG_ACCESS_LOG",
67    "RWS_CONFIG_ACCESS_LOG_KEEP",
68    "RWS_CONFIG_ACCESS_LOG_MAX_SIZE",
69    "RWS_CONFIG_GATEWAY_API_CONTROLLER_NAME",
70    "RWS_CONFIG_GATEWAY_API_ENABLED",
71    "RWS_CONFIG_GATEWAY_API_GATEWAY",
72    "RWS_CONFIG_GATEWAY_API_IMAGE",
73    "RWS_CONFIG_GATEWAY_API_LEASE_NAMESPACE",
74    "RWS_CONFIG_GATEWAY_API_MODE",
75    "RWS_CONFIG_GATEWAY_API_POD_SELECTOR",
76    "RWS_CONFIG_GATEWAY_API_PORT_RANGE",
77    "RWS_CONFIG_GATEWAY_API_SERVICE_ACCOUNT",
78    "RWS_CONFIG_GATEWAY_API_SERVICE_TYPE",
79    "RWS_CONFIG_COMPRESSION_DICTIONARIES",
80    "RWS_CONFIG_EARLY_HINTS_HTTP1",
81    "RWS_CONFIG_LOG_FORMAT",
82    "RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES",
83    "RWS_CONFIG_MIN_FREE_DISK",
84    "RWS_CONFIG_NANOS_HEADERS",
85    "RWS_CONFIG_OPEN_FILE_CACHE_SECS",
86    "RWS_CONFIG_OPEN_FILE_CACHE_STRICT",
87    "RWS_CONFIG_PROXY_PROTOCOL",
88    "RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS",
89    "RWS_CONFIG_RATE_LIMIT_WINDOW_SECS",
90    "RWS_CONFIG_RUNTIME",
91    "RWS_CONFIG_SECURITY_HEADERS",
92    "RWS_CONFIG_SERVE_DOTFILES",
93    "RWS_CONFIG_SPA_FALLBACK",
94    "RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES",
95    "RWS_CONFIG_STATIC_CACHE_CONTROL",
96    "RWS_CONFIG_DIRECTORY_LISTING",
97    "RWS_CONFIG_TEMPLATE_DIR",
98    "RWS_CONFIG_TLS_CLIENT_CA_FILE",
99    "RWS_CONFIG_WATCH",
100    "RWS_CONFIG_TRAFFIC_ENABLED",
101    "RWS_CONFIG_TRAFFIC_EXCLUDE",
102    "RWS_CONFIG_TRAFFIC_PERSIST",
103    "RWS_CONFIG_TRAFFIC_RETENTION_DAYS",
104];
105
106/// Tables (and their sub-tables) read by `proxy_config`'s own parser, not
107/// mapped to `RWS_CONFIG_*` variables.
108const PROXY_TABLES: &[&str] = &["route", "upstream", "tcp_proxy", "udp_proxy", "ws_proxy", "middleware", "authz"];
109
110/// `[[virtual_host]]` fields, set as `RWS_CONFIG_VIRTUAL_HOST_<n>_<FIELD>`.
111const VIRTUAL_HOST_FIELDS: &[&str] = &["DOMAIN", "CERT_FILE", "KEY_FILE"];
112
113/// The settings of a `rws.config.toml` document, resolved to the
114/// `RWS_CONFIG_*` variables they set — without touching the environment.
115#[derive(Debug, Default, PartialEq)]
116pub struct ConfigSettings {
117    /// `(RWS_CONFIG_* name, value)` in file order.
118    pub settings: Vec<(String, String)>,
119    /// Keys no setting answers to, as `key` or `[table] key`.
120    pub unknown: Vec<String>,
121}
122
123/// Resolve every setting in a `rws.config.toml` document. `prefix` is the
124/// table the document starts in (normally empty).
125///
126/// Top-level keys and keys in plain `[tables]` map to `RWS_CONFIG_<TABLE>_<KEY>`
127/// (`[cors] allow_all` → `RWS_CONFIG_CORS_ALLOW_ALL`); each `[[virtual_host]]`
128/// block maps to `RWS_CONFIG_VIRTUAL_HOST_<n>_*`. Strings keep their exact
129/// contents (spaces, quotes inside them); arrays become comma-separated lists.
130/// Proxy tables (`[[route]]`, `[[upstream]]`, …) are left to `proxy_config`.
131pub fn collect_settings(
132    cursor: Cursor<&[u8]>,
133    prefix: String) -> Result<ConfigSettings, String> {
134
135    let mut table = prefix;
136    // Index of the current [[array-table]] entry, per array-table name.
137    let mut array_table_counters: HashMap<String, usize> = HashMap::new();
138    let mut array_index: Option<usize> = None;
139    let mut resolved = ConfigSettings::default();
140    let flags = CommandLineArgument::get_command_line_arg_list();
141
142    for line in cursor.lines() {
143        let line = line.map_err(|e| e.to_string())?;
144        let line = strip_comment(&line).trim().to_string();
145        if line.is_empty() {
146            continue;
147        }
148
149        if let Some(name) = line.strip_prefix("[[").and_then(|l| l.strip_suffix("]]")) {
150            let name = name.trim().to_string();
151            let count = array_table_counters.entry(name.clone()).or_insert(0);
152            array_index = Some(*count);
153            *count += 1;
154            table = name;
155            continue;
156        }
157        if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
158            table = name.trim().to_string();
159            array_index = None;
160            continue;
161        }
162
163        let Some((raw_key, raw_value)) = line.split_once('=') else { continue };
164        let key = raw_key.trim();
165
166        let root = table.split('.').next().unwrap_or("");
167        if PROXY_TABLES.contains(&root) {
168            continue;
169        }
170
171        // An inline table, `rate_limit = { max_requests = 5 }`, is the
172        // sub-table `[rate_limit]` (or `[<table>.rate_limit]`), as in TOML
173        // and as in the proxy sections.
174        if let Some(inner) = raw_value.trim().strip_prefix('{').and_then(|v| v.strip_suffix('}')) {
175            let sub_table = if table.is_empty() { key.to_string() } else { format!("{}.{}", table, key) };
176            for entry in split_top_level(inner) {
177                if let Some((inner_key, inner_value)) = entry.split_once('=') {
178                    resolve_setting(&sub_table, array_index, inner_key.trim(), parse_value(inner_value), &flags, &mut resolved);
179                } else if !entry.trim().is_empty() {
180                    resolved.unknown.push(qualified_key(&sub_table, entry.trim()));
181                }
182            }
183            continue;
184        }
185
186        resolve_setting(&table, array_index, key, parse_value(raw_value), &flags, &mut resolved);
187    }
188
189    Ok(resolved)
190}
191
192/// Map one `key = value` in `table` to its `RWS_CONFIG_*` setting, or record
193/// it as unknown.
194fn resolve_setting(
195    table: &str,
196    array_index: Option<usize>,
197    key: &str,
198    value: String,
199    flags: &[CommandLineArgument],
200    resolved: &mut ConfigSettings,
201) {
202    if table == "virtual_host" {
203        let field = key.to_ascii_uppercase();
204        if VIRTUAL_HOST_FIELDS.contains(&field.as_str()) {
205            let name = format!("RWS_CONFIG_VIRTUAL_HOST_{}_{}", array_index.unwrap_or(0), field);
206            resolved.settings.push((name, value));
207        } else {
208            resolved.unknown.push(qualified_key(table, key));
209        }
210        return;
211    }
212
213    let path = if table.is_empty() { key.to_string() } else { format!("{}_{}", table.replace('.', "_"), key) };
214    let long_form = path.replace('_', "-");
215    if let Some(flag) = flags.iter().find(|f| f.long_form == long_form) {
216        resolved.settings.push((flag.environment_variable.clone(), value));
217        return;
218    }
219    let name = format!("RWS_CONFIG_{}", path.to_ascii_uppercase());
220    if SETTINGS_WITHOUT_FLAG.contains(&name.as_str()) {
221        resolved.settings.push((name, value));
222    } else {
223        resolved.unknown.push(qualified_key(table, key));
224    }
225}
226
227/// Split an inline table's body on commas outside quotes and `[...]`.
228fn split_top_level(inner: &str) -> Vec<&str> {
229    let mut items = vec![];
230    let mut quote: Option<char> = None;
231    let mut depth = 0usize;
232    let mut start = 0;
233    for (i, c) in inner.char_indices() {
234        match (quote, c) {
235            (None, '"') | (None, '\'') => quote = Some(c),
236            (Some(q), c) if c == q => quote = None,
237            (None, '[') => depth += 1,
238            (None, ']') => depth = depth.saturating_sub(1),
239            (None, ',') if depth == 0 => {
240                items.push(&inner[start..i]);
241                start = i + 1;
242            }
243            _ => {}
244        }
245    }
246    items.push(&inner[start..]);
247    items
248}
249
250/// Apply every setting in a `rws.config.toml` document to the process
251/// environment (see [`collect_settings`]). Unknown keys are reported on
252/// stderr instead of being ignored silently.
253pub fn read_config_file(
254    cursor: Cursor<&[u8]>,
255    prefix: String) -> Result<bool, String> {
256    let resolved = collect_settings(cursor, prefix)?;
257    for (name, value) in &resolved.settings {
258        set_setting(name, value);
259    }
260    for key in &resolved.unknown {
261        eprintln!("    Warning: unknown setting '{}' in rws.config.toml — ignored", key);
262    }
263    Ok(true)
264}
265
266fn set_setting(name: &str, value: &str) {
267    if value.contains('\0') {
268        // env::set_var panics on NUL — a stray byte in the file must not crash startup.
269        eprintln!("    Warning: value for {} contains a NUL byte — ignored", name);
270        return;
271    }
272    env::set_var(name, value);
273    crate::server_config::invalidate();
274    println!("    Set env variable '{}' to value '{}'", name, crate::entry_point::shown(name, value));
275}
276
277fn qualified_key(table: &str, key: &str) -> String {
278    if table.is_empty() { key.to_string() } else { format!("[{}] {}", table, key) }
279}
280
281/// Drop a trailing `# comment`, ignoring `#` inside quoted strings.
282fn strip_comment(line: &str) -> &str {
283    let mut quotes = Quotes::default();
284    for (i, c) in line.char_indices() {
285        if !quotes.step(c) && c == '#' {
286            return &line[..i];
287        }
288    }
289    line
290}
291
292/// A TOML value as a plain string: quoted strings lose their quotes (basic
293/// strings also their escapes, see [`toml_str::unquote`]), arrays become
294/// `a,b,c`, anything else (numbers, booleans) is trimmed.
295fn parse_value(raw: &str) -> String {
296    let raw = raw.trim();
297    if let Some(inner) = raw.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
298        return split_array(inner)
299            .iter()
300            .map(|item| unquote(item.trim()))
301            .filter(|item| !item.is_empty())
302            .collect::<Vec<_>>()
303            .join(",");
304    }
305    unquote(raw)
306}
307
308/// Split array items on commas outside quotes.
309fn split_array(inner: &str) -> Vec<&str> {
310    let mut items = vec![];
311    let mut quotes = Quotes::default();
312    let mut start = 0;
313    for (i, c) in inner.char_indices() {
314        if !quotes.step(c) && c == ',' {
315            items.push(&inner[start..i]);
316            start = i + 1;
317        }
318    }
319    items.push(&inner[start..]);
320    items
321}
322
323/// Load `rws.config.toml` into the environment: `filepath` (relative to the
324/// working directory) when given, else the file named by `RWS_CONFIG_FILE`
325/// (absolute, or relative to the working directory) — the same variable
326/// `proxy_config` reads routes from — else `rws.config.toml` in the working
327/// directory.
328pub fn override_environment_variables_from_config(filepath: Option<&str>) {
329    println!("\n  Start of Config Section");
330
331    let from_env = env::var("RWS_CONFIG_FILE").ok().filter(|p| !p.trim().is_empty());
332    let resolved = match (filepath, from_env) {
333        (Some(path), _) => FileExt::get_static_filepath(path),
334        (None, Some(path)) => Ok(path),
335        (None, None) => FileExt::get_static_filepath("/rws.config.toml"),
336    };
337    let path = match resolved {
338        Ok(path) => path,
339        Err(e) => {
340            eprintln!("{}", e);
341            println!("  End of Config Section");
342            return;
343        }
344    };
345
346    match std::fs::read_to_string(&path) {
347        Ok(content) => {
348            if let Err(e) = read_config_file(Cursor::new(content.as_bytes()), String::new()) {
349                eprintln!("    Unable to parse {}: {}", path, e);
350            }
351        }
352        Err(e) => eprintln!("    Unable to read {}: {}", path, e),
353    }
354
355    println!("  End of Config Section");
356}