Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
fix: limit grok's and codex's model shell to core env
Lin (kwant bot)2ce255143b9b
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex aa4bbd1b..ce46684f 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -123,6 +123,15 @@ pub fn codex_reserved_name_conflict(ctx: Option<&crate::mcp::McpTurnContext>, us/// How long `codex mcp list` may take before the turn is refused.const CODEX_MCP_LIST_TIMEOUT: Duration = Duration::from_secs(15);+/// `codex exec` overrides limiting the model's shell commands to codex's "core" env+/// (PATH, HOME, USER, SHELL...). codex's default passes its whole env, provider key included.+pub const CODEX_SHELL_POLICY: [&str; 4] = [+ "-c",+ "shell_environment_policy.inherit=\"core\"",+ "-c",+ "shell_environment_policy.ignore_default_excludes=false",+];+/// Names of the MCP servers codex would load for this turn, as codex itself resolves them:/// `$CODEX_HOME`/`~/.codex` config, its active profile, a trusted project's `.codex/config.toml`/// for `cwd`, and system config. The listing holds server env values, so it is never logged.@@ -382,6 +391,7 @@ impl CliDriver {.and_then(|h| std::fs::read_to_string(h.join("config.toml")).ok()).map(|text| super::grok::model_settings(&text)).unwrap_or_default();+ super::grok::restrict_shell_env(&mut config);let auth_file = std::env::var_os("GROK_AUTH_PATH").filter(|p| !p.is_empty()).map(std::path::PathBuf::from)@@ -527,7 +537,9 @@ impl Driver for CliDriver {// Never the user's own codex servers: codex exec has no hook for kwnt's// approval cards. The kwant's servers come only through kwnt's gateway..arg("-c")- .arg(codex_mcp_servers(input.mcp.as_ref(), &user_servers));+ .arg(codex_mcp_servers(input.mcp.as_ref(), &user_servers))+ // The model's shell sees only codex's core env, never kwnt's keys or rc exports+ .args(CODEX_SHELL_POLICY);if let Some(gateway) = input.mcp.as_ref().and_then(|c| c.gateway.as_ref()) {cmd.env(crate::mcp::GATEWAY_TOKEN_ENV, &gateway.token);// codex's default shell env policy passes the token on to the model's shell@@ -734,6 +746,20 @@ mod tests {use super::*;use crate::db::models::{Kwant, Message};+ #[test]+ fn codex_shell_policy_is_core_only() {+ let args = CODEX_SHELL_POLICY.join(" ");+ assert_eq!(+ args,+ "-c shell_environment_policy.inherit=\"core\" -c shell_environment_policy.ignore_default_excludes=false"+ );+ // Each override must parse as TOML, the way `codex -c key=value` reads it+ for pair in CODEX_SHELL_POLICY.iter().skip(1).step_by(2) {+ let table: toml::Table = pair.parse().unwrap();+ assert!(table.contains_key("shell_environment_policy"), "{pair}");+ }+ }+#[test]fn test_build_cli_prompt_with_history() {let kwant = Kwant {diff --git a/src/drivers/grok.rs b/src/drivers/grok.rsindex 96d9aaa0..2d694363 100644--- a/src/drivers/grok.rs+++ b/src/drivers/grok.rs@@ -255,9 +255,66 @@ pub fn add_gateway(config: &mut toml::Table, url: &str, slowest: u64) {let mut servers = toml::Table::new();servers.insert(crate::mcp::RESERVED_SERVER_NAME.into(), server.into());config.insert("mcp_servers".into(), servers.into());+ exclude_from_shell(config, token_env);+}++/// Env names grok's own credentials may come from; hidden from the model's shell.+const CREDENTIAL_ENV: [&str; 2] = ["XAI_API_KEY", "GROK_AUTH_PATH"];++/// Limits the env the model's shell commands see to grok's "core" set (PATH, HOME, USER,+/// SHELL, TERM, LANG...). grok's default passes its whole env, and the user's rc-file+/// exports, to the model. Must run on every launch; the user's own policy was already dropped+/// by `model_settings`. The `exclude` list is belt-and-braces on top of `core`.+pub fn restrict_shell_env(config: &mut toml::Table) {+ let mut names: Vec<String> = CREDENTIAL_ENV.iter().map(|s| s.to_string()).collect();+ names.extend(provider_env_names(config));let mut policy = toml::Table::new();- policy.insert("exclude".into(), toml::Value::Array(vec![token_env.into()]));+ policy.insert("inherit".into(), "core".into());+ policy.insert("ignore_default_excludes".into(), false.into());+ policy.insert("exclude".into(), toml::Value::Array(vec![]));config.insert("shell_environment_policy".into(), policy.into());+ for name in names {+ exclude_from_shell(config, &name);+ }+}++/// `env_key` and `env_http_headers` variable names of the kept `[model.*]` tables.+fn provider_env_names(config: &toml::Table) -> Vec<String> {+ let Some(models) = config.get("model").and_then(|m| m.as_table()) else {+ return Vec::new();+ };+ let mut names = Vec::new();+ for model in models.values().filter_map(|m| m.as_table()) {+ if let Some(key) = model.get("env_key").and_then(|k| k.as_str()) {+ names.push(key.to_string());+ }+ if let Some(headers) = model.get("env_http_headers").and_then(|h| h.as_table()) {+ names.extend(+ headers+ .values()+ .filter_map(|v| v.as_str())+ .map(String::from),+ );+ }+ }+ names+}++fn exclude_from_shell(config: &mut toml::Table, name: &str) {+ let policy = config+ .entry("shell_environment_policy")+ .or_insert_with(|| toml::Table::new().into());+ let Some(policy) = policy.as_table_mut() else {+ return;+ };+ let exclude = policy+ .entry("exclude")+ .or_insert_with(|| toml::Value::Array(vec![]));+ if let Some(list) = exclude.as_array_mut() {+ if !list.iter().any(|v| v.as_str() == Some(name)) {+ list.push(name.into());+ }+ }}/// The `--allow` rule that lets grok call the gateway's tools without its own (headless,@@ -398,6 +455,77 @@ allow = ["Bash(*)"]assert_eq!(gateway_allow_rule(), "MCPTool(kwnt__*)");}+ fn exclude_list(config: &toml::Table) -> Vec<&str> {+ config["shell_environment_policy"]["exclude"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap())+ .collect()+ }++ #[test]+ fn shell_env_is_core_only_on_every_run() {+ let user = r#"+[models]+default = "corp"++[model.corp]+base_url = "https://llm.example/v1"+env_key = "CORP_LLM_KEY"+env_http_headers = { "X-Org" = "CORP_ORG_ID" }++[shell_environment_policy]+inherit = "all"+include_only = ["*"]+"#;+ // No gateway: the policy is still written, and the user's own policy is gone+ let mut config = model_settings(user);+ restrict_shell_env(&mut config);+ let text = toml::to_string(&config).unwrap();+ let parsed: toml::Table = text.parse().unwrap();+ let policy = parsed["shell_environment_policy"].as_table().unwrap();+ assert_eq!(policy["inherit"].as_str(), Some("core"), "{text}");+ assert_eq!(policy["ignore_default_excludes"].as_bool(), Some(false));+ assert!(!policy.contains_key("include_only"), "{text}");+ assert_eq!(+ exclude_list(&parsed),+ [+ "XAI_API_KEY",+ "GROK_AUTH_PATH",+ "CORP_LLM_KEY",+ "CORP_ORG_ID"+ ]+ );++ // The gateway adds its token without dropping the core policy, once+ add_gateway(&mut config, "http://x", 0);+ add_gateway(&mut config, "http://x", 0);+ assert_eq!(+ config["shell_environment_policy"]["inherit"].as_str(),+ Some("core")+ );+ assert_eq!(+ exclude_list(&config),+ [+ "XAI_API_KEY",+ "GROK_AUTH_PATH",+ "CORP_LLM_KEY",+ "CORP_ORG_ID",+ "KWNT_MCP_GATEWAY_TOKEN"+ ]+ );++ // No user config at all still gets the policy+ let mut empty = toml::Table::new();+ restrict_shell_env(&mut empty);+ assert_eq!(+ empty["shell_environment_policy"]["inherit"].as_str(),+ Some("core")+ );+ assert_eq!(exclude_list(&empty), ["XAI_API_KEY", "GROK_AUTH_PATH"]);+ }+#[test]fn written_gateway_home_never_contains_the_token() {let base = tempfile::tempdir().unwrap();diff --git a/tests/grok_driver_test.rs b/tests/grok_driver_test.rsindex ec03b445..189f17a1 100644--- a/tests/grok_driver_test.rs+++ b/tests/grok_driver_test.rs@@ -174,10 +174,17 @@ async fn grok_runs_in_a_private_temp_home() {"{listing}");- // Only the model settings are carried over+ // Only the model settings are carried over, plus kwnt's shell env policylet config: toml::Table = grok.out("config.toml").parse().unwrap();- assert_eq!(config.keys().collect::<Vec<_>>(), ["model", "models"]);+ assert_eq!(+ config.keys().collect::<Vec<_>>(),+ ["model", "models", "shell_environment_policy"]+ );assert_eq!(config["models"]["default"].as_str(), Some("mock"));+ assert_eq!(+ config["shell_environment_policy"]["inherit"].as_str(),+ Some("core")+ );assert!(!home.exists(), "temp home left behind: {home:?}");// The user's own grok home is untouched@@ -226,7 +233,16 @@ async fn grok_without_user_config_still_runs_isolated() {std::fs::remove_file(grok.user_home.join("config.toml")).unwrap();let (reply, _) = grok.run(None).await;assert_eq!(reply.trim(), "ok");- assert_eq!(grok.out("config.toml").trim(), "");+ // Nothing of the user's, but the model's shell is still limited to core env+ let config: toml::Table = grok.out("config.toml").parse().unwrap();+ assert_eq!(+ config.keys().collect::<Vec<_>>(),+ ["shell_environment_policy"]+ );+ assert_eq!(+ config["shell_environment_policy"]["inherit"].as_str(),+ Some("core")+ );}async fn wait_for(path: &Path) {@@ -338,9 +354,13 @@ async fn grok_gets_the_gateway_with_the_token_in_env_only() {Some("Bearer ${KWNT_MCP_GATEWAY_TOKEN}"));assert_eq!(- config["shell_environment_policy"]["exclude"][0].as_str(),- Some("KWNT_MCP_GATEWAY_TOKEN")+ config["shell_environment_policy"]["inherit"].as_str(),+ Some("core"));+ assert!(config["shell_environment_policy"]["exclude"]+ .as_array()+ .unwrap()+ .contains(&toml::Value::from("KWNT_MCP_GATEWAY_TOKEN")));for secret in ["gw-secret-token", "sk-very-secret", "/usr/bin/true"] {assert!(!argv.contains(secret), "{secret} in argv: {argv}");assert!(diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex 95e48b13..9b9f74ac 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -406,7 +406,14 @@ async fn codex_cli_reaches_mcp_only_through_kwnts_gateway() {// Without servers (none assigned, or the kwant opted out) codex still gets none of the user'slet (plain, token, _, _) = fake_agent_run("codex", None, Some(USER_SERVERS)).await;assert!(plain.contains(r#"-c mcp_servers={"userdummy"={enabled=false},"user.dot \"q\""={enabled=false}} "#), "{plain}");- assert!(!plain.contains("shell_environment_policy"), "{plain}");+ // The model's shell is limited to core env on every run, gateway or not+ for run in [&argv, &plain] {+ assert!(+ run.contains(r#"-c shell_environment_policy.inherit="core" -c shell_environment_policy.ignore_default_excludes=false "#),+ "{run}"+ );+ }+ assert!(!plain.contains("shell_environment_policy.set"), "{plain}");assert_eq!(token, "unset");// And with no user servers either, the override is empty, as before