Skip to main content

rws_proxy/config_check/
syntax.rs

1//! TOML syntax for `rws --check` (18.37.0): the server's reader is
2//! line-based and forgiving (an unclosed `[[route]` header was skipped, and
3//! `--check` said "configuration OK"), so the check reads the file as TOML
4//! first and reports the first mistakes with line and column.
5//!
6//! Structural mistakes are errors: a table header that isn't closed, a line
7//! that is neither a header nor `key = value`, a string, array or inline
8//! table that isn't closed, an empty value. A bare word where TOML wants a
9//! quoted string (`ip = 0.0.0.0`) is a warning: rws reads it anyway.
10
11/// One finding: 1-based line and column, and the message.
12#[derive(Debug, PartialEq)]
13pub struct Finding {
14    pub line: usize,
15    pub column: usize,
16    pub message: String,
17    pub error: bool,
18}
19
20/// Check `content` as TOML; at most 20 findings.
21pub fn check(content: &str) -> Vec<Finding> {
22    let mut out = Vec::new();
23    let lines: Vec<&str> = content.lines().collect();
24    let mut i = 0;
25    while i < lines.len() && out.len() < 20 {
26        let number = i + 1;
27        let raw = lines[i];
28        let indent = raw.len() - raw.trim_start().len();
29        let line = raw.trim();
30        i += 1;
31        if line.is_empty() || line.starts_with('#') {
32            continue;
33        }
34        let at = |column: usize, message: String, error: bool| Finding { line: number, column, message, error };
35        if line.starts_with('[') {
36            let code = strip_comment(line).trim_end();
37            let double = code.starts_with("[[");
38            let close = if double { "]]" } else { "]" };
39            if !code.ends_with(close) || (double && code.len() < 4) {
40                out.push(at(indent + code.len() + 1, format!("table header {code} is not closed: expected `{close}`"), true));
41                continue;
42            }
43            let name = code.trim_start_matches('[').trim_end_matches(']').trim();
44            if !double && code.ends_with("]]") {
45                out.push(at(indent + 1, format!("table header {code} opens with `[` but closes with `]]`"), true));
46            } else if name.is_empty() || !valid_key_path(name) {
47                out.push(at(indent + 2, format!("table header {code}: `{name}` is not a valid table name"), true));
48            }
49            continue;
50        }
51        let Some(eq) = find_outside_quotes(line, '=') else {
52            out.push(at(indent + 1, format!("expected `key = value` or a [table] header, found `{}`", shorten(line)), true));
53            continue;
54        };
55        let key = line[..eq].trim();
56        if key.is_empty() || !valid_key_path(key) {
57            out.push(at(indent + 1, format!("`{}` is not a valid key", shorten(key)), true));
58            continue;
59        }
60        let value_start = indent + eq + 1;
61        let mut value = strip_comment(line[eq + 1..].trim()).trim().to_string();
62        let value_column = value_start + (line[eq + 1..].len() - line[eq + 1..].trim_start().len()) + 1;
63        if value.is_empty() {
64            out.push(at(value_column, format!("`{key} =` has no value"), true));
65            continue;
66        }
67        // Multi-line strings and arrays/inline tables over several lines.
68        for delim in ["\"\"\"", "'''"] {
69            if value.starts_with(delim) && (value.len() < 6 || !value[3..].contains(delim)) {
70                let mut closed = false;
71                while i < lines.len() {
72                    let next = lines[i];
73                    i += 1;
74                    if next.contains(delim) {
75                        closed = true;
76                        break;
77                    }
78                }
79                if !closed {
80                    out.push(at(value_column, format!("the multi-line string for `{key}` is not closed: expected {delim}"), true));
81                }
82                value.clear();
83                break;
84            }
85        }
86        if value.is_empty() {
87            continue;
88        }
89        if value.starts_with('[') || value.starts_with('{') {
90            let mut depth = balance(&value);
91            while depth.0 > 0 && depth.1.is_none() && i < lines.len() {
92                let next = strip_comment(lines[i].trim()).to_string();
93                i += 1;
94                value.push(' ');
95                value.push_str(&next);
96                depth = balance(&value);
97            }
98            if let Some(problem) = depth.1 {
99                out.push(at(value_column, format!("`{key}`: {problem}"), true));
100            } else if depth.0 > 0 {
101                let close = if value.starts_with('[') { "]" } else { "}" };
102                out.push(at(value_column, format!("`{key}`: not closed: expected `{close}`"), true));
103            }
104            continue;
105        }
106        if value.starts_with('"') || value.starts_with('\'') {
107            match closing_quote(&value) {
108                None => out.push(at(value_column, format!("the string for `{key}` is not closed: expected {}", &value[..1]), true)),
109                Some(end) if !value[end + 1..].trim().is_empty() => out.push(at(
110                    value_column + end + 1,
111                    format!("unexpected `{}` after the string for `{key}`", shorten(value[end + 1..].trim())),
112                    true,
113                )),
114                _ => {}
115            }
116            continue;
117        }
118        if !scalar(&value) {
119            out.push(at(value_column, format!("`{key} = {}`: a string needs quotes in TOML: {key} = \"{}\"", shorten(&value), value.replace('"', "\\\"")), false));
120        }
121    }
122    out
123}
124
125fn shorten(s: &str) -> String {
126    if s.chars().count() > 40 { format!("{}…", s.chars().take(40).collect::<String>()) } else { s.to_string() }
127}
128
129/// Bare (`a-b_c`), quoted (`"a b"`) and dotted (`a.b`) keys.
130fn valid_key_path(path: &str) -> bool {
131    let mut rest = path.trim();
132    loop {
133        let (part, tail) = if rest.starts_with('"') || rest.starts_with('\'') {
134            let Some(end) = closing_quote(rest) else { return false };
135            (&rest[..=end], rest[end + 1..].trim_start())
136        } else {
137            let end = rest.find('.').unwrap_or(rest.len());
138            let part = rest[..end].trim();
139            if part.is_empty() || !part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') {
140                return false;
141            }
142            (part, &rest[end..])
143        };
144        let _ = part;
145        if tail.is_empty() {
146            return true;
147        }
148        let Some(after) = tail.strip_prefix('.') else { return false };
149        rest = after.trim();
150        if rest.is_empty() {
151            return false;
152        }
153    }
154}
155
156/// Byte index of the quote closing the string `s` starts with.
157fn closing_quote(s: &str) -> Option<usize> {
158    let quote = s.chars().next()?;
159    let mut escaped = false;
160    for (i, c) in s.char_indices().skip(1) {
161        if quote == '"' && escaped {
162            escaped = false;
163            continue;
164        }
165        if quote == '"' && c == '\\' {
166            escaped = true;
167        } else if c == quote {
168            return Some(i);
169        }
170    }
171    None
172}
173
174fn find_outside_quotes(s: &str, wanted: char) -> Option<usize> {
175    let mut quote: Option<char> = None;
176    let mut escaped = false;
177    for (i, c) in s.char_indices() {
178        match quote {
179            Some('"') if escaped => escaped = false,
180            Some('"') if c == '\\' => escaped = true,
181            Some(q) if c == q => quote = None,
182            Some(_) => {}
183            None if c == '"' || c == '\'' => quote = Some(c),
184            None if c == '#' => return None,
185            None if c == wanted => return Some(i),
186            None => {}
187        }
188    }
189    None
190}
191
192/// Drop a trailing `# comment` outside quotes.
193fn strip_comment(s: &str) -> &str {
194    let mut quote: Option<char> = None;
195    let mut escaped = false;
196    for (i, c) in s.char_indices() {
197        match quote {
198            Some('"') if escaped => escaped = false,
199            Some('"') if c == '\\' => escaped = true,
200            Some(q) if c == q => quote = None,
201            Some(_) => {}
202            None if c == '"' || c == '\'' => quote = Some(c),
203            None if c == '#' => return &s[..i],
204            None => {}
205        }
206    }
207    s
208}
209
210/// Open bracket depth of an array or inline table, and the first mismatch.
211fn balance(s: &str) -> (usize, Option<String>) {
212    let mut stack: Vec<char> = Vec::new();
213    let mut quote: Option<char> = None;
214    let mut escaped = false;
215    for c in s.chars() {
216        match quote {
217            Some('"') if escaped => escaped = false,
218            Some('"') if c == '\\' => escaped = true,
219            Some(q) if c == q => quote = None,
220            Some(_) => {}
221            None => match c {
222                '"' | '\'' => quote = Some(c),
223                '[' | '{' => stack.push(c),
224                ']' | '}' => {
225                    let open = if c == ']' { '[' } else { '{' };
226                    if stack.pop() != Some(open) {
227                        return (0, Some(format!("unexpected `{c}`")));
228                    }
229                }
230                _ => {}
231            },
232        }
233    }
234    if quote.is_some() {
235        return (stack.len().max(1), Some("a string inside is not closed".to_string()));
236    }
237    (stack.len(), None)
238}
239
240/// A TOML number, boolean or date/time.
241fn scalar(v: &str) -> bool {
242    if v == "true" || v == "false" || v == "inf" || v == "nan" || v == "+inf" || v == "-inf" {
243        return true;
244    }
245    let digits = v.trim_start_matches(['+', '-']);
246    if let Some(hex) = digits.strip_prefix("0x").or_else(|| digits.strip_prefix("0o")).or_else(|| digits.strip_prefix("0b")) {
247        return !hex.is_empty() && hex.chars().all(|c| c.is_ascii_hexdigit() || c == '_');
248    }
249    if !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit() || matches!(c, '_' | '.' | 'e' | 'E' | '+' | '-')) && digits.starts_with(|c: char| c.is_ascii_digit()) {
250        return true;
251    }
252    // Dates and times: 1979-05-27, 07:32:00, 1979-05-27T07:32:00Z.
253    v.starts_with(|c: char| c.is_ascii_digit())
254        && v.chars().all(|c| c.is_ascii_digit() || matches!(c, '-' | ':' | 'T' | 't' | 'Z' | 'z' | '.' | '+' | ' '))
255        && (v.contains('-') || v.contains(':'))
256}
257
258#[cfg(test)]
259mod tests {
260    use super::check;
261
262    fn errors(s: &str) -> Vec<String> {
263        check(s).into_iter().filter(|f| f.error).map(|f| format!("{}:{} {}", f.line, f.column, f.message)).collect()
264    }
265
266    #[test]
267    fn valid_toml_has_no_findings() {
268        let ok = "# c\nport = 8080\nip = \"0.0.0.0\" # x\n[cors]\nallow_all = true\n\n[[route]]\npath = \"/api/*\"\nupstream = \"api\"\nheaders = { set = { \"x-a\" = \"b\" } }\nlist = [\n  \"a\",\n  \"b\", # c\n]\nwhen = 1979-05-27T07:32:00Z\ns = '''\nmulti\n'''\n[admin.\"quoted key\"]\nx = 1_000\n";
269        assert_eq!(check(ok), vec![]);
270    }
271
272    #[test]
273    fn unclosed_header_is_an_error_with_position() {
274        assert_eq!(errors("port = 1\n[[route]\npath = \"/\"\n"), vec!["2:9 table header [[route] is not closed: expected `]]`"]);
275        assert_eq!(errors("[admin\n").len(), 1);
276    }
277
278    #[test]
279    fn structural_mistakes_are_errors() {
280        assert!(errors("just words\n")[0].contains("expected `key = value`"));
281        assert!(errors("a = \"open\n")[0].contains("not closed"));
282        assert!(errors("a = [1, 2\n")[0].contains("not closed"));
283        assert!(errors("a = { b = 1 ]\n")[0].contains("unexpected `]`"));
284        assert!(errors("a =\n")[0].contains("no value"));
285        assert!(errors("a = \"x\" y\n")[0].contains("after the string"));
286    }
287
288    #[test]
289    fn bare_words_are_warnings() {
290        let f = check("ip = 0.0.0.0\nname = hello\n");
291        assert_eq!(f.len(), 1);
292        assert!(!f[0].error && f[0].message.contains("needs quotes"));
293    }
294}