permissions: --yolo, command-aware allow rules, load allow.json
This commit is contained in:
1 parent
b36559bd95
commit
23dc8cd36e
6 files changed
+148
-36
No files matched your search
@@ -36,6 +36,9 @@ struct Cli {
|
||||
/// Resume: no value opens the session picker; with a query resumes the best title match.
|
||||
#[arg(short, long, num_args = 0..=1, default_missing_value = "")]
|
||||
resume: Option<String>,
|
||||
/// Skip permission prompts for bash/write/edit (also `permissions = "yolo"` in config.toml).
|
||||
#[arg(long)]
|
||||
yolo: bool,
|
||||
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio).
|
||||
#[arg(long, value_enum, default_value_t = Mode::Text)]
|
||||
mode: Mode,
|
||||
@@ -79,6 +82,8 @@ struct Config {
|
||||
explore_model: Option<String>,
|
||||
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
|
||||
mouse: Option<bool>,
|
||||
/// "ask" (default) or "yolo": whether bash/write/edit prompt in the TUI.
|
||||
permissions: Option<String>,
|
||||
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
|
||||
system_prompt: Option<String>,
|
||||
lsp: Option<LspCfg>,
|
||||
@@ -124,6 +129,7 @@ impl Config {
|
||||
max_tokens: o.max_tokens.or(c.max_tokens),
|
||||
explore_model: o.explore_model.or(c.explore_model),
|
||||
mouse: o.mouse.or(c.mouse),
|
||||
permissions: o.permissions.or(c.permissions),
|
||||
system_prompt: o.system_prompt.or(c.system_prompt),
|
||||
lsp: o.lsp.or(c.lsp),
|
||||
extensions: [c.extensions, o.extensions].concat(),
|
||||
@@ -616,6 +622,7 @@ async fn main() -> Result<()> {
|
||||
pricing,
|
||||
specs,
|
||||
open_sessions,
|
||||
yolo: cli.yolo || cfg.permissions.as_deref() == Some("yolo"),
|
||||
mcp: mcp
|
||||
.servers
|
||||
.iter()
|
||||
|
||||
@@ -32,25 +32,74 @@ pub type Permit = std::sync::Arc<
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
/// `bash` rules cover a command's first word (`bash:cargo`); file tools are covered as a whole.
|
||||
// ponytail: first-word granularity; add glob/argument patterns when people want `rm target/*` only.
|
||||
/// Never remembered as a pattern: "always" stores the exact command only.
|
||||
const RISKY: &[&str] = &[
|
||||
"rm", "sudo", "su", "dd", "mkfs", "chmod", "chown", "curl", "wget", "ssh", "scp", "sh", "bash",
|
||||
"zsh", "eval", "exec", "xargs", "find", "env", "git",
|
||||
];
|
||||
|
||||
/// Shell syntax that chains or redirects: such commands match no pattern rule and are never
|
||||
/// remembered, so `cargo test && rm -rf ~` cannot ride on a `cargo test *` rule.
|
||||
fn compound(cmd: &str) -> bool {
|
||||
cmd.contains(['\n', ';', '&', '|', '<', '>', '`', '$', '(', ')'])
|
||||
}
|
||||
|
||||
/// Rule for "allow always". Bash: `bash:<command words> *` (first word, plus the subcommand when
|
||||
/// there is one, e.g. `bash:cargo test *`); risky or compound commands store the exact command, or
|
||||
/// nothing at all for compound ones (empty rule = the prompt offers no "always").
|
||||
/// File tools are covered as a whole by the tool name.
|
||||
// ponytail: patterns are `*` globs on the full command line; add argument-aware rules if needed.
|
||||
pub fn request(tool: &str, args: &serde_json::Value) -> Request {
|
||||
let s = |k: &str| args[k].as_str().unwrap_or_default().to_string();
|
||||
if tool == "bash" {
|
||||
let cmd = s("command");
|
||||
let word = cmd.split_whitespace().next().unwrap_or_default();
|
||||
Request {
|
||||
tool: tool.into(),
|
||||
detail: cmd.clone(),
|
||||
rule: format!("bash:{word}"),
|
||||
}
|
||||
} else {
|
||||
Request {
|
||||
if tool != "bash" {
|
||||
return Request {
|
||||
tool: tool.into(),
|
||||
detail: s("path"),
|
||||
rule: tool.into(),
|
||||
};
|
||||
}
|
||||
let cmd = s("command");
|
||||
let cmd = cmd.trim().to_string();
|
||||
let words: Vec<&str> = cmd.split_whitespace().collect();
|
||||
let rule = if compound(&cmd) || words.is_empty() {
|
||||
String::new()
|
||||
} else if RISKY.contains(&words[0]) {
|
||||
format!("bash:{cmd}")
|
||||
} else if let Some(w) = words.get(1).filter(|w| {
|
||||
w.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
&& !w.starts_with('-')
|
||||
}) {
|
||||
format!("bash:{} {w} *", words[0])
|
||||
} else {
|
||||
format!("bash:{} *", words[0])
|
||||
};
|
||||
Request {
|
||||
tool: tool.into(),
|
||||
detail: cmd,
|
||||
rule,
|
||||
}
|
||||
}
|
||||
|
||||
/// `*` matches any run of characters; everything else literally.
|
||||
fn glob(pat: &str, s: &str) -> bool {
|
||||
let parts: Vec<&str> = pat.split('*').collect();
|
||||
if parts.len() == 1 {
|
||||
return pat == s;
|
||||
}
|
||||
let (first, last) = (parts[0], parts[parts.len() - 1]);
|
||||
if s.len() < first.len() + last.len() || !s.starts_with(first) || !s.ends_with(last) {
|
||||
return false;
|
||||
}
|
||||
let mut at = first.len();
|
||||
let end = s.len() - last.len();
|
||||
for m in &parts[1..parts.len() - 1] {
|
||||
match s[at..end].find(m) {
|
||||
Some(i) => at += i + m.len(),
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Always-allowed rules, persisted in `<project>/.hx/allow.json`.
|
||||
@@ -72,11 +121,26 @@ impl Allow {
|
||||
file: Some(file),
|
||||
}
|
||||
}
|
||||
pub fn has(&self, rule: &str) -> bool {
|
||||
self.rules.contains(rule)
|
||||
|
||||
/// Is this request covered by a stored rule? `bash:cargo test *` also covers a bare `cargo test`.
|
||||
pub fn allows(&self, r: &Request) -> bool {
|
||||
if r.tool != "bash" {
|
||||
return self.rules.contains(&r.rule);
|
||||
}
|
||||
if compound(&r.detail) {
|
||||
return false;
|
||||
}
|
||||
self.rules
|
||||
.iter()
|
||||
.filter_map(|x| x.strip_prefix("bash:"))
|
||||
.any(|p| glob(p, &r.detail) || p.strip_suffix(" *").is_some_and(|b| b == r.detail))
|
||||
}
|
||||
|
||||
/// Remember a rule; the file is best effort (the rule holds for this session either way).
|
||||
pub fn add(&mut self, rule: &str) {
|
||||
if rule.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.rules.insert(rule.into());
|
||||
if let Some(f) = &self.file {
|
||||
let mut v: Vec<_> = self.rules.iter().collect();
|
||||
@@ -102,23 +166,33 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn bash(c: &str) -> Request {
|
||||
request("bash", &json!({ "command": c }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_from_requests() {
|
||||
let r = request("bash", &json!({"command": "cargo test -q"}));
|
||||
assert_eq!(
|
||||
(r.rule.as_str(), r.detail.as_str()),
|
||||
("bash:cargo", "cargo test -q")
|
||||
);
|
||||
assert_eq!(bash("cargo test -q").rule, "bash:cargo test *");
|
||||
assert_eq!(bash("ls -l").rule, "bash:ls *");
|
||||
assert_eq!(bash("rm -rf target").rule, "bash:rm -rf target");
|
||||
assert_eq!(bash("cargo test && rm -rf ~").rule, "");
|
||||
assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "edit");
|
||||
assert!(gated("bash") && !gated("read"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allow_persists() {
|
||||
fn rules_match_narrowly() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let mut a = Allow::load(d.path());
|
||||
assert!(!a.has("bash:ls"));
|
||||
a.add("bash:ls");
|
||||
assert!(Allow::load(d.path()).has("bash:ls"));
|
||||
a.add(&bash("cargo test -q").rule);
|
||||
a.add(&bash("rm -rf target").rule);
|
||||
assert!(a.allows(&bash("cargo test")) && a.allows(&bash("cargo test -p x")));
|
||||
assert!(!a.allows(&bash("cargo publish")) && !a.allows(&bash("cargo testx")));
|
||||
assert!(!a.allows(&bash("cargo test && rm -rf ~")) && !a.allows(&bash("cargo test; id")));
|
||||
assert!(a.allows(&bash("rm -rf target")) && !a.allows(&bash("rm -rf /")));
|
||||
// persisted
|
||||
assert!(Allow::load(d.path()).allows(&bash("cargo test -q")));
|
||||
a.add("");
|
||||
assert!(!a.allows(&bash("")));
|
||||
}
|
||||
}
|
||||
@@ -114,7 +114,7 @@ impl Registry {
|
||||
.allow
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.has(&req.rule);
|
||||
.allows(&req);
|
||||
if !known {
|
||||
let rule = req.rule.clone();
|
||||
match ask(req).await {
|
||||
|
||||
@@ -53,6 +53,8 @@ pub struct Setup {
|
||||
pub open_sessions: bool,
|
||||
/// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag.
|
||||
pub mouse: bool,
|
||||
/// No permission prompts (`--yolo`).
|
||||
pub yolo: bool,
|
||||
/// MCP servers for the side panel: (name, connected).
|
||||
pub mcp: Vec<(String, bool)>,
|
||||
}
|
||||
@@ -234,6 +236,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
specs,
|
||||
open_sessions,
|
||||
mouse,
|
||||
yolo,
|
||||
mcp,
|
||||
} = setup;
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
@@ -250,7 +253,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
Box::pin(async move { orx.await.unwrap_or(false) })
|
||||
}));
|
||||
}
|
||||
{
|
||||
if !yolo {
|
||||
let tx = tx.clone();
|
||||
let _ = agent.cx.state.permit.set(std::sync::Arc::new(move |r| {
|
||||
let (otx, orx) = tokio::sync::oneshot::channel();
|
||||
@@ -270,6 +273,12 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
let _ = agent.cx.state.subs.events.set(stx);
|
||||
let abort: AbortHandle = agent.abort_handle();
|
||||
let cwd = agent.cx.cwd.clone();
|
||||
*agent
|
||||
.cx
|
||||
.state
|
||||
.allow
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner()) = hx_core::permit::Allow::load(&cwd);
|
||||
let mut app = App {
|
||||
t: Transcript::default(),
|
||||
ed: Editor::default(),
|
||||
|
||||
@@ -18,20 +18,40 @@ impl Prompt {
|
||||
}
|
||||
|
||||
/// Some = decided.
|
||||
/// Chained commands have no rule: they are asked every time.
|
||||
fn can_always(&self) -> bool {
|
||||
!self.req.rule.is_empty()
|
||||
}
|
||||
|
||||
fn opts(&self) -> Vec<(Decision, String)> {
|
||||
let mut v = vec![(Decision::Once, "[y] allow once".to_string())];
|
||||
if self.can_always() {
|
||||
let r = self
|
||||
.req
|
||||
.rule
|
||||
.strip_prefix("bash:")
|
||||
.unwrap_or(&self.req.rule);
|
||||
v.push((Decision::Always, format!("[a] allow always: {r}")));
|
||||
}
|
||||
v.push((Decision::Deny, "[n] deny".into()));
|
||||
v
|
||||
}
|
||||
|
||||
pub fn key(&mut self, k: KeyEvent) -> Option<Decision> {
|
||||
match k.code {
|
||||
KeyCode::Char('y' | 'Y') => Some(Decision::Once),
|
||||
KeyCode::Char('a' | 'A') => Some(Decision::Always),
|
||||
KeyCode::Char('a' | 'A') if self.can_always() => Some(Decision::Always),
|
||||
KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(Decision::Deny),
|
||||
KeyCode::Up | KeyCode::Left => {
|
||||
self.sel = (self.sel + 2) % 3;
|
||||
let n = self.opts().len();
|
||||
self.sel = (self.sel + n - 1) % n;
|
||||
None
|
||||
}
|
||||
KeyCode::Down | KeyCode::Right | KeyCode::Tab => {
|
||||
self.sel = (self.sel + 1) % 3;
|
||||
self.sel = (self.sel + 1) % self.opts().len();
|
||||
None
|
||||
}
|
||||
KeyCode::Enter => Some([Decision::Once, Decision::Always, Decision::Deny][self.sel]),
|
||||
KeyCode::Enter => Some(self.opts()[self.sel].0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -49,11 +69,7 @@ impl Prompt {
|
||||
let th = theme::t();
|
||||
let a = f.area();
|
||||
let w = (a.width * 3 / 5).clamp(44, 100).min(a.width);
|
||||
let opts = [
|
||||
"[y] allow once".to_string(),
|
||||
format!("[a] allow always: {}", self.req.rule),
|
||||
"[n] deny".to_string(),
|
||||
];
|
||||
let opts: Vec<String> = self.opts().into_iter().map(|o| o.1).collect();
|
||||
let mut lines = vec![
|
||||
Line::styled("hx wants to run:", th.dim()),
|
||||
Line::default(),
|
||||
@@ -102,7 +118,7 @@ mod tests {
|
||||
Prompt::new(Request {
|
||||
tool: "bash".into(),
|
||||
detail: "rm -rf x".into(),
|
||||
rule: "bash:rm".into(),
|
||||
rule: "bash:rm -rf x".into(),
|
||||
})
|
||||
}
|
||||
fn k(c: KeyCode) -> KeyEvent {
|
||||
@@ -117,5 +133,11 @@ mod tests {
|
||||
let mut q = p();
|
||||
assert_eq!(q.key(k(KeyCode::Down)), None);
|
||||
assert_eq!(q.key(k(KeyCode::Enter)), Some(Decision::Always));
|
||||
// chained command: no "always"
|
||||
let mut c = p();
|
||||
c.req.rule.clear();
|
||||
assert_eq!(c.key(k(KeyCode::Char('a'))), None);
|
||||
c.key(k(KeyCode::Down));
|
||||
assert_eq!(c.key(k(KeyCode::Enter)), Some(Decision::Deny));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user