Files
codex/codex-rs/core/src/tools/runtimes/shell.rs
T

255 lines
7.6 KiB
Rust

/*
Runtime: shell
Executes shell requests under the orchestrator: asks for approval when needed,
builds a CommandSpec, and runs it under the current SandboxAttempt.
*/
use crate::command_safety::is_dangerous_command::requires_initial_appoval;
use crate::exec::ExecToolCallOutput;
use crate::exec_policy::evaluate_with_policy;
use crate::protocol::SandboxPolicy;
use crate::sandboxing::execute_env;
use crate::tools::runtimes::build_command_spec;
use crate::tools::sandboxing::Approvable;
use crate::tools::sandboxing::ApprovalCtx;
use crate::tools::sandboxing::ApprovalRequirement;
use crate::tools::sandboxing::ProvidesSandboxRetryData;
use crate::tools::sandboxing::SandboxAttempt;
use crate::tools::sandboxing::SandboxRetryData;
use crate::tools::sandboxing::Sandboxable;
use crate::tools::sandboxing::SandboxablePreference;
use crate::tools::sandboxing::ToolCtx;
use crate::tools::sandboxing::ToolError;
use crate::tools::sandboxing::ToolRuntime;
use crate::tools::sandboxing::with_cached_approval;
use codex_execpolicy2::Policy as ExecPolicyV2;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::ReviewDecision;
use futures::future::BoxFuture;
use std::path::PathBuf;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct ShellRequest {
pub command: Vec<String>,
pub cwd: PathBuf,
pub timeout_ms: Option<u64>,
pub env: std::collections::HashMap<String, String>,
pub with_escalated_permissions: Option<bool>,
pub justification: Option<String>,
pub exec_policy: Option<Arc<ExecPolicyV2>>,
}
impl ProvidesSandboxRetryData for ShellRequest {
fn sandbox_retry_data(&self) -> Option<SandboxRetryData> {
Some(SandboxRetryData {
command: self.command.clone(),
cwd: self.cwd.clone(),
})
}
}
#[derive(Default)]
pub struct ShellRuntime;
#[derive(serde::Serialize, Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) struct ApprovalKey {
command: Vec<String>,
cwd: PathBuf,
escalated: bool,
}
impl ShellRuntime {
pub fn new() -> Self {
Self
}
fn stdout_stream(ctx: &ToolCtx<'_>) -> Option<crate::exec::StdoutStream> {
Some(crate::exec::StdoutStream {
sub_id: ctx.turn.sub_id.clone(),
call_id: ctx.call_id.clone(),
tx_event: ctx.session.get_tx_event(),
})
}
}
impl Sandboxable for ShellRuntime {
fn sandbox_preference(&self) -> SandboxablePreference {
SandboxablePreference::Auto
}
fn escalate_on_failure(&self) -> bool {
true
}
}
impl Approvable<ShellRequest> for ShellRuntime {
type ApprovalKey = ApprovalKey;
fn approval_key(&self, req: &ShellRequest) -> Self::ApprovalKey {
ApprovalKey {
command: req.command.clone(),
cwd: req.cwd.clone(),
escalated: req.with_escalated_permissions.unwrap_or(false),
}
}
fn start_approval_async<'a>(
&'a mut self,
req: &'a ShellRequest,
ctx: ApprovalCtx<'a>,
) -> BoxFuture<'a, ReviewDecision> {
let key = self.approval_key(req);
let command = req.command.clone();
let cwd = req.cwd.clone();
let reason = ctx
.retry_reason
.clone()
.or_else(|| req.justification.clone());
let risk = ctx.risk.clone();
let session = ctx.session;
let turn = ctx.turn;
let call_id = ctx.call_id.to_string();
Box::pin(async move {
with_cached_approval(&session.services, key, move || async move {
session
.request_command_approval(turn, call_id, command, cwd, reason, risk)
.await
})
.await
})
}
fn approval_requirement(
&self,
req: &ShellRequest,
policy: AskForApproval,
sandbox_policy: &SandboxPolicy,
) -> ApprovalRequirement {
if let Some(exec_policy) = &req.exec_policy
&& let Some(requirement) = evaluate_with_policy(exec_policy, &req.command, policy)
{
requirement
} else if requires_initial_appoval(
policy,
sandbox_policy,
&req.command,
req.with_escalated_permissions.unwrap_or(false),
) {
ApprovalRequirement::NeedsApproval { reason: None }
} else {
ApprovalRequirement::Skip
}
}
fn wants_escalated_first_attempt(&self, req: &ShellRequest) -> bool {
req.with_escalated_permissions.unwrap_or(false)
}
}
impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
async fn run(
&mut self,
req: &ShellRequest,
attempt: &SandboxAttempt<'_>,
ctx: &ToolCtx<'_>,
) -> Result<ExecToolCallOutput, ToolError> {
let spec = build_command_spec(
&req.command,
&req.cwd,
&req.env,
req.timeout_ms,
req.with_escalated_permissions,
req.justification.clone(),
)?;
let env = attempt
.env_for(&spec)
.map_err(|err| ToolError::Codex(err.into()))?;
let out = execute_env(&env, attempt.policy, Self::stdout_stream(ctx))
.await
.map_err(ToolError::Codex)?;
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
use codex_execpolicy2::PolicyParser;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
fn parse_policy(src: &str) -> Arc<ExecPolicyV2> {
let mut parser = PolicyParser::new();
parser
.parse("test.codexpolicy", src)
.expect("parse execpolicy2 file");
Arc::new(parser.build())
}
fn shell_request(command: &[&str], exec_policy: Option<Arc<ExecPolicyV2>>) -> ShellRequest {
ShellRequest {
command: command.iter().map(ToString::to_string).collect(),
cwd: PathBuf::from("."),
timeout_ms: None,
env: HashMap::new(),
with_escalated_permissions: None,
justification: None,
exec_policy,
}
}
#[test]
fn prompt_decision_requires_approval() {
let policy = parse_policy(r#"prefix_rule(pattern=["echo"], decision="prompt")"#);
let req = shell_request(&["echo", "hi"], Some(policy));
let runtime = ShellRuntime::new();
let requirement = runtime.approval_requirement(
&req,
AskForApproval::OnRequest,
&SandboxPolicy::DangerFullAccess,
);
assert_eq!(
requirement,
ApprovalRequirement::NeedsApproval {
reason: Some("execpolicy requires approval for this command".to_string())
}
);
}
#[test]
fn prompt_blocked_when_approval_disabled() {
let policy = parse_policy(r#"prefix_rule(pattern=["echo"], decision="prompt")"#);
let req = shell_request(&["echo", "hi"], Some(policy));
let runtime = ShellRuntime::new();
let requirement = runtime.approval_requirement(
&req,
AskForApproval::Never,
&SandboxPolicy::DangerFullAccess,
);
assert_eq!(
requirement,
ApprovalRequirement::Forbidden {
reason: "execpolicy requires approval for this command".to_string()
}
);
}
#[test]
fn user_shell_commands_skip_execpolicy() {
let req = shell_request(&["echo", "hi"], None);
let runtime = ShellRuntime::new();
let requirement = runtime.approval_requirement(
&req,
AskForApproval::OnRequest,
&SandboxPolicy::DangerFullAccess,
);
assert_eq!(requirement, ApprovalRequirement::Skip);
}
}