| 1 | use super::*; |
| 2 | use tempfile::tempdir; |
| 3 | |
| 4 | #[test] |
| 5 | fn enforced_readonly_mode_is_an_execution_contract_and_preserves_plain_classification() { |
| 6 | let plain = json!({"command": "python3 -c 'print(1)'"}); |
| 7 | let input = json!({"command": "python3 -c 'print(1)'", "read_only": true}); |
| 8 | assert!(!agent_readonly_bash_input(&plain)); |
| 9 | assert!(!LowercaseBashTool.is_read_only_for(&plain)); |
| 10 | assert!(agent_readonly_bash_input(&input)); |
| 11 | assert!(LowercaseBashTool.is_read_only_for(&input)); |
| 12 | assert!(LowercaseBashTool.supports_parallel_for(&input)); |
| 13 | assert_eq!( |
| 14 | LowercaseBashTool.input_schema()["properties"]["read_only"]["type"], |
| 15 | "boolean" |
| 16 | ); |
| 17 | for invalid in [json!(null), json!("true"), json!(1)] { |
| 18 | let mut input = input.clone(); |
| 19 | input["read_only"] = invalid; |
| 20 | assert!(contract_bash_legacy_input(&input).is_err()); |
| 21 | assert!(!agent_readonly_bash_input(&input)); |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | #[tokio::test] |
| 26 | async fn enforced_readonly_rejects_incompatible_shapes_before_running_anything() { |
| 27 | let tmp = tempdir().unwrap(); |
| 28 | let context = ToolContext::new(tmp.path()); |
| 29 | for (key, value) in [ |
| 30 | ("action", json!("wait")), |
| 31 | ("background", json!(true)), |
| 32 | ("interactive", json!(true)), |
| 33 | ("tty", json!(true)), |
| 34 | ("stdin", json!("input")), |
| 35 | ("sandbox_permissions", json!("danger-full-access")), |
| 36 | ("justification", json!("please widen")), |
| 37 | ] { |
| 38 | let mut input = json!({"command": "touch should-not-exist", "read_only": true}); |
| 39 | input[key] = value; |
| 40 | assert!( |
| 41 | exec_shell_input_agent_readonly_verdict(&input).is_err(), |
| 42 | "{input}" |
| 43 | ); |
| 44 | let error = BashTool::new("Bash") |
| 45 | .execute(input, &context) |
| 46 | .await |
| 47 | .unwrap_err(); |
| 48 | assert!(error.to_string().contains("incompatible"), "{error}"); |
| 49 | assert!(!tmp.path().join("should-not-exist").exists()); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[test] |
| 54 | fn enforced_readonly_refuses_an_unenforced_or_writable_prepared_environment() { |
| 55 | let tmp = tempdir().unwrap(); |
| 56 | let mut environment = ExecEnv { |
| 57 | command: vec!["must-not-run".into()], |
| 58 | cwd: tmp.path().into(), |
| 59 | env: HashMap::new(), |
| 60 | timeout: Duration::from_secs(1), |
| 61 | sandbox_type: SandboxType::None, |
| 62 | policy: ExecutionSandboxPolicy::read_only(), |
| 63 | scratch: None, |
| 64 | }; |
| 65 | assert!(require_native_readonly_execution(&environment).is_err()); |
| 66 | #[cfg(target_os = "macos")] |
| 67 | { |
| 68 | environment.sandbox_type = SandboxType::MacosSeatbelt; |
| 69 | } |
| 70 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 71 | { |
| 72 | environment.sandbox_type = SandboxType::LinuxBubblewrap; |
| 73 | } |
| 74 | environment.policy = ExecutionSandboxPolicy::DangerFullAccess; |
| 75 | assert!(require_native_readonly_execution(&environment).is_err()); |
| 76 | } |
| 77 | |
| 78 | struct RefusingExternalBackend; |
| 79 | #[async_trait] |
| 80 | impl codewhale_sandbox::backend::SandboxBackend for RefusingExternalBackend { |
| 81 | fn kind(&self) -> codewhale_sandbox::backend::SandboxKind { |
| 82 | codewhale_sandbox::backend::SandboxKind::Unsupported |
| 83 | } |
| 84 | async fn exec( |
| 85 | &self, |
| 86 | _command: &str, |
| 87 | _env: &HashMap<String, String>, |
| 88 | ) -> Result<codewhale_sandbox::backend::SandboxOutput> { |
| 89 | panic!("enforced read-only must never reach an unattested external executor") |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | #[tokio::test] |
| 94 | async fn enforced_readonly_refuses_external_backend_without_dispatch() { |
| 95 | let tmp = tempdir().unwrap(); |
| 96 | let mut context = ToolContext::new(tmp.path()); |
| 97 | context.sandbox_backend = Some(std::sync::Arc::new(RefusingExternalBackend)); |
| 98 | let error = LowercaseBashTool |
| 99 | .execute( |
| 100 | json!({"command": "touch should-not-exist", "read_only": true}), |
| 101 | &context, |
| 102 | ) |
| 103 | .await |
| 104 | .unwrap_err(); |
| 105 | assert!(error.to_string().contains("external backends"), "{error}"); |
| 106 | assert!(!tmp.path().join("should-not-exist").exists()); |
| 107 | } |
| 108 | |
| 109 | #[cfg(unix)] |
| 110 | #[allow(clippy::print_stderr)] // Test receipt distinguishes unavailable enforcement from a real probe. |
| 111 | fn native_context(root: &std::path::Path) -> Option<ToolContext> { |
| 112 | let mut context = ToolContext::new(root); |
| 113 | context.auto_approve = true; |
| 114 | // Exercise narrowing from the broadest incoming posture. |
| 115 | context.elevated_sandbox_policy = Some(ExecutionSandboxPolicy::DangerFullAccess); |
| 116 | context.shell_policy = ShellPolicy::ReadOnly; |
| 117 | #[cfg(target_os = "linux")] |
| 118 | context.shell_manager.lock().unwrap().set_prefer_bwrap(true); |
| 119 | if !context |
| 120 | .shell_manager |
| 121 | .lock() |
| 122 | .unwrap() |
| 123 | .configured_sandbox_type() |
| 124 | .is_some_and(is_native_readonly_sandbox) |
| 125 | { |
| 126 | eprintln!("UNRUN: native read_only execution probe; no enforcing sandbox available"); |
| 127 | return None; |
| 128 | } |
| 129 | Some(context) |
| 130 | } |
| 131 | |
| 132 | #[cfg(unix)] |
| 133 | fn python(script: &str) -> String { |
| 134 | let binary = [ |
| 135 | "/usr/bin/python3", |
| 136 | "/opt/homebrew/bin/python3", |
| 137 | "/usr/local/bin/python3", |
| 138 | ] |
| 139 | .into_iter() |
| 140 | .find(|candidate| std::path::Path::new(candidate).is_file()) |
| 141 | .expect("Python fixture runtime"); |
| 142 | format!("{binary} -I -B -c {}", shell_words::quote(script)) |
| 143 | } |
| 144 | |
| 145 | #[cfg(unix)] |
| 146 | #[tokio::test] |
| 147 | #[allow(clippy::print_stderr)] // Native enforcement receipt, outside the TUI runtime. |
| 148 | async fn enforced_readonly_native_python_reads_sqlite_and_cannot_write() { |
| 149 | // #6305: the sandbox replaces /tmp with a fresh tmpfs, so a fixture |
| 150 | // rooted there vanishes before --chdir reaches it. |
| 151 | let tmp = crate::test_support::sandbox_visible_tempdir(); |
| 152 | let Some(context) = native_context(tmp.path()) else { |
| 153 | return; |
| 154 | }; |
| 155 | let database = rusqlite::Connection::open(tmp.path().join("fixture.sqlite")).unwrap(); |
| 156 | database |
| 157 | .execute_batch( |
| 158 | "CREATE TABLE fixture(value TEXT); INSERT INTO fixture VALUES ('read-receipt');", |
| 159 | ) |
| 160 | .unwrap(); |
| 161 | drop(database); |
| 162 | std::fs::write(tmp.path().join("peer.txt"), "preserve peer bytes").unwrap(); |
| 163 | let read = LowercaseBashTool.execute(json!({ |
| 164 | "command": python("import sqlite3; c=sqlite3.connect('file:fixture.sqlite?mode=ro', uri=True); print(c.execute('SELECT value FROM fixture').fetchone()[0])"), |
| 165 | "read_only": true |
| 166 | }), &context).await.unwrap(); |
| 167 | assert!( |
| 168 | read.success && read.content.contains("read-receipt"), |
| 169 | "{}", |
| 170 | read.content |
| 171 | ); |
| 172 | assert_eq!(read.metadata.as_ref().unwrap()["sandboxed"], true); |
| 173 | let refused = LowercaseBashTool |
| 174 | .execute( |
| 175 | json!({ |
| 176 | "command": python("open('peer.txt', 'w').write('corrupt')"), "read_only": true |
| 177 | }), |
| 178 | &context, |
| 179 | ) |
| 180 | .await |
| 181 | .unwrap_err(); |
| 182 | assert!( |
| 183 | refused.to_string().contains("Operation not permitted") |
| 184 | || refused.to_string().contains("Read-only file system") |
| 185 | || refused.to_string().contains("Permission denied"), |
| 186 | "{refused}" |
| 187 | ); |
| 188 | assert_eq!( |
| 189 | std::fs::read_to_string(tmp.path().join("peer.txt")).unwrap(), |
| 190 | "preserve peer bytes" |
| 191 | ); |
| 192 | eprintln!( |
| 193 | "NATIVE_READONLY_ENFORCED: SQLite read succeeded; write denied and peer bytes preserved" |
| 194 | ); |
| 195 | } |
| 196 | |
| 197 | #[cfg(unix)] |
| 198 | #[tokio::test] |
| 199 | #[allow(clippy::print_stderr)] // Native enforcement receipt, outside the TUI runtime. |
| 200 | async fn enforced_readonly_native_python_cannot_reach_a_loopback_listener() { |
| 201 | // #6305: the sandbox replaces /tmp with a fresh tmpfs, so a fixture |
| 202 | // rooted there vanishes before --chdir reaches it. |
| 203 | let tmp = crate::test_support::sandbox_visible_tempdir(); |
| 204 | let Some(mut context) = native_context(tmp.path()) else { |
| 205 | return; |
| 206 | }; |
| 207 | context.elevated_sandbox_policy = Some(ExecutionSandboxPolicy::default()); |
| 208 | let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); |
| 209 | listener.set_nonblocking(true).unwrap(); |
| 210 | let port = listener.local_addr().unwrap().port(); |
| 211 | let script = format!( |
| 212 | "import socket; s=socket.socket(); s.settimeout(1); s.connect(('127.0.0.1', {port})); print('connected')" |
| 213 | ); |
| 214 | let refused = LowercaseBashTool |
| 215 | .execute( |
| 216 | json!({"command": python(&script), "read_only": true}), |
| 217 | &context, |
| 218 | ) |
| 219 | .await |
| 220 | .unwrap_err(); |
| 221 | // Python includes the submitted source line in its traceback. Only an |
| 222 | // actual output line means the script reached the print after connect. |
| 223 | assert!( |
| 224 | !refused |
| 225 | .to_string() |
| 226 | .lines() |
| 227 | .any(|line| line.trim() == "connected"), |
| 228 | "{refused}" |
| 229 | ); |
| 230 | assert_eq!( |
| 231 | listener.accept().unwrap_err().kind(), |
| 232 | std::io::ErrorKind::WouldBlock |
| 233 | ); |
| 234 | eprintln!( |
| 235 | "NATIVE_READONLY_ENFORCED: loopback connection denied; listener received no connection" |
| 236 | ); |
| 237 | } |
| 238 | |
| 239 | #[cfg(unix)] |
| 240 | #[tokio::test] |
| 241 | #[allow(clippy::print_stderr)] |
| 242 | async fn enforced_readonly_native_gets_a_private_tmpdir_removed_after_the_command() { |
| 243 | let tmp = crate::test_support::sandbox_visible_tempdir(); |
| 244 | let Some(context) = native_context(tmp.path()) else { |
| 245 | return; |
| 246 | }; |
| 247 | #[cfg(target_os = "macos")] |
| 248 | let command = "f=$(mktemp -p \"$TMPDIR\") && echo scratch > \"$f\" && cat \"$f\" && /bin/zsh -c 'cat <<EOF\nheredoc-ok:$TMPDIR\nEOF'"; |
| 249 | #[cfg(not(target_os = "macos"))] |
| 250 | let command = "f=$(mktemp -p \"$TMPDIR\") && echo scratch > \"$f\" && cat \"$f\" <<'EOF'\nunused\nEOF\ncat <<EOF\nfile:$f\nheredoc-ok:$TMPDIR\nEOF"; |
| 251 | let result = LowercaseBashTool |
| 252 | .execute( |
| 253 | json!({ |
| 254 | "command": command, |
| 255 | "read_only": true |
| 256 | }), |
| 257 | &context, |
| 258 | ) |
| 259 | .await |
| 260 | .unwrap(); |
| 261 | assert!( |
| 262 | result.success && result.content.contains("scratch"), |
| 263 | "{}", |
| 264 | result.content |
| 265 | ); |
| 266 | let scratch = result |
| 267 | .content |
| 268 | .lines() |
| 269 | .find_map(|line| line.trim().strip_prefix("heredoc-ok:")) |
| 270 | .map(std::path::PathBuf::from) |
| 271 | .unwrap_or_else(|| panic!("{}", result.content)); |
| 272 | assert!(!scratch.starts_with(tmp.path()), "{}", scratch.display()); |
| 273 | #[cfg(target_os = "macos")] |
| 274 | assert!( |
| 275 | !scratch.exists(), |
| 276 | "{} outlived the command", |
| 277 | scratch.display() |
| 278 | ); |
| 279 | #[cfg(not(target_os = "macos"))] |
| 280 | { |
| 281 | let file = result |
| 282 | .content |
| 283 | .lines() |
| 284 | .find_map(|line| line.trim().strip_prefix("file:")) |
| 285 | .map(std::path::PathBuf::from) |
| 286 | .unwrap_or_else(|| panic!("{}", result.content)); |
| 287 | assert!( |
| 288 | !file.exists(), |
| 289 | "{} leaked outside bubblewrap", |
| 290 | file.display() |
| 291 | ); |
| 292 | } |
| 293 | #[cfg(target_os = "macos")] |
| 294 | { |
| 295 | let sh_heredoc = LowercaseBashTool |
| 296 | .execute( |
| 297 | json!({"command": "/bin/sh -c 'cat <<EOF\nhi\nEOF'", "read_only": true}), |
| 298 | &context, |
| 299 | ) |
| 300 | .await |
| 301 | .unwrap_err(); |
| 302 | assert!( |
| 303 | sh_heredoc.to_string().contains("/bin/zsh -c"), |
| 304 | "{sh_heredoc}" |
| 305 | ); |
| 306 | } |
| 307 | let refused = LowercaseBashTool |
| 308 | .execute( |
| 309 | json!({"command": "printf x > peer.txt", "read_only": true}), |
| 310 | &context, |
| 311 | ) |
| 312 | .await; |
| 313 | assert!(!tmp.path().join("peer.txt").exists(), "{refused:?}"); |
| 314 | let error = refused.expect_err("workspace write must fail"); |
| 315 | let message = error.to_string(); |
| 316 | assert!(message.contains("private TMPDIR"), "{message}"); |
| 317 | let metadata = error.metadata().expect("failure metadata"); |
| 318 | assert!(metadata.get("sandbox_denied_hint").is_some()); |
| 319 | assert!(metadata.get("sandbox_network_restricted").is_none()); |
| 320 | eprintln!( |
| 321 | "NATIVE_READONLY_ENFORCED: private TMPDIR usable and removed; workspace write refused" |
| 322 | ); |
| 323 | } |
| 324 |