feat(security): Add Phase 1 security features

* test: add comprehensive recovery tests for agent loop

Add recovery test coverage for all edge cases and failure scenarios
in the agentic loop, addressing the missing test coverage for
recovery use cases.

Tool Call Parsing Edge Cases:
- Empty tool_result tags
- Empty tool_calls arrays
- Whitespace-only tool names
- Empty string arguments

History Management:
- Trimming without system prompt
- Role ordering consistency after trim
- Only system prompt edge case

Arguments Parsing:
- Invalid JSON string fallback
- None arguments handling
- Null value handling

JSON Extraction:
- Empty input handling
- Whitespace only input
- Multiple JSON objects
- JSON arrays

Tool Call Value Parsing:
- Missing name field
- Non-OpenAI format
- Empty tool_calls array
- Missing tool_calls field fallback
- Top-level array format

Constants Validation:
- MAX_TOOL_ITERATIONS bounds (prevent runaway loops)
- MAX_HISTORY_MESSAGES bounds (prevent memory bloat)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(security): Add Phase 1 security features - sandboxing, resource limits, audit logging

Phase 1 security enhancements with zero impact on the quick setup wizard:
-  Pluggable sandbox trait system (traits.rs)
-  Landlock sandbox support (Linux kernel 5.13+)
-  Firejail sandbox support (Linux user-space)
-  Bubblewrap sandbox support (Linux/macOS user namespaces)
-  Docker sandbox support (container isolation)
-  No-op fallback (application-layer security only)
-  Auto-detection logic (detect.rs)
-  Audit logging with HMAC signing support (audit.rs)
-  SecurityConfig schema (SandboxConfig, ResourceLimitsConfig, AuditConfig)
-  Feature-gated implementation (sandbox-landlock, sandbox-bubblewrap)
-  1,265 tests passing

Key design principles:
- Silent auto-detection: no new prompts in wizard
- Graceful degradation: works on all platforms
- Feature flags: zero overhead when disabled
- Pluggable architecture: swap sandbox backends via config
- Backward compatible: existing configs work unchanged

Config usage:
```toml
[security.sandbox]
enabled = false  # Explicitly disable
backend = "auto"  # auto, landlock, firejail, bubblewrap, docker, none

[security.resources]
max_memory_mb = 512
max_cpu_time_seconds = 60

[security.audit]
enabled = true
log_path = "audit.log"
sign_events = false
```

Security documentation:
- docs/sandboxing.md: Sandbox implementation strategies
- docs/resource-limits.md: Resource limit approaches
- docs/audit-logging.md: Audit logging specification
- docs/security-roadmap.md: 3-phase implementation plan
- docs/frictionless-security.md: Zero-impact wizard design
- docs/agnostic-security.md: Platform/hardware agnostic approach

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Argenis 2026-02-16 04:14:16 -05:00 committed by GitHub
parent 1140a7887d
commit 0383a82a6f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 4129 additions and 13 deletions

122
src/security/firejail.rs Normal file
View file

@ -0,0 +1,122 @@
//! Firejail sandbox (Linux user-space sandboxing)
//!
//! Firejail is a SUID sandbox program that Linux applications use to sandbox themselves.
use crate::security::traits::Sandbox;
use std::process::Command;
/// Firejail sandbox backend for Linux
#[derive(Debug, Clone, Default)]
pub struct FirejailSandbox;
impl FirejailSandbox {
/// Create a new Firejail sandbox
pub fn new() -> std::io::Result<Self> {
if Self::is_installed() {
Ok(Self)
} else {
Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"Firejail not found. Install with: sudo apt install firejail",
))
}
}
/// Probe if Firejail is available (for auto-detection)
pub fn probe() -> std::io::Result<Self> {
Self::new()
}
/// Check if firejail is installed
fn is_installed() -> bool {
Command::new("firejail")
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
}
impl Sandbox for FirejailSandbox {
fn wrap_command(&self, cmd: &mut Command) -> std::io::Result<()> {
// Prepend firejail to the command
let program = cmd.get_program().to_string_lossy().to_string();
let args: Vec<String> = cmd.get_args().map(|s| s.to_string_lossy().to_string()).collect();
// Build firejail wrapper with security flags
let mut firejail_cmd = Command::new("firejail");
firejail_cmd.args([
"--private=home", // New home directory
"--private-dev", // Minimal /dev
"--nosound", // No audio
"--no3d", // No 3D acceleration
"--novideo", // No video devices
"--nowheel", // No input devices
"--notv", // No TV devices
"--noprofile", // Skip profile loading
"--quiet", // Suppress warnings
]);
// Add the original command
firejail_cmd.arg(&program);
firejail_cmd.args(&args);
// Replace the command
*cmd = firejail_cmd;
Ok(())
}
fn is_available(&self) -> bool {
Self::is_installed()
}
fn name(&self) -> &str {
"firejail"
}
fn description(&self) -> &str {
"Linux user-space sandbox (requires firejail to be installed)"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn firejail_sandbox_name() {
assert_eq!(FirejailSandbox.name(), "firejail");
}
#[test]
fn firejail_description_mentions_dependency() {
let desc = FirejailSandbox.description();
assert!(desc.contains("firejail"));
}
#[test]
fn firejail_new_fails_if_not_installed() {
// This will fail unless firejail is actually installed
let result = FirejailSandbox::new();
match result {
Ok(_) => println!("Firejail is installed"),
Err(e) => assert!(e.kind() == std::io::ErrorKind::NotFound || e.kind() == std::io::ErrorKind::Unsupported),
}
}
#[test]
fn firejail_wrap_command_prepends_firejail() {
let sandbox = FirejailSandbox;
let mut cmd = Command::new("echo");
cmd.arg("test");
// Note: wrap_command will fail if firejail isn't installed,
// but we can still test the logic structure
let _ = sandbox.wrap_command(&mut cmd);
// After wrapping, the program should be firejail
if sandbox.is_available() {
assert_eq!(cmd.get_program().to_string_lossy(), "firejail");
}
}
}