返回 CodeWhale
permissions.rs
根目录 / crates / config / src / permissions.rs
1 use crate::config_backup::{checked_config_sibling_path, config_sibling_path_unchecked};
2 use crate::config_document;
3 use crate::config_store::toml_error_location;
4 use crate::external_credentials::quote_os_path;
5 use crate::path_io::{checked_path_exists, read_checked_permissions_file};
6 use crate::provider_toml::PERMISSIONS_FILE_NAME;
7 use crate::state_dirs::resolve_config_path;
8 use anyhow::Context as _;
9 use anyhow::{Result, bail};
10 use codewhale_execpolicy::{PermissionAction, Ruleset, ToolAskRule, unreachable_rule_warning};
11 use serde::{Deserialize, Serialize};
12 use sha2::{Digest as _, Sha256};
13 use std::ffi::OsStr;
14 use std::fs;
15 use std::io::Write;
16 use std::path::{Path, PathBuf};
17
18 /// Sibling `permissions.toml` schema.
19 ///
20 /// Each rule is a typed condition that can deny, allow, or ask before a tool
21 /// invocation. The approval card persists ask rules and narrowly scoped,
22 /// exact allow grants; deny rules remain manually authored.
23 #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
24 #[serde(deny_unknown_fields)]
25 pub struct PermissionsToml {
26 #[serde(default, skip_serializing_if = "Vec::is_empty")]
27 pub rules: Vec<ToolAskRule>,
28 }
29
30 /// On-disk state of the active sibling `permissions.toml`.
31 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
32 pub enum PermissionsFileState {
33 /// No sibling permission file exists.
34 Missing,
35 /// The sibling permission file exists but contains no TOML content.
36 Empty,
37 /// The sibling permission file contains a parsed TOML document.
38 Present,
39 }
40
41 #[derive(Debug, Clone, PartialEq, Eq)]
42 pub struct PermissionRuleWarning {
43 pub rule_index: usize,
44 pub tool: String,
45 pub message: String,
46 }
47
48 /// A parsed, read-only view of the active sibling `permissions.toml`.
49 ///
50 /// Removal tokens bind a displayed rule index to the exact file bytes that
51 /// produced this snapshot. A later editor must present the rule again when
52 /// another process changed the file instead of deleting whichever rule moved
53 /// into the old index.
54 #[derive(Debug, Clone, PartialEq, Eq)]
55 pub struct PermissionsSnapshot {
56 path: PathBuf,
57 file_state: PermissionsFileState,
58 permissions: PermissionsToml,
59 removal_tokens: Vec<String>,
60 warnings: Vec<PermissionRuleWarning>,
61 }
62
63 impl PermissionsSnapshot {
64 #[must_use]
65 pub fn path(&self) -> &Path {
66 &self.path
67 }
68
69 #[must_use]
70 pub fn file_exists(&self) -> bool {
71 self.file_state != PermissionsFileState::Missing
72 }
73
74 #[must_use]
75 pub fn file_state(&self) -> PermissionsFileState {
76 self.file_state
77 }
78
79 #[must_use]
80 pub fn permissions(&self) -> &PermissionsToml {
81 &self.permissions
82 }
83
84 #[must_use]
85 pub fn rules(&self) -> &[ToolAskRule] {
86 &self.permissions.rules
87 }
88
89 #[must_use]
90 pub fn warnings(&self) -> &[PermissionRuleWarning] {
91 &self.warnings
92 }
93
94 #[must_use]
95 pub fn rule_warning(&self, index: usize) -> Option<&str> {
96 self.warnings
97 .iter()
98 .find(|warning| warning.rule_index == index)
99 .map(|warning| warning.message.as_str())
100 }
101
102 /// Return the opaque confirmation token for a zero-based rule index.
103 #[must_use]
104 pub fn removal_token(&self, index: usize) -> Option<&str> {
105 self.removal_tokens.get(index).map(String::as_str)
106 }
107 }
108
109 impl PermissionsToml {
110 #[must_use]
111 pub fn is_empty(&self) -> bool {
112 self.rules.is_empty()
113 }
114
115 #[must_use]
116 pub fn ruleset(&self) -> Ruleset {
117 let mut denied = Vec::new();
118 let mut trusted = Vec::new();
119 let mut ask_rules = Vec::new();
120
121 for rule in &self.rules {
122 match rule.action {
123 PermissionAction::Deny => {
124 // Command-based deny rules are promoted to denied_prefixes
125 // so they are caught by execpolicy's deny-always-wins check.
126 if let Some(cmd) = &rule.command
127 && !rule.command_exact
128 && rule.workspace.is_none()
129 {
130 denied.push(cmd.clone());
131 }
132 // Always keep in ask_rules for path-based and tool-only matching.
133 ask_rules.push(rule.clone());
134 }
135 PermissionAction::Allow => {
136 // Command-based allow rules are promoted to trusted_prefixes
137 // for arity-aware matching. Path-only allow rules are
138 // handled through ask_rules (they skip the approval prompt).
139 if let Some(cmd) = &rule.command
140 && !rule.command_exact
141 && rule.workspace.is_none()
142 {
143 trusted.push(cmd.clone());
144 }
145 // Keep in ask_rules so path-only allow rules also work.
146 ask_rules.push(rule.clone());
147 }
148 PermissionAction::Ask => {
149 ask_rules.push(rule.clone());
150 }
151 }
152 }
153
154 Ruleset::user(trusted, denied).with_ask_rules(ask_rules)
155 }
156 }
157
158 #[must_use]
159 pub fn permissions_path_for_config_path(config_path: &Path) -> PathBuf {
160 config_sibling_path_unchecked(config_path, OsStr::new(PERMISSIONS_FILE_NAME))
161 }
162
163 pub(crate) fn checked_permissions_path_for_config_path(config_path: &Path) -> Result<PathBuf> {
164 checked_config_sibling_path(config_path, OsStr::new(PERMISSIONS_FILE_NAME))
165 }
166
167 pub fn resolve_permissions_path(config_path: Option<PathBuf>) -> Result<PathBuf> {
168 checked_permissions_path_for_config_path(&resolve_config_path(config_path)?)
169 }
170
171 fn collect_unreachable_rule_warnings(
172 path: &Path,
173 rules: &[ToolAskRule],
174 ) -> Vec<PermissionRuleWarning> {
175 let mut warnings = Vec::new();
176 for (index, rule) in rules.iter().enumerate() {
177 if let Some(message) = unreachable_rule_warning(rule) {
178 tracing::warn!(
179 target: "codewhale::config::permissions",
180 path = %path.display(),
181 rule_index = index + 1,
182 tool = %rule.tool,
183 warning = %message,
184 "unreachable permissions.toml rule"
185 );
186 warnings.push(PermissionRuleWarning {
187 rule_index: index,
188 tool: rule.tool.clone(),
189 message,
190 });
191 }
192 }
193 warnings
194 }
195
196 /// Load the active sibling permission rules with confirmation tokens suitable
197 /// for a later compare-and-remove operation.
198 pub fn load_permissions_snapshot(config_path: Option<PathBuf>) -> Result<PermissionsSnapshot> {
199 let path = resolve_permissions_path(config_path)?;
200 let (file_exists, raw, permissions) = read_permissions_state(&path)?;
201 let file_state = if !file_exists {
202 PermissionsFileState::Missing
203 } else if raw.is_empty() {
204 PermissionsFileState::Empty
205 } else {
206 PermissionsFileState::Present
207 };
208 let removal_tokens = (0..permissions.rules.len())
209 .map(|index| permission_removal_token(&path, &raw, index))
210 .collect();
211 let warnings = collect_unreachable_rule_warnings(&path, &permissions.rules);
212 Ok(PermissionsSnapshot {
213 path,
214 file_state,
215 permissions,
216 removal_tokens,
217 warnings,
218 })
219 }
220
221 #[derive(Debug, Clone, PartialEq, Eq)]
222 pub struct StalePermissionSnapshot {
223 detail: String,
224 }
225
226 impl std::fmt::Display for StalePermissionSnapshot {
227 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 formatter.write_str(&self.detail)
229 }
230 }
231
232 impl std::error::Error for StalePermissionSnapshot {}
233
234 /// Remove one zero-based permission rule if `expected_token` still describes
235 /// that exact index in the current file.
236 ///
237 /// The file is re-read only after acquiring the same adjacent lock used by
238 /// append operations. This makes the token check and atomic replacement one
239 /// transaction, preventing stale list views from deleting a different rule.
240 pub fn remove_permission_rule(
241 config_path: Option<PathBuf>,
242 index: usize,
243 expected_token: &str,
244 ) -> Result<ToolAskRule> {
245 let path = resolve_permissions_path(config_path)?;
246 config_document::with_config_write_lock(&path, |path| {
247 let (file_exists, raw, permissions) = read_permissions_state(path)?;
248 if !file_exists {
249 return Err(anyhow::Error::new(StalePermissionSnapshot {
250 detail: format!(
251 "permissions changed after they were listed; reload {} and retry",
252 quote_os_path(path)
253 ),
254 }));
255 }
256 let rule = permissions.rules.get(index).cloned().ok_or_else(|| {
257 anyhow::Error::new(StalePermissionSnapshot {
258 detail: format!(
259 "permission rule {} no longer exists in {}; list rules again",
260 index + 1,
261 quote_os_path(path)
262 ),
263 })
264 })?;
265 let current_token = permission_removal_token(path, &raw, index);
266 if current_token != expected_token {
267 return Err(anyhow::Error::new(StalePermissionSnapshot {
268 detail: format!(
269 "permissions changed after they were listed; reload {} and retry",
270 quote_os_path(path)
271 ),
272 }));
273 }
274
275 let mut document = parse_permissions_document(path, &raw)?;
276 let rules_item = document.get_mut("rules").with_context(|| {
277 format!(
278 "permissions at {} no longer contain a rules array",
279 quote_os_path(path)
280 )
281 })?;
282 let orphaned_header = remove_permission_rule_item(rules_item, index)?;
283 if let Some(header) = orphaned_header {
284 let trailing = format!(
285 "{header}{}",
286 document.trailing().as_str().unwrap_or_default()
287 );
288 document.set_trailing(trailing);
289 }
290 let body = document.to_string();
291 let persisted = parse_generated_permissions(path, &body)?;
292 if persisted.rules.len() + 1 != permissions.rules.len() {
293 bail!(
294 "refusing inconsistent permission removal at {}",
295 quote_os_path(path)
296 );
297 }
298 write_permissions_atomic(path, body.as_bytes())?;
299 Ok(rule)
300 })
301 }
302
303 pub(crate) fn load_sibling_permissions(config_path: &Path) -> Result<PermissionsToml> {
304 let permissions_path = checked_permissions_path_for_config_path(config_path)?;
305 let (_, _, permissions) = read_permissions_state(&permissions_path)?;
306 let _ = collect_unreachable_rule_warnings(&permissions_path, &permissions.rules);
307 Ok(permissions)
308 }
309
310 pub(crate) fn read_permissions_state(path: &Path) -> Result<(bool, String, PermissionsToml)> {
311 let file_exists = checked_path_exists(path)?;
312 let raw = if file_exists {
313 read_checked_permissions_file(path)?
314 } else {
315 String::new()
316 };
317 let permissions = if raw.trim().is_empty() {
318 PermissionsToml::default()
319 } else {
320 toml::from_str(&raw).map_err(|err| {
321 anyhow::anyhow!(
322 "failed to parse permissions at {} ({}); file contents were omitted",
323 quote_os_path(path),
324 toml_error_location(Some(&raw), &err)
325 )
326 })?
327 };
328 Ok((file_exists, raw, permissions))
329 }
330
331 pub(crate) fn parse_permissions_document(path: &Path, raw: &str) -> Result<toml_edit::DocumentMut> {
332 if raw.trim().is_empty() {
333 Ok(toml_edit::DocumentMut::new())
334 } else {
335 raw.parse::<toml_edit::DocumentMut>().map_err(|_| {
336 anyhow::anyhow!(
337 "failed to edit permissions at {}; file contents were omitted",
338 quote_os_path(path)
339 )
340 })
341 }
342 }
343
344 pub(crate) fn parse_generated_permissions(path: &Path, body: &str) -> Result<PermissionsToml> {
345 toml::from_str(body).map_err(|_| {
346 anyhow::anyhow!(
347 "generated invalid permissions document for {}; file contents were omitted",
348 quote_os_path(path)
349 )
350 })
351 }
352
353 pub(crate) fn permission_removal_token(path: &Path, raw: &str, index: usize) -> String {
354 let mut hasher = Sha256::new();
355 hasher.update(b"codewhale-permission-removal-v1\0");
356 hasher.update(quote_os_path(path).as_bytes());
357 hasher.update(b"\0");
358 hasher.update(index.to_le_bytes());
359 hasher.update(b"\0");
360 hasher.update(raw.as_bytes());
361 let digest = hasher.finalize();
362 let mut token = String::with_capacity(24);
363 for byte in &digest[..12] {
364 use std::fmt::Write as _;
365 let _ = write!(&mut token, "{byte:02x}");
366 }
367 token
368 }
369
370 pub(crate) fn append_permission_rule(item: &mut toml_edit::Item, rule: &ToolAskRule) -> Result<()> {
371 match item {
372 toml_edit::Item::ArrayOfTables(rules) => {
373 rules.push(permission_rule_table(rule));
374 Ok(())
375 }
376 toml_edit::Item::Value(value) => {
377 let Some(rules) = value.as_array_mut() else {
378 bail!("`rules` in permissions.toml must be an array");
379 };
380 rules.push(toml_edit::Value::InlineTable(permission_rule_inline_table(
381 rule,
382 )));
383 Ok(())
384 }
385 _ => bail!("`rules` in permissions.toml must be an array"),
386 }
387 }
388
389 pub(crate) fn remove_permission_rule_item(
390 item: &mut toml_edit::Item,
391 index: usize,
392 ) -> Result<Option<String>> {
393 match item {
394 toml_edit::Item::ArrayOfTables(rules) => {
395 if index >= rules.len() {
396 bail!("permission rule index changed before removal");
397 }
398 let file_header = if index == 0 {
399 rules
400 .get(index)
401 .and_then(|rule| rule.decor().prefix())
402 .and_then(toml_edit::RawString::as_str)
403 .map(str::to_owned)
404 } else {
405 None
406 };
407 rules.remove(index);
408 if let Some(header) = file_header.as_deref()
409 && let Some(next_rule) = rules.get_mut(0)
410 {
411 let next_prefix = next_rule
412 .decor()
413 .prefix()
414 .and_then(toml_edit::RawString::as_str)
415 .unwrap_or_default()
416 .to_owned();
417 next_rule
418 .decor_mut()
419 .set_prefix(format!("{header}{next_prefix}"));
420 return Ok(None);
421 }
422 Ok(file_header)
423 }
424 toml_edit::Item::Value(value) => {
425 let Some(rules) = value.as_array_mut() else {
426 bail!("`rules` in permissions.toml must be an array");
427 };
428 if index >= rules.len() {
429 bail!("permission rule index changed before removal");
430 }
431 rules.remove(index);
432 Ok(None)
433 }
434 _ => bail!("`rules` in permissions.toml must be an array"),
435 }
436 }
437
438 pub(crate) fn permission_rule_table(rule: &ToolAskRule) -> toml_edit::Table {
439 let mut table = toml_edit::Table::new();
440 table["tool"] = toml_edit::value(rule.tool.clone());
441 if let Some(command) = rule.command.as_deref() {
442 table["command"] = toml_edit::value(command);
443 }
444 if rule.command_exact {
445 table["command_exact"] = toml_edit::value(true);
446 }
447 if let Some(path) = rule.path.as_deref() {
448 table["path"] = toml_edit::value(path);
449 }
450 if let Some(workspace) = rule.workspace.as_deref() {
451 table["workspace"] = toml_edit::value(workspace);
452 }
453 if rule.action != PermissionAction::Ask {
454 table["action"] = toml_edit::value(match rule.action {
455 PermissionAction::Allow => "allow",
456 PermissionAction::Ask => "ask",
457 PermissionAction::Deny => "deny",
458 });
459 }
460 table
461 }
462
463 pub(crate) fn permission_rule_inline_table(rule: &ToolAskRule) -> toml_edit::InlineTable {
464 let mut table = toml_edit::InlineTable::new();
465 table.insert("tool", toml_edit::Value::from(rule.tool.clone()));
466 if let Some(command) = rule.command.as_deref() {
467 table.insert("command", toml_edit::Value::from(command));
468 }
469 if rule.command_exact {
470 table.insert("command_exact", toml_edit::Value::from(true));
471 }
472 if let Some(path) = rule.path.as_deref() {
473 table.insert("path", toml_edit::Value::from(path));
474 }
475 if let Some(workspace) = rule.workspace.as_deref() {
476 table.insert("workspace", toml_edit::Value::from(workspace));
477 }
478 if rule.action != PermissionAction::Ask {
479 table.insert(
480 "action",
481 toml_edit::Value::from(match rule.action {
482 PermissionAction::Allow => "allow",
483 PermissionAction::Ask => "ask",
484 PermissionAction::Deny => "deny",
485 }),
486 );
487 }
488 table
489 }
490
491 pub(crate) fn write_permissions_atomic(path: &Path, body: &[u8]) -> Result<()> {
492 write_permissions_atomic_with_dir_sync(path, body, crate::persistence::sync_parent_dir)
493 }
494
495 fn write_permissions_atomic_with_dir_sync(
496 path: &Path,
497 body: &[u8],
498 sync_dir: impl FnOnce(&Path) -> Result<()>,
499 ) -> Result<()> {
500 let parent = path.parent().with_context(|| {
501 format!(
502 "permissions path has no parent directory: {}",
503 path.display()
504 )
505 })?;
506 fs::create_dir_all(parent).with_context(|| {
507 format!(
508 "failed to create permissions directory {}",
509 parent.display()
510 )
511 })?;
512
513 let mut temporary = tempfile::NamedTempFile::new_in(parent).with_context(|| {
514 format!(
515 "failed to create temporary permissions file in {}",
516 parent.display()
517 )
518 })?;
519 // A filesystem that assigns modes itself (HarmonyOS hmdfs) refuses the
520 // call; `tighten_mode` tolerates only that case and reports every other
521 // failure, so a permissions file that really is world-readable still
522 // fails here.
523 #[cfg(unix)]
524 crate::private_directory::tighten_mode_of(temporary.as_file(), temporary.path(), 0o600)
525 .with_context(|| {
526 format!(
527 "failed to secure temporary permissions file for {}",
528 path.display()
529 )
530 })?;
531 temporary
532 .write_all(body)
533 .with_context(|| format!("failed to write permissions at {}", path.display()))?;
534 temporary
535 .as_file()
536 .sync_all()
537 .with_context(|| format!("failed to sync permissions at {}", path.display()))?;
538 temporary
539 .persist(path)
540 .map_err(|error| error.error)
541 .with_context(|| format!("failed to replace permissions at {}", path.display()))?;
542 let sync_target = if parent.as_os_str().is_empty() {
543 Path::new(".")
544 } else {
545 parent
546 };
547 crate::persistence::sync_parent_dir_best_effort(sync_target, sync_dir);
548 Ok(())
549 }
550
551 #[cfg(test)]
552 mod tests {
553 use super::*;
554
555 #[test]
556 fn write_permissions_atomic_syncs_parent_directory_without_failing_persisted_save() {
557 let tmp = tempfile::tempdir().expect("tempdir");
558 let path = tmp.path().join("permissions.toml");
559 let mut synced = None;
560 write_permissions_atomic_with_dir_sync(&path, b"rules = []\n", |dir| {
561 synced = Some(dir.to_path_buf());
562 Ok(())
563 })
564 .expect("write should succeed when parent sync succeeds");
565 assert_eq!(synced.as_deref(), Some(tmp.path()));
566
567 write_permissions_atomic_with_dir_sync(&path, b"rules = [\"allow\"]\n", |_| {
568 anyhow::bail!("injected directory sync failure")
569 })
570 .expect("best-effort parent directory sync must not fail an already-persisted write");
571 assert_eq!(
572 std::fs::read_to_string(&path).expect("read permissions"),
573 "rules = [\"allow\"]\n"
574 );
575 }
576
577 #[test]
578 fn load_permissions_snapshot_attaches_warnings_only_for_unreachable_rules() {
579 let tmp = tempfile::tempdir().expect("tempdir");
580 let config_path = tmp.path().join("config.toml");
581 let permissions_path = tmp.path().join("permissions.toml");
582 fs::write(
583 &permissions_path,
584 concat!(
585 "[[rules]]\n",
586 "tool = \"write\"\n",
587 "path = \"src/lib.rs\"\n",
588 "action = \"deny\"\n\n",
589 "[[rules]]\n",
590 "tool = \"bash\"\n",
591 "path = \"src/lib.rs\"\n",
592 "action = \"deny\"\n\n",
593 "[[rules]]\n",
594 "tool = \"*\"\n",
595 "action = \"deny\"\n\n",
596 "[[rules]]\n",
597 "tool = \"write_file\"\n",
598 "path = \"src/lib.rs\"\n",
599 "action = \"deny\"\n\n",
600 "[[rules]]\n",
601 "tool = \"bash\"\n",
602 "command = \"cargo test\"\n",
603 "action = \"allow\"\n\n",
604 "[[rules]]\n",
605 "tool = \"*\"\n",
606 "action = \"allow\"\n",
607 ),
608 )
609 .expect("write permissions");
610
611 let snapshot = load_permissions_snapshot(Some(config_path)).expect("load snapshot");
612 assert_eq!(snapshot.rules().len(), 6);
613 assert_eq!(snapshot.rules()[0].tool, "write");
614 assert_eq!(snapshot.warnings().len(), 3);
615 assert!(
616 snapshot
617 .rule_warning(0)
618 .expect("write rule warning")
619 .contains("write_file")
620 );
621 assert!(
622 snapshot
623 .rule_warning(1)
624 .expect("bash+path rule warning")
625 .contains("bash")
626 );
627 assert!(
628 snapshot
629 .rule_warning(2)
630 .expect("wildcard deny warning")
631 .contains("tool = \"*\"")
632 );
633 assert_eq!(snapshot.rule_warning(3), None);
634 assert_eq!(snapshot.rule_warning(4), None);
635 assert_eq!(snapshot.rule_warning(5), None);
636 }
637 }
638
638 lines RUST