From cc9b0cbdc431120bec3722c12526aa645937916c Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:40:22 -0600 Subject: [PATCH] permissions: a project settings file incode cannot use fails closed and says why MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found while running issue #19's steps with a real model: its .incode/settings.json was {"deny":["Write(secret.txt)"]}, a top-level `deny` incode does not read (rules go under "permissions"). The file parsed, the key was ignored, the rule was simply not there, and the Write it was written to stop ran: secret.txt was written. The only trace was a warning shown by /permissions, never on a -t run. Now read_project refuses a file with a key incode does not read, at the top level or inside `permissions` (a typo such as `denny`), as well as bad JSON or a non-object; and load() fails closed on any such file, as it already did for a broken managed file: every tool call is refused by a project-layer catch-all whose text carries the reason and the right shape, so the refusal the agent relays says what to fix. Measured live with the same file after the fix: `NOT RUN — Write is refused by the deny rule `*: .incode/settings.json has `deny` at the top level, which incode does not read (rules go under `permissions`: ...)``, and no secret.txt. Test: each unusable shape refuses Write, Read and Bash with that reason; the right shape denies only what it lists. Full suite: 2437 lib + 59 bin pass. --- src/permissions/rules/set.rs | 82 +++++++++++++++++++++++---- src/permissions/rules/tests/layers.rs | 68 ++++++++++++++++++++++ 2 files changed, 139 insertions(+), 11 deletions(-) diff --git a/src/permissions/rules/set.rs b/src/permissions/rules/set.rs index 4cb4a7c..8cdb972 100644 --- a/src/permissions/rules/set.rs +++ b/src/permissions/rules/set.rs @@ -3,8 +3,6 @@ use std::path::Path; -use serde::Deserialize; - use super::rule::{Rule, Spec}; use super::split::{split_command, Segment}; use super::{Effect, Layer, PathContext, RuleLists, Subject, Verdict, PROJECT_SETTINGS}; @@ -58,7 +56,7 @@ impl PermissionRules { match read_project(workspace) { Ok(Some(lists)) => rules.add(&lists, Layer::Project, home.as_deref()), Ok(None) => {} - Err(why) => rules.warnings.push(why), + Err(why) => rules.refuse_for_project(&why), } rules } @@ -111,6 +109,28 @@ impl PermissionRules { } } + /// The project's settings file is there and cannot be used: fail closed, + /// as for a broken managed file. A deny rule in a file incode cannot read + /// (a top-level `"deny"` instead of `"permissions": {"deny": ...}`, a typo, + /// bad JSON) was silently dropped before, and the call it was written to + /// stop ran (measured: issue #19's own steps wrote `secret.txt`). The + /// reason travels in the catch-all's text, so the refusal every call gets + /// says what to fix, on a `-t` run too, not only under `/permissions`. + /// + /// Called by [`PermissionRules::load`] when `read_project` fails. + fn refuse_for_project(&mut self, why: &str) { + let warning = + format!("{why}; every tool call is refused until {PROJECT_SETTINGS} is fixed"); + if let Ok(mut rule) = Rule::parse("*", None) { + rule.text = format!("*: {warning}"); + self.deny.push(Sourced { + rule, + layer: Layer::Project, + }); + } + self.warnings.push(warning); + } + #[must_use] pub fn is_empty(&self) -> bool { self.deny.is_empty() && self.ask.is_empty() && self.allow.is_empty() @@ -311,12 +331,14 @@ fn host_matches(url: &str, domain: &str) -> bool { /// The project's lists, from [`PROJECT_SETTINGS`]. `None` when there is no /// file, or no `permissions` in it. +/// +/// # Errors +/// When the file cannot be read, is not JSON, or holds a key incode does not +/// know, at the top or inside `permissions`: such a key is most often a rule +/// list in the wrong place (`{"deny": [...]}`), and ignoring it would drop the +/// rule while the run goes on ([`PermissionRules::refuse_for_project`]). fn read_project(workspace: &Path) -> Result, String> { - #[derive(Deserialize)] - struct ProjectSettings { - #[serde(default)] - permissions: Option, - } + const RIGHT_SHAPE: &str = r#"{"permissions": {"deny": [...], "ask": [...]}}"#; let path = workspace.join(PROJECT_SETTINGS); let text = match crate::text::read_authored(&path) { Ok(text) => text, @@ -326,7 +348,45 @@ fn read_project(workspace: &Path) -> Result, String> { if text.trim().is_empty() { return Ok(None); } - serde_json::from_str::(&text) - .map(|s| s.permissions) - .map_err(|e| format!("{} is not valid settings: {e}", path.display())) + let value: serde_json::Value = serde_json::from_str(&text) + .map_err(|e| format!("{} is not valid JSON: {e}", path.display()))?; + let unknown = |object: &serde_json::Map, known: &[&str]| { + object + .keys() + .filter(|k| !known.contains(&k.as_str())) + .map(|k| format!("`{k}`")) + .collect::>() + }; + let Some(top) = value.as_object() else { + return Err(format!( + "{} must be a JSON object such as {RIGHT_SHAPE}", + path.display() + )); + }; + let stray = unknown(top, &["permissions"]); + if !stray.is_empty() { + return Err(format!( + "{} has {} at the top level, which incode does not read (rules go under \ + `permissions`: {RIGHT_SHAPE})", + path.display(), + stray.join(", ") + )); + } + let Some(permissions) = top.get("permissions") else { + return Ok(None); + }; + if let Some(lists) = permissions.as_object() { + let stray = unknown(lists, &["deny", "ask", "allow"]); + if !stray.is_empty() { + return Err(format!( + "{}: `permissions` has {}, which incode does not read (it reads `deny`, `ask` \ + and `allow`)", + path.display(), + stray.join(", ") + )); + } + } + serde_json::from_value::(permissions.clone()) + .map(Some) + .map_err(|e| format!("{}: `permissions` is not valid: {e}", path.display())) } diff --git a/src/permissions/rules/tests/layers.rs b/src/permissions/rules/tests/layers.rs index f9c249e..f46e340 100644 --- a/src/permissions/rules/tests/layers.rs +++ b/src/permissions/rules/tests/layers.rs @@ -117,6 +117,74 @@ fn project_settings_with_a_byte_order_mark_still_deny() { ); } +/// **A PROJECT SETTINGS FILE INCODE CANNOT USE REFUSES EVERY CALL, AND SAYS +/// WHY.** Issue #19's own steps wrote `{"deny":["Write(secret.txt)"]}`: a +/// top-level `deny` incode does not read. It was dropped without a word, and +/// the Write it was meant to stop ran (measured on a real `-t` run). Now that +/// file, a typo inside `permissions`, and bad JSON each fail closed, the +/// refusal naming the file and the fix. Control: the right shape denies only +/// what it lists. +#[test] +fn a_project_settings_file_incode_cannot_use_refuses_every_call_and_says_why() { + let ws_for = |dir: &tempfile::TempDir| PathContext { + workspace: dir.path().to_path_buf(), + home: None, + }; + let write = |path: &str| Subject::Paths(vec![path.to_string()]); + for (text, says) in [ + ( + r#"{"deny":["Write(secret.txt)"]}"#, + "`deny` at the top level", + ), + ( + r#"{"permissions": {"denny": ["Write(secret.txt)"]}}"#, + "`permissions` has `denny`", + ), + ( + r#"{"permissions": {"deny": ["Write(secret.txt)"]"#, + "not valid JSON", + ), + (r#"["Write(secret.txt)"]"#, "must be a JSON object"), + ] { + let dir = tempfile::tempdir().expect("dir"); + std::fs::create_dir_all(dir.path().join(".incode")).expect("mkdir"); + std::fs::write(dir.path().join(PROJECT_SETTINGS), text).expect("write"); + let rules = PermissionRules::load(dir.path()); + let ws = ws_for(&dir); + for (tool, subject) in [ + ("Write", write("secret.txt")), + ("Read", write("other.txt")), + ("Bash", Subject::Command("ls".to_string())), + ] { + let verdict = rules.decide(tool, &subject, &ws).expect("decided"); + assert_eq!(verdict.effect, Effect::Deny, "{text}: {tool}"); + assert_eq!(verdict.layer, Layer::Project, "{text}"); + let said = verdict.describe(); + assert!(said.contains(says), "{text}: {said}"); + assert!(said.contains(PROJECT_SETTINGS), "{text}: {said}"); + } + assert_eq!(rules.warnings().len(), 1, "{:?}", rules.warnings()); + } + + let dir = tempfile::tempdir().expect("dir"); + std::fs::create_dir_all(dir.path().join(".incode")).expect("mkdir"); + std::fs::write( + dir.path().join(PROJECT_SETTINGS), + r#"{"permissions": {"deny": ["Write(secret.txt)"]}}"#, + ) + .expect("write"); + let rules = PermissionRules::load(dir.path()); + let ws = ws_for(&dir); + assert!(rules.warnings().is_empty(), "{:?}", rules.warnings()); + assert_eq!( + rules + .decide("Write", &write("secret.txt"), &ws) + .map(|v| v.effect), + Some(Effect::Deny) + ); + assert_eq!(rules.decide("Write", &write("other.txt"), &ws), None); +} + // --- a turn's allowlist --------------------------------------------------- fn listed(texts: &[&str]) -> Allowlist {