Skip to main content

eclipse_core/config/
check.rs

1//! Which keys a config file sets that this build does not read.
2//!
3//! Found while verifying M1: a misplaced `${VAR}` was reported as `web.api_key`, and the mistake was
4//! obvious only by accident — `api_key` under `[web]` had been ignored in silence. Nothing here is
5//! fatal, deliberately: a profile overlay or a plugin's provider profile may legitimately carry a
6//! key a given build does not know yet, so this is a report, not a parse error.
7//!
8//! The schema comes from the **loaded config serialised back to TOML**, not from a list written by
9//! hand. A key the file sets and no struct field holds is dropped by that round trip, so the
10//! difference between the two trees is exactly the set of keys nothing reads — and a field added
11//! later is known to this check the moment it exists, with no second place to update. The one blind
12//! spot is a field that serialises to nothing at all when unset (`skip_serializing_if`), which is
13//! what [`KNOWN_WHEN_EMPTY`] is for.
14
15use super::Config;
16use std::fmt;
17
18/// A key in a config file that no part of [`Config`] reads.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct UnknownKey {
21    /// Dotted table path, `""` at the top level, `provider.route` for an entry of
22    /// `[[provider.route]]`.
23    pub table: String,
24    /// Which entry of that array, when the key sits inside `[[…]]`.
25    pub row: Option<usize>,
26    /// The key as written.
27    pub key: String,
28    /// Where the same key *is* read, when it is read somewhere. This is the answer to a key under
29    /// the wrong table, which is the mistake that started this.
30    pub hint: Option<String>,
31}
32
33impl fmt::Display for UnknownKey {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match (&self.row, self.table.is_empty()) {
36            (Some(i), _) => write!(f, "[[{}]] entry {}, `{}`", self.table, i + 1, self.key),
37            (None, true) => write!(f, "top level, `{}`", self.key),
38            (None, false) => write!(f, "[{}], `{}`", self.table, self.key),
39        }
40    }
41}
42
43/// Fields that exist and are read, but serialise to nothing when unset, so the round trip cannot
44/// see them: `(table, key)`. Empty is not the same as absent, and a config that writes
45/// `fallback = []` is writing a real key.
46/// Keys that are read, but *disappear* from the loaded config when they hold an empty value.
47///
48/// Two reasons, one effect: `empty_is_none` turns `""` into `None` (a shipped config writes every
49/// secret, path and route as `""` or `"${VAR:-}"`, and an empty one means "not in use"), and the
50/// `Option` fields that a route or a hook owns are only visible when set. The comparison below is
51/// against the *loaded* config, so without this list the shipped file would report seven of its own
52/// keys as spellings nothing reads.
53///
54/// Adding a key here is a claim that an empty value means something; a key that is genuinely
55/// misspelled still shows up, because the spelling has to be one the struct holds.
56const KNOWN_WHEN_EMPTY: &[(&str, &str)] = &[
57    ("provider", "fallback"),
58    ("provider", "aux"),
59    ("provider", "delegate"),
60    ("provider", "route"),
61    ("provider", "api_key"),
62    ("provider", "api_key_env"),
63    ("provider", "profile"),
64    ("provider", "reasoning_effort"),
65    ("agent", "output_schema"),
66    ("web", "auth_token"),
67    ("web", "default_profile"),
68    ("update", "remote"),
69    ("update", "releases"),
70];
71
72/// The one table whose entries carry another table's whole surface.
73///
74/// [`RouteConfig`](crate::config::RouteConfig) is `#[serde(flatten)] ProviderConfig`, so every key
75/// `[provider]` reads is read on a route too — `apply_key_env` resolves `api_key` and
76/// `api_key_env` there with the same function, which is why a working key on a route used to be
77/// reported as a spelling nothing reads (`#496`).
78const ROUTE_TABLE: &str = "provider.route";
79/// What a route entry inherits from.
80const ROUTE_BASE_TABLE: &str = "provider";
81
82/// Whether `key` under `path` is a key that exists and is read but serialises to nothing when it
83/// holds an empty value, so the round trip below cannot see it.
84///
85/// A route entry answers to `[provider]`'s list as well as its own: the flatten is what makes the
86/// route's `api_key = ""` mean "not in use" rather than "a spelling nothing reads".
87fn known_when_empty(path: &str, key: &str) -> bool {
88    KNOWN_WHEN_EMPTY.contains(&(path, key))
89        || (path == ROUTE_TABLE && KNOWN_WHEN_EMPTY.contains(&(ROUTE_BASE_TABLE, key)))
90}
91
92impl Config {
93    /// Every key in `value` this build does not read, table by table as the parser hands them
94    /// over (sorted, not in the order the file wrote them — `toml::Table` is a map).
95    ///
96    /// `value` is one file as written — the base config, or a profile's overlay. `self` supplies the
97    /// shape, so pass the config that was actually loaded: a file that sets `model` is only known
98    /// to be right because the struct has the field.
99    pub fn unknown_keys(&self, value: &toml::Value) -> Vec<UnknownKey> {
100        let Ok(known) = toml::Value::try_from(self) else {
101            // A config that cannot be serialised cannot describe its own shape. Say nothing rather
102            // than report every key in the file as unknown.
103            return Vec::new();
104        };
105        let mut out = Vec::new();
106        walk(value, &known, "", None, &mut out);
107        // Hints come from a JSON round trip, not the TOML one: serde_json keeps a `None` field as
108        // `null` instead of dropping it, so `api_key` under `[provider]` is visible here even in a
109        // config that sets no key. TOML is still what decides the walk above, because it is the
110        // language the file is written in.
111        let hints = serde_json::to_value(self).ok().map(|json| {
112            let mut paths = Vec::new();
113            json_tables_with(&json, None, "", &mut paths);
114            paths
115        });
116        if let Some(paths) = hints {
117            for unknown in &mut out {
118                let mut found: Vec<&str> = paths
119                    .iter()
120                    .filter(|(key, table)| *key == unknown.key && **table != unknown.table)
121                    .map(|(_, table)| table.as_str())
122                    .collect();
123                // Several tables read this key (`model` is under `provider` and under every route):
124                // the shortest path is the one a user meant.
125                found.sort_by_key(|t| t.len());
126                unknown.hint = found.first().map(std::string::ToString::to_string);
127            }
128        }
129        out
130    }
131}
132
133fn walk(
134    file: &toml::Value,
135    known: &toml::Value,
136    path: &str,
137    row: Option<usize>,
138    out: &mut Vec<UnknownKey>,
139) {
140    match (file, known) {
141        (toml::Value::Table(from_file), toml::Value::Table(read)) => {
142            for (key, value) in from_file {
143                match read.get(key) {
144                    Some(known_value) => {
145                        let below = if path.is_empty() {
146                            key.to_string()
147                        } else {
148                            format!("{path}.{key}")
149                        };
150                        walk(value, known_value, &below, row, out);
151                    }
152                    None if known_when_empty(path, key.as_str()) => {}
153                    None => out.push(UnknownKey {
154                        table: path.to_string(),
155                        row,
156                        key: key.clone(),
157                        hint: None,
158                    }),
159                }
160            }
161        }
162        // `[[table]]` entries line up one for one: a key nobody reads is dropped from the entry it
163        // was written in, not from the array, so the indexes stay aligned.
164        (toml::Value::Array(from_file), toml::Value::Array(read))
165            if from_file.len() == read.len() =>
166        {
167            for (i, (a, b)) in from_file.iter().zip(read).enumerate() {
168                walk(a, b, path, Some(i), out);
169            }
170        }
171        _ => {}
172    }
173}
174
175/// `(key, table)` for every key the shapes declare, from the JSON round trip. `serde_json` keeps a
176/// `None` field as `null` rather than dropping it, which is the difference between this and the
177/// TOML walk.
178fn json_tables_with(
179    value: &serde_json::Value,
180    key_wanted: Option<&str>,
181    path: &str,
182    out: &mut Vec<(String, String)>,
183) {
184    match value {
185        serde_json::Value::Object(map) => {
186            for (k, v) in map {
187                let below = if path.is_empty() {
188                    k.clone()
189                } else {
190                    format!("{path}.{k}")
191                };
192                if key_wanted.is_none_or(|wanted| wanted == k) {
193                    out.push((k.clone(), path.to_string()));
194                }
195                json_tables_with(v, key_wanted, &below, out);
196            }
197        }
198        serde_json::Value::Array(items) => {
199            for v in items {
200                json_tables_with(v, key_wanted, path, out);
201            }
202        }
203        _ => {}
204    }
205}
206
207/// Read one config file and report the keys in it that `cfg` does not read.
208///
209/// The file is parsed as TOML and nothing more: a config whose types are wrong never gets here,
210/// because `cfg` had to load for the shape to exist, and that load would have failed first.
211pub fn unknown_keys_in_file(
212    path: &std::path::Path,
213    cfg: &Config,
214) -> super::Result<Vec<UnknownKey>> {
215    let text = std::fs::read_to_string(path).map_err(|e| super::Error::io(path, e))?;
216    let value: toml::Value = toml::from_str(&text).map_err(|message| super::Error::Parse {
217        path: path.to_path_buf(),
218        message: message.to_string(),
219    })?;
220    Ok(cfg.unknown_keys(&value))
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    fn keys(config: &str) -> Vec<String> {
228        let value: toml::Value = toml::from_str(config).unwrap();
229        let cfg: Config = value.clone().try_into().unwrap();
230        cfg.unknown_keys(&value)
231            .iter()
232            .map(std::string::ToString::to_string)
233            .collect()
234    }
235
236    #[test]
237    fn a_key_nothing_reads_is_named_with_the_table_it_sits_in() {
238        let found = keys("[tools]\nworkspace_root = \"/tmp\"\nbogus_setting = 5\n");
239        assert_eq!(found, ["[tools], `bogus_setting`"]);
240    }
241
242    #[test]
243    fn a_key_in_the_wrong_table_says_where_it_is_read() {
244        // The M1 accident: `api_key` belongs under `[provider]`, and under `[web]` it was silently
245        // ignored — which is how a config looks correct and sends no key.
246        let value: toml::Value =
247            toml::from_str("[provider]\nmodel = \"m\"\n[web]\napi_key = \"x\"\n").unwrap();
248        let cfg: Config = value.clone().try_into().unwrap();
249        let found = cfg.unknown_keys(&value);
250        assert_eq!(found.len(), 1, "{found:?}");
251        assert_eq!(found[0].key, "api_key");
252        assert_eq!(found[0].table, "web");
253        assert_eq!(found[0].hint.as_deref(), Some("provider"));
254    }
255
256    #[test]
257    fn a_nested_table_and_the_top_level_are_both_reported_by_path() {
258        // `[sessions]` has no `store` table, so the whole table is the unknown thing; a typo inside
259        // a table that does exist is named by its own path.
260        let found = keys("top_level_typo = 1\n[sessions]\nstore = { nope = 2 }\n");
261        assert_eq!(
262            found,
263            ["[sessions], `store`", "top level, `top_level_typo`"],
264            "{found:?}"
265        );
266    }
267
268    #[test]
269    fn a_type_that_does_not_match_is_left_to_the_parser() {
270        // `model` is a string; here it is a table. Serde reports that on load with the key and the
271        // type, so this check must not also claim the key is unknown.
272        let value: toml::Value = toml::from_str("[provider]\nmodel = { nope = 1 }\n").unwrap();
273        let cfg = Config::default();
274        assert!(cfg.unknown_keys(&value).is_empty());
275    }
276
277    #[test]
278    fn the_keys_that_serialise_to_nothing_when_unset_are_still_known() {
279        // `fallback`, `aux`, `delegate` and `route` are `skip_serializing_if`, so a round trip
280        // cannot see them. Writing them empty must not be called a typo.
281        for line in [
282            "fallback = []",
283            "aux = \"a\"",
284            "delegate = \"b\"",
285            "route = []",
286        ] {
287            let text = format!("[provider]\n{line}\n");
288            assert_eq!(keys(&text), [] as [String; 0], "{line}");
289        }
290    }
291
292    #[test]
293    fn a_route_entry_is_checked_without_losing_the_other_entries() {
294        let found = keys(
295            "[[provider.route]]\nname = \"a\"\nmodel = \"m\"\n\n\
296             [[provider.route]]\nname = \"b\"\nmodel = \"m\"\ntempo = 0.2\n",
297        );
298        assert_eq!(found, ["[[provider.route]] entry 2, `tempo`"]);
299    }
300
301    /// `#496`: a route is `#[serde(flatten)] ProviderConfig`, and `apply_key_env` resolves
302    /// `api_key`/`api_key_env` on every route with the function `[provider]` uses. A key whose
303    /// value is empty drops out of the loaded config, so the round trip cannot see it — the route
304    /// has to inherit the list of keys that still mean something when they hold nothing.
305    #[test]
306    fn a_route_entry_reads_the_keys_provider_reads_even_when_they_hold_nothing() {
307        for line in [
308            "api_key = \"\"",
309            "api_key_env = \"\"",
310            "profile = \"\"",
311            "reasoning_effort = \"\"",
312            "fallback = []",
313        ] {
314            let text = format!(
315                "[[provider.route]]\nname = \"a\"\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n{line}\n"
316            );
317            assert_eq!(keys(&text), [] as [String; 0], "{line}");
318        }
319    }
320
321    /// The half the report was actually about: a route that carries the key it needs. The literal
322    /// is deliberately not shaped like a vendor token, so nothing redacts the fixture.
323    #[test]
324    fn a_route_entry_with_a_key_and_one_with_a_named_variable_report_nothing() {
325        let found = keys(
326            "[[provider.route]]\nname = \"a\"\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
327             api_key = \"a-literal-key\"\n\n\
328             [[provider.route]]\nname = \"b\"\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
329             api_key_env = \"A_KEY\"\n",
330        );
331        assert_eq!(found, [] as [String; 0]);
332    }
333
334    /// The bug was a false finding, so the fix must not turn the check off: an inherited key
335    /// spelled wrong is still a key nothing reads.
336    #[test]
337    fn a_misspelled_inherited_key_on_a_route_is_still_reported() {
338        let found = keys(
339            "[[provider.route]]\nname = \"a\"\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
340             timeout_sec = 60\n",
341        );
342        assert_eq!(found, ["[[provider.route]] entry 1, `timeout_sec`"]);
343    }
344
345    #[test]
346    fn hooks_are_the_parsers_business_and_are_not_reported_here() {
347        // `[hooks.<name>]` is a `flatten` map whose keys are hook names, and `hooks::validate`
348        // already names the field that is wrong inside one.
349        let found = keys(
350            "[hooks]\norder = [\"pre_tool\"]\n\n[hooks.pre_tool]\ncommand = \"x\"\nwhat = 1\n",
351        );
352        assert_eq!(found, [] as [String; 0]);
353    }
354
355    #[test]
356    fn the_starter_config_is_clean() {
357        // The drift guard: every key the shipped starter file documents must be one this build
358        // reads, so a field renamed without the starter following it fails here.
359        let found = keys(&crate::config::starter_config().unwrap());
360        assert_eq!(found, [] as [String; 0]);
361    }
362
363    #[test]
364    fn the_shipped_profile_starter_is_clean_too() {
365        let found = keys(crate::config::STARTER_PROFILE_CONFIG);
366        assert_eq!(found, [] as [String; 0], "profile starter");
367    }
368}