返回 CodeWhale
project_config.rs
根目录 / crates / config / src / project_config.rs
1 use crate::config_store::{config_toml_error_location, parse_config_toml_str};
2 use crate::config_toml::ConfigToml;
3 use crate::external_credentials::quote_os_path;
4 use crate::path_io::read_checked_config_file;
5 use crate::provider_kind::ProviderKind;
6 use crate::provider_toml::CONFIG_FILE_NAME;
7 use anyhow::{Result, bail};
8 use codewhale_paths::{CODEWHALE_APP_DIR, LEGACY_APP_DIR};
9 use std::fs;
10 use std::path::{Path, PathBuf};
11
12 /// Values config.toml's root `approval_policy` accepts, compared trimmed and
13 /// case-insensitively. settings.toml's `approval_policy` also allows
14 /// `use-tui-default` and `full-access`.
15 pub const CONFIG_TOML_APPROVAL_POLICIES: &[&str] = &[
16 "on-request",
17 "untrusted",
18 "never",
19 "auto",
20 "auto-review",
21 "suggest",
22 "ask",
23 "accept-edits",
24 ];
25
26 /// Values config.toml's root `sandbox_mode` accepts.
27 pub const CONFIG_TOML_SANDBOX_MODES: &[&str] = &[
28 "read-only",
29 "workspace-write",
30 "danger-full-access",
31 "external-sandbox",
32 ];
33
34 /// Values config.toml's root `verbosity` accepts.
35 pub const CONFIG_TOML_VERBOSITIES: &[&str] = &["normal", "concise"];
36
37 /// The closed vocabulary of a config.toml root key, if it has one.
38 #[must_use]
39 pub fn config_toml_choices(key: &str) -> Option<&'static [&'static str]> {
40 match key {
41 "approval_policy" => Some(CONFIG_TOML_APPROVAL_POLICIES),
42 "sandbox_mode" => Some(CONFIG_TOML_SANDBOX_MODES),
43 "verbosity" => Some(CONFIG_TOML_VERBOSITIES),
44 _ => None,
45 }
46 }
47
48 /// Refuse a value the config.toml loader would reject for a closed-vocabulary
49 /// root key, so shared setters cannot write a file the TUI then fails to load.
50 pub fn check_config_toml_choice(key: &str, value: &str) -> Result<()> {
51 let Some(choices) = config_toml_choices(key) else {
52 return Ok(());
53 };
54 if choices.contains(&value.trim().to_ascii_lowercase().as_str()) {
55 return Ok(());
56 }
57 let settings_note = if key == "approval_policy" {
58 " (`use-tui-default` and `full-access` are settings.toml \
59 values for the /settings editor; config.toml does not read them.)"
60 } else {
61 ""
62 };
63 let value = codewhale_sanitize::redact::redact_secrets(value);
64 bail!(
65 "invalid value '{value}' for '{key}': config.toml accepts {}.{settings_note} \
66 No value was changed.\nfix: codewhale config set {key} {}",
67 choices.join(", "),
68 choices[0]
69 )
70 }
71
72 #[must_use]
73 pub fn project_approval_policy_is_allowed(current: Option<&str>, project: &str) -> bool {
74 let Some(project_rank) = approval_policy_rank(project) else {
75 return false;
76 };
77 match current.and_then(approval_policy_rank) {
78 Some(current_rank) => project_rank >= current_rank,
79 None => project_rank >= 3,
80 }
81 }
82
83 #[must_use]
84 pub fn project_sandbox_mode_is_allowed(current: Option<&str>, project: &str) -> bool {
85 let normalized_project = project.trim().to_ascii_lowercase();
86 if normalized_project == "external-sandbox" {
87 return current
88 .map(|value| value.trim().eq_ignore_ascii_case("external-sandbox"))
89 .unwrap_or(false);
90 }
91
92 let Some(project_rank) = sandbox_mode_rank(project) else {
93 return false;
94 };
95 match current.and_then(sandbox_mode_rank) {
96 Some(current_rank) => project_rank >= current_rank,
97 None => project_rank >= 2,
98 }
99 }
100
101 pub(crate) fn approval_policy_rank(value: &str) -> Option<u8> {
102 match value.trim().to_ascii_lowercase().as_str() {
103 "auto" | "auto-review" | "auto_review" => Some(0),
104 "accept-edits" | "accept_edits" | "acceptedits" | "edits" => Some(1),
105 "suggest" | "suggested" | "on-request" | "untrusted" | "ask" => Some(2),
106 "never" | "deny" | "denied" => Some(3),
107 _ => None,
108 }
109 }
110
111 pub(crate) fn sandbox_mode_rank(value: &str) -> Option<u8> {
112 match value.trim().to_ascii_lowercase().as_str() {
113 "danger-full-access" => Some(0),
114 "external-sandbox" => Some(0),
115 "workspace-write" => Some(1),
116 "read-only" => Some(2),
117 _ => None,
118 }
119 }
120
121 /// What [`load_project_config_outcome`] found in the workspace.
122 ///
123 /// The distinction between "no project config" and "a project config that is
124 /// broken" is security-relevant, so it is in the type rather than in a log
125 /// line. A project config can only *tighten* `approval_policy` /
126 /// `sandbox_mode` beyond the user's baseline; if a typo makes it unparseable
127 /// and that is reported as absence, the project silently loses its
128 /// restrictions and falls back to the user's more permissive baseline.
129 #[derive(Debug, Clone)]
130 pub enum ProjectConfigOutcome {
131 /// No project config file exists in this workspace.
132 Missing,
133 /// A project config was found and parsed.
134 Loaded(Box<ConfigToml>),
135 /// A project config file exists but could not be used. Its contents are
136 /// deliberately not included — a config file holds credentials.
137 Invalid {
138 /// The offending file.
139 path: PathBuf,
140 /// Why it could not be used, safe to display.
141 reason: String,
142 },
143 }
144
145 impl ProjectConfigOutcome {
146 /// The parsed config, discarding the reason a broken one was rejected.
147 #[must_use]
148 pub fn into_config(self) -> Option<ConfigToml> {
149 match self {
150 Self::Loaded(config) => Some(*config),
151 Self::Missing | Self::Invalid { .. } => None,
152 }
153 }
154
155 /// The path and reason when a project config exists but is unusable.
156 #[must_use]
157 pub fn invalid(&self) -> Option<(&Path, &str)> {
158 match self {
159 Self::Invalid { path, reason } => Some((path.as_path(), reason.as_str())),
160 Self::Missing | Self::Loaded(_) => None,
161 }
162 }
163 }
164
165 /// Load a project-level config from the workspace, reporting why a file that
166 /// exists could not be used.
167 ///
168 /// Checks `$WORKSPACE/.codewhale/config.toml` first, falling back to
169 /// `$WORKSPACE/.deepseek/config.toml` for backward compatibility.
170 pub fn load_project_config_outcome(workspace: &Path) -> ProjectConfigOutcome {
171 for dir in [CODEWHALE_APP_DIR, LEGACY_APP_DIR] {
172 let path = workspace.join(dir).join(CONFIG_FILE_NAME);
173 if !project_config_candidate_exists(&path) {
174 continue;
175 }
176 let raw = match read_checked_config_file(&path) {
177 Ok(raw) => raw,
178 Err(e) => {
179 tracing::warn!("Failed to read project config {}: {e:#}", path.display());
180 return ProjectConfigOutcome::Invalid {
181 path,
182 reason: format!("could not be read: {e}"),
183 };
184 }
185 };
186 match parse_config_toml_str(&raw) {
187 Ok(config) => {
188 let raw_provider = toml::from_str::<toml::Value>(&raw)
189 .ok()
190 .and_then(|document| document.get("provider").cloned())
191 .and_then(|provider| provider.as_str().map(str::to_string));
192 if config.provider == ProviderKind::Custom
193 && raw_provider.as_deref() != Some(ProviderKind::Custom.as_str())
194 {
195 // An unrecognized provider name deserializes to `Custom`
196 // rather than failing, so a typo would otherwise be
197 // accepted as a deliberate custom-provider selection.
198 tracing::warn!(
199 "Failed to parse project config {}; file contents were omitted",
200 quote_os_path(&path)
201 );
202 return ProjectConfigOutcome::Invalid {
203 path,
204 reason: match raw_provider {
205 // A key pasted into `provider =` must not be
206 // echoed; an ordinary typo stays readable.
207 Some(name) => format!(
208 "unknown provider '{}'",
209 codewhale_sanitize::redact::redact_secrets(&name)
210 ),
211 None => "unknown provider".to_string(),
212 },
213 };
214 }
215 return ProjectConfigOutcome::Loaded(Box::new(config));
216 }
217 Err(err) => {
218 tracing::warn!(
219 "Failed to parse project config {}; file contents were omitted",
220 quote_os_path(&path)
221 );
222 return ProjectConfigOutcome::Invalid {
223 path,
224 // Position only: `toml`'s message and snippet can quote
225 // the offending value, which may be a credential.
226 reason: format!("invalid TOML at {}", config_toml_error_location(&raw, &err)),
227 };
228 }
229 }
230 }
231 ProjectConfigOutcome::Missing
232 }
233
234 /// Load a project-level config from the workspace.
235 ///
236 /// Returns `None` both when no project config exists and when one exists but
237 /// is unusable. Callers that act on the *absence* of project restrictions —
238 /// anything deciding whether a project tightens `approval_policy` or
239 /// `sandbox_mode` — should use [`load_project_config_outcome`] instead, so a
240 /// broken file is not read as "this project asked for nothing."
241 pub fn load_project_config(workspace: &Path) -> Option<ConfigToml> {
242 load_project_config_outcome(workspace).into_config()
243 }
244
245 pub(crate) fn project_config_candidate_exists(path: &Path) -> bool {
246 fs::symlink_metadata(path).is_ok_and(|metadata| {
247 let file_type = metadata.file_type();
248 file_type.is_file() || file_type.is_symlink()
249 })
250 }
251
251 lines RUST