返回 CodeWhale
config_store.rs
根目录 / crates / config / src / config_store.rs
1 use crate::config_backup::{merge_and_preserve_comments, note_legacy_root_file_migration};
2 use crate::config_document::replace_config_document_if_unchanged;
3 use crate::config_toml::ConfigToml;
4 use crate::external_credentials::quote_os_path;
5 use crate::path_io::{checked_path_exists, normalize_config_file_path, read_checked_config_file};
6 use crate::permissions::{
7 PermissionsToml, append_permission_rule, checked_permissions_path_for_config_path,
8 load_sibling_permissions, parse_generated_permissions, parse_permissions_document,
9 read_permissions_state, write_permissions_atomic,
10 };
11 use crate::state_dirs::resolve_config_path;
12 use crate::{catalog, config_document, legacy_root};
13 use anyhow::Context as _;
14 use anyhow::{Result, bail};
15 use codewhale_execpolicy::{ExecPolicyEngine, PermissionAction, ToolAskRule};
16 use std::path::{Path, PathBuf};
17
18 #[derive(Debug, Clone)]
19 pub struct ConfigStore {
20 pub(crate) path: PathBuf,
21 pub config: ConfigToml,
22 pub(crate) permissions: PermissionsToml,
23 /// Original file text, retained so [`save`](Self::save) can merge
24 /// comments back after serialisation.
25 pub(crate) original_raw: Option<String>,
26 /// What loading moved in memory from legacy top-level keys (#6394).
27 pub(crate) legacy_root: legacy_root::LegacyRootMigration,
28 }
29
30 /// Parse a [`ConfigToml`] on a dedicated thread with an explicit stack size.
31 ///
32 /// `ConfigToml` nests the per-provider tables, fleet trust policy, and every
33 /// typed sub-table in one struct, and the monomorphized toml/serde
34 /// deserializer frames for a struct this large overflow the 2 MiB default
35 /// stack of libtest and tokio worker threads in debug builds (the same
36 /// hazard the TUI fixed for its `ConfigFile`; reproduced as the #5585 stack
37 /// overflow through the guided-setup save path). Every production
38 /// `ConfigToml` parse goes through here so config-store loads stay safe
39 /// regardless of the calling thread's stack budget.
40 pub(crate) fn parse_config_toml_str(contents: &str) -> Result<ConfigToml, toml::de::Error> {
41 parse_config_toml_with_receipt(contents).map(|(config, _)| config)
42 }
43
44 /// [`parse_config_toml_str`] plus the receipt of the legacy top-level keys it
45 /// moved in memory (#6394).
46 pub(crate) fn parse_config_toml_with_receipt(
47 contents: &str,
48 ) -> Result<(ConfigToml, legacy_root::LegacyRootMigration), toml::de::Error> {
49 std::thread::scope(|scope| {
50 match std::thread::Builder::new()
51 .name("config-toml-parse".to_string())
52 .stack_size(16 * 1024 * 1024)
53 .spawn_scoped(scope, || parse_config_toml_canonical(contents))
54 {
55 Ok(handle) => handle
56 .join()
57 .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
58 // Spawning can only fail under resource exhaustion; parsing on
59 // the caller's stack is still the best remaining option.
60 Err(_) => parse_config_toml_canonical(contents),
61 }
62 })
63 }
64
65 pub(crate) fn parse_config_toml_canonical(
66 contents: &str,
67 ) -> Result<(ConfigToml, legacy_root::LegacyRootMigration), toml::de::Error> {
68 let (text, receipt) = legacy_root::canonicalize_text(contents)?;
69 let config = toml::from_str::<ConfigToml>(&text)?;
70 Ok((config, receipt))
71 }
72
73 /// Where a TOML error sits: `line L, column C` in `source` (the exact text
74 /// that was parsed), plus the key path when the deserializer recorded one.
75 ///
76 /// Never the error's message or source snippet: both can quote the offending
77 /// value (`invalid type: string "sk-…", expected a boolean`), and config and
78 /// permissions files hold credentials. Pass `None` for `source` when the
79 /// span refers to text the user did not write.
80 #[must_use]
81 pub fn toml_error_location(source: Option<&str>, err: &toml::de::Error) -> String {
82 let position = source.zip(err.span()).map(|(source, span)| {
83 let mut start = span.start.min(source.len());
84 while !source.is_char_boundary(start) {
85 start -= 1;
86 }
87 let before = &source[..start];
88 let line = before.matches('\n').count() + 1;
89 let column = before.rsplit('\n').next().unwrap_or("").chars().count() + 1;
90 format!("line {line}, column {column}")
91 });
92 // Without its input, `toml` renders exactly `{message}\n` followed by
93 // ``in `{keys}`\n`` when it recorded a key path; take only the latter.
94 let mut detached = err.clone();
95 detached.set_input(None);
96 let rendered = detached.to_string();
97 let key_path = rendered
98 .strip_prefix(err.message())
99 .and_then(|rest| rest.strip_prefix("\nin `"))
100 .and_then(|rest| rest.strip_suffix("`\n"))
101 .filter(|keys| !keys.is_empty())
102 .map(|keys| format!("in `{}`", codewhale_sanitize::redact::redact_secrets(keys)));
103 match (position, key_path) {
104 (Some(position), Some(keys)) => format!("{position}, {keys}"),
105 (Some(position), None) => position,
106 (None, Some(keys)) => keys,
107 (None, None) => "position unknown".to_string(),
108 }
109 }
110
111 /// [`toml_error_location`] for an error from [`parse_config_toml_with_receipt`].
112 /// A file with legacy top-level keys is parsed from a rewritten copy whose
113 /// offsets name nothing the user wrote, so only the key path is reported.
114 pub(crate) fn config_toml_error_location(raw: &str, err: &toml::de::Error) -> String {
115 let rewritten = matches!(
116 legacy_root::canonicalize_text(raw),
117 Ok((std::borrow::Cow::Owned(_), _))
118 );
119 toml_error_location((!rewritten).then_some(raw), err)
120 }
121
122 /// Parse any `config.toml`-shaped document into [`ConfigToml`], moving legacy
123 /// top-level `base_url` / `api_key` into their provider tables first. Every
124 /// caller outside this crate (bundle import, tests) parses through here so a
125 /// top-level key can never land in `extras`.
126 pub fn parse_config_toml(contents: &str) -> Result<ConfigToml, toml::de::Error> {
127 parse_config_toml_str(contents)
128 }
129
130 pub fn tool_launcher_in_profiles(document: &toml::Value) -> bool {
131 document
132 .get("profiles")
133 .and_then(toml::Value::as_table)
134 .is_some_and(|profiles| {
135 profiles
136 .values()
137 .any(|profile| profile.get("tool_launcher").is_some())
138 })
139 }
140
141 pub fn reject_unmanaged_tool_launcher(document: &toml::Value, path: &Path) -> Result<()> {
142 if document.get("tool_launcher").is_some() || tool_launcher_in_profiles(document) {
143 bail!(
144 "`tool_launcher` in {} is not accepted: it is read only from the managed configuration (CODEWHALE_MANAGED_CONFIG_PATH, or the default managed path), in a file the Engine cannot write",
145 quote_os_path(path)
146 );
147 }
148 Ok(())
149 }
150
151 impl ConfigStore {
152 /// The validated file snapshot captured by the last load or successful
153 /// save. This read-only view preserves literal provider identities that a
154 /// typed serialization may normalize; it excludes unsaved in-memory edits.
155 #[must_use]
156 pub fn original_body(&self) -> Option<&str> {
157 self.original_raw.as_deref()
158 }
159
160 pub fn load(path: Option<PathBuf>) -> Result<Self> {
161 let path = resolve_config_path(path)?;
162 let (config, original_raw, legacy_root) = if checked_path_exists(&path)? {
163 let raw = read_checked_config_file(&path)?;
164 let (mut parsed, receipt) = parse_config_toml_with_receipt(&raw).map_err(|err| {
165 anyhow::anyhow!(
166 "failed to parse config at {} ({}); file contents were omitted",
167 quote_os_path(&path),
168 config_toml_error_location(&raw, &err)
169 )
170 })?;
171 let raw_document: toml::Value = toml::from_str(&raw).map_err(|err| {
172 anyhow::anyhow!(
173 "failed to parse config at {} ({}); file contents were omitted",
174 quote_os_path(&path),
175 toml_error_location(Some(&raw), &err)
176 )
177 })?;
178 reject_unmanaged_tool_launcher(&raw_document, &path)?;
179 if let Some(provider_id) = raw_document.get("provider").and_then(toml::Value::as_str) {
180 parsed
181 .bind_persisted_provider_id(provider_id)
182 .with_context(|| {
183 format!("failed to parse config at {}", quote_os_path(&path))
184 })?;
185 }
186 (parsed, Some(raw), receipt)
187 } else {
188 (
189 ConfigToml::default(),
190 None,
191 legacy_root::LegacyRootMigration::default(),
192 )
193 };
194 let permissions = load_sibling_permissions(&path)?;
195
196 Ok(Self {
197 path,
198 config,
199 permissions,
200 original_raw,
201 legacy_root,
202 })
203 }
204
205 /// What loading moved in memory from legacy top-level keys. Loading never
206 /// rewrites the file; the next save does, keeping any conflict in place.
207 #[must_use]
208 pub fn legacy_root_migration(&self) -> &legacy_root::LegacyRootMigration {
209 &self.legacy_root
210 }
211
212 /// Render the exact body [`save`](Self::save) would write: the serialized
213 /// config with comments and disabled keys from the originally-loaded file
214 /// merged back in. Exposed so setup flows can stage this body into a
215 /// `persistence::SetupTransaction` alongside sibling files and keep the
216 /// comment-preserving write atomic with the rest of the transaction.
217 pub fn rendered_body(&self) -> Result<String> {
218 catalog::configured::validate_configured_models(
219 self.config.custom_models.as_deref().unwrap_or_default(),
220 )?;
221 let mut serialized =
222 toml::to_string_pretty(&self.config).context("failed to serialize config")?;
223 let provider_id = self.config.provider_id();
224 if provider_id != self.config.provider.as_str() {
225 let mut document = serialized
226 .parse::<toml_edit::DocumentMut>()
227 .context("failed to edit serialized config")?;
228 document["provider"] = toml_edit::value(provider_id);
229 serialized = document.to_string();
230 }
231 if let Some(ref original_raw) = self.original_raw {
232 // Comments come from the original with legacy top-level keys
233 // already moved (#6394): a comment above a moved key stays in
234 // place instead of vanishing with the key.
235 let decor_source = legacy_root::migrated_document_text(original_raw);
236 let merged = merge_and_preserve_comments(
237 &serialized,
238 decor_source.as_deref().unwrap_or(original_raw),
239 )
240 .with_context(|| {
241 format!(
242 "cannot safely preserve config at {}; reload it and retry instead of replacing an unmergeable snapshot",
243 quote_os_path(&self.path)
244 )
245 })?;
246 // The typed body has no top-level keys. A conflicting pair the
247 // user never touched goes back exactly as it was on disk.
248 let mut document = merged
249 .parse::<toml_edit::DocumentMut>()
250 .context("failed to edit serialized config")?;
251 if legacy_root::restore_conflicts(&mut document, original_raw) {
252 return Ok(document.to_string());
253 }
254 Ok(merged)
255 } else {
256 Ok(serialized)
257 }
258 }
259
260 pub fn save(&mut self) -> Result<()> {
261 let path = normalize_config_file_path(self.path.clone())?;
262 let body = self.rendered_body()?;
263 if let Some(original_raw) = self.original_raw.as_deref() {
264 note_legacy_root_file_migration(&path, original_raw)?;
265 }
266 replace_config_document_if_unchanged(&path, self.original_raw.as_deref(), &body)?;
267 self.original_raw = Some(body);
268 Ok(())
269 }
270
271 /// Refresh the typed value and byte snapshot after a targeted writer used
272 /// the shared config lock. This keeps a long-lived command process from
273 /// treating its own successful mutation as an external stale conflict.
274 pub fn reload(&mut self) -> Result<()> {
275 *self = Self::load(Some(self.path.clone()))?;
276 Ok(())
277 }
278
279 #[must_use]
280 pub fn path(&self) -> &Path {
281 &self.path
282 }
283
284 #[must_use]
285 pub fn permissions(&self) -> &PermissionsToml {
286 &self.permissions
287 }
288
289 #[must_use]
290 pub fn permissions_path(&self) -> PathBuf {
291 checked_permissions_path_for_config_path(&self.path)
292 .expect("ConfigStore path is validated before construction")
293 }
294
295 #[must_use]
296 pub fn exec_policy_engine(&self) -> ExecPolicyEngine {
297 if self.permissions.is_empty() {
298 ExecPolicyEngine::new(Vec::new(), Vec::new())
299 } else {
300 ExecPolicyEngine::with_rulesets(vec![self.permissions.ruleset()])
301 }
302 }
303
304 /// Atomically append ask-only permission rules to the sibling
305 /// `permissions.toml` file.
306 ///
307 /// Existing comments and formatting are preserved. Exact duplicate rules
308 /// are ignored, and the in-memory permissions snapshot is refreshed after
309 /// a successful write.
310 pub fn append_ask_rules(&mut self, rules: &[ToolAskRule]) -> Result<usize> {
311 self.append_permission_rules(rules, PermissionAction::Ask)
312 }
313
314 /// Atomically append exact, repo-scoped allow rules to the sibling
315 /// `permissions.toml` file.
316 ///
317 /// The caller is responsible for deciding which tool calls are eligible;
318 /// this boundary rejects broad or incorrectly typed records so a UI bug
319 /// cannot persist an unscoped allow grant.
320 pub fn append_allow_rules(&mut self, rules: &[ToolAskRule]) -> Result<usize> {
321 for rule in rules {
322 if rule.action != PermissionAction::Allow {
323 bail!("append_allow_rules only accepts action = \"allow\"");
324 }
325 let Some(workspace) = rule
326 .workspace
327 .as_deref()
328 .and_then(codewhale_execpolicy::normalize_workspace_scope)
329 else {
330 bail!("persistent allow rules must be scoped to a workspace");
331 };
332 if rule.command.is_some() && !rule.command_exact {
333 bail!("persistent command allow rules must use exact matching");
334 }
335 if rule.command.is_none() && rule.path.is_none() {
336 bail!("persistent allow rules must match an exact command or path");
337 }
338 if let Some(command) = rule.command.as_deref()
339 && command.trim().is_empty()
340 {
341 bail!("persistent command allow rules must not be empty");
342 }
343 if let Some(path) = rule.path.as_deref()
344 && codewhale_execpolicy::normalize_workspace_relative_path(path, &workspace)
345 .is_none_or(|path| path.is_empty())
346 {
347 bail!("persistent path allow rules must stay within the workspace");
348 }
349 }
350 self.append_permission_rules(rules, PermissionAction::Allow)
351 }
352
353 fn append_permission_rules(
354 &mut self,
355 rules: &[ToolAskRule],
356 expected_action: PermissionAction,
357 ) -> Result<usize> {
358 if rules.is_empty() {
359 return Ok(0);
360 }
361 if rules.iter().any(|rule| rule.action != expected_action) {
362 bail!(
363 "permission rule action does not match requested {:?} persistence",
364 expected_action
365 );
366 }
367
368 let path = checked_permissions_path_for_config_path(&self.path)?;
369 let (added, persisted) = config_document::with_config_write_lock(&path, |path| {
370 let (_, raw, mut permissions) = read_permissions_state(path)?;
371 let mut document = parse_permissions_document(path, &raw)?;
372
373 if !document.contains_key("rules") {
374 document["rules"] = toml_edit::Item::ArrayOfTables(toml_edit::ArrayOfTables::new());
375 }
376 let rules_item = document
377 .get_mut("rules")
378 .expect("rules entry was inserted above");
379
380 let mut added = 0;
381 for rule in rules {
382 if permissions.rules.contains(rule) {
383 continue;
384 }
385 append_permission_rule(rules_item, rule)?;
386 permissions.rules.push(rule.clone());
387 added += 1;
388 }
389 if added == 0 {
390 return Ok((0, permissions));
391 }
392
393 let body = document.to_string();
394 let persisted = parse_generated_permissions(path, &body)?;
395 write_permissions_atomic(path, body.as_bytes())?;
396 Ok((added, persisted))
397 })?;
398 self.permissions = persisted;
399 Ok(added)
400 }
401 }
402
402 lines RUST