use super::common::{RequestInfo, RuleResponse};
use super::{EvaluationResult, RuleEngineTrait};
use async_trait::async_trait;
use hyper::Method;
use serde_json;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::sync::Mutex;
use tracing::{debug, error};
const MAX_RESPONSE_BYTES: usize = 64 * 1024;
async fn read_bounded_line<R: tokio::io::AsyncBufRead + Unpin>(
reader: &mut R,
bytes: &mut Vec<u8>,
) -> std::io::Result<usize> {
loop {
let chunk = reader.fill_buf().await?;
if chunk.is_empty() {
return Ok(bytes.len());
}
let end = chunk
.iter()
.position(|byte| *byte == b'\n')
.map_or(chunk.len(), |pos| pos + 1);
let copy = end.min(MAX_RESPONSE_BYTES + 1 - bytes.len());
let complete = chunk[copy - 1] == b'\n';
bytes.extend_from_slice(&chunk[..copy]);
reader.consume(copy);
if bytes.len() > MAX_RESPONSE_BYTES {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Program response exceeds 64 KiB",
));
}
if complete {
return Ok(bytes.len());
}
}
}
pub struct ProcRuleEngine {
program: String,
process: Arc<Mutex<Option<ProcessState>>>,
restricted: bool,
}
struct ProcessState {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
}
impl ProcRuleEngine {
pub fn new(program: String) -> Self {
ProcRuleEngine {
program,
process: Arc::new(Mutex::new(None)),
restricted: false,
}
}
pub fn restricted(mut self) -> Self {
self.restricted = true;
self
}
#[inline]
fn kill_process(process_state: ProcessState) {
drop(process_state);
}
async fn ensure_process_running(
&self,
process_guard: &mut Option<ProcessState>,
) -> Result<(), String> {
if let Some(mut process_state) = process_guard.take() {
match process_state.child.try_wait() {
Ok(Some(status)) => {
debug!(
"Program process exited with status: {:?}, restarting",
status
);
Self::kill_process(process_state);
}
Ok(None) => {
*process_guard = Some(process_state);
return Ok(());
}
Err(e) => {
error!("Failed to check process status: {}, restarting", e);
Self::kill_process(process_state);
}
}
}
if process_guard.is_none() {
debug!("Starting program process: {}", self.program);
let mut cmd = if self.restricted {
let mut cmd = Command::new("/usr/bin/setpriv");
cmd.args([
"--no-new-privs",
"--reuid=65534",
"--regid=65534",
"--clear-groups",
"--",
&self.program,
]);
cmd
} else {
Command::new(&self.program)
};
if self.restricted {
cmd.env_clear().env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin");
}
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
let mut child = cmd
.spawn()
.map_err(|e| format!("Failed to spawn program: {}", e))?;
let stdin = child
.stdin
.take()
.ok_or_else(|| "Failed to get stdin handle".to_string())?;
let stdout = child
.stdout
.take()
.ok_or_else(|| "Failed to get stdout handle".to_string())?;
*process_guard = Some(ProcessState {
child,
stdin,
stdout: BufReader::new(stdout),
});
}
Ok(())
}
async fn send_request_to_process(
&self,
process_guard: &mut Option<ProcessState>,
json_request: &str,
) -> Result<(bool, Option<String>, Option<u64>), String> {
self.ensure_process_running(process_guard).await?;
let process_state = process_guard
.as_mut()
.ok_or_else(|| "Process not available after ensure_process_running".to_string())?;
let mut request_line = json_request.to_string();
request_line.push('\n');
let timeout = Duration::from_secs(5);
match tokio::time::timeout(timeout, async {
process_state
.stdin
.write_all(request_line.as_bytes())
.await?;
process_state.stdin.flush().await
})
.await
{
Ok(Ok(())) => {}
Ok(Err(e)) => {
error!("Failed to write to program stdin: {}", e);
if let Some(state) = process_guard.take() {
Self::kill_process(state);
}
return Err("Failed to write to program".to_string());
}
Err(_) => {
debug!("Program stdin timeout after {:?}", timeout);
if let Some(state) = process_guard.take() {
Self::kill_process(state);
}
return Err("Program stdin timeout".to_string());
}
}
let mut response_bytes = Vec::new();
let read = read_bounded_line(&mut process_state.stdout, &mut response_bytes);
match tokio::time::timeout(timeout, read).await {
Ok(Ok(0)) => {
debug!("Program closed stdout unexpectedly");
if let Some(state) = process_guard.take() {
Self::kill_process(state);
}
Err("Program closed unexpectedly".to_string())
}
Ok(Ok(_)) => {
let response_line = String::from_utf8_lossy(&response_bytes);
let response = response_line.trim();
debug!("Program response: {}", response);
if response.is_empty() {
error!("Program returned empty response - killing process");
if let Some(state) = process_guard.take() {
Self::kill_process(state);
}
return Err("Program returned empty response".to_string());
}
let rule_response = RuleResponse::from_string(response);
let (allowed, message, max_tx_bytes) = rule_response.to_evaluation_result();
Ok((allowed, message, max_tx_bytes))
}
Ok(Err(e)) => {
error!("Error reading from program: {}", e);
if let Some(state) = process_guard.take() {
Self::kill_process(state);
}
Err(format!("Error reading from program: {}", e))
}
Err(_) => {
debug!("Program response timeout after {:?}", timeout);
if let Some(state) = process_guard.take() {
Self::kill_process(state);
}
Err("Program response timeout".to_string())
}
}
}
async fn execute_program(
&self,
method: Method,
url: &str,
requester_ip: &str,
) -> EvaluationResult {
let request_info = match RequestInfo::from_request(&method, url, requester_ip) {
Ok(info) => info,
Err(e) => {
debug!("Failed to parse request: {}", e);
return EvaluationResult::deny().with_context(e);
}
};
let json_request = match serde_json::to_string(&request_info) {
Ok(json) => json,
Err(e) => {
error!("Failed to serialize request: {}", e);
return EvaluationResult::deny()
.with_context("Program evaluation failed".to_string());
}
};
let mut process_guard = self.process.lock().await;
for attempt in 0..2 {
debug!(
"Sending request to program for {} {} from {} (attempt {})",
method,
url,
requester_ip,
attempt + 1
);
match self
.send_request_to_process(&mut process_guard, &json_request)
.await
{
Ok((allowed, message, max_tx_bytes)) => {
if allowed {
debug!("ALLOW: {} {} (program allowed)", method, url);
let mut result = EvaluationResult::allow();
if let Some(msg) = message {
result = result.with_context(msg);
}
if let Some(bytes) = max_tx_bytes {
result = result.with_max_tx_bytes(bytes);
}
return result;
} else {
debug!("DENY: {} {} (program denied)", method, url);
return match message {
Some(msg) => EvaluationResult::deny().with_context(msg),
None => EvaluationResult::deny(),
};
}
}
Err(e) => {
debug!("Request failed: {}", e);
if e == "Program stdin timeout" || e == "Program response timeout" {
return EvaluationResult::deny()
.with_context("Program evaluation timed out".to_string());
}
if attempt == 0 {
debug!("Retrying with fresh process");
}
}
}
}
EvaluationResult::deny().with_context("Program evaluation failed".to_string())
}
}
#[async_trait]
impl RuleEngineTrait for ProcRuleEngine {
async fn evaluate(&self, method: Method, url: &str, requester_ip: &str) -> EvaluationResult {
self.execute_program(method, url, requester_ip).await
}
fn name(&self) -> &str {
"proc"
}
}
impl Drop for ProcRuleEngine {
fn drop(&mut self) {
if let Ok(mut guard) = self.process.try_lock() {
if let Some(process_state) = guard.take() {
Self::kill_process(process_state);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rules::Action;
use std::fs;
use std::io::Write;
use tempfile::{NamedTempFile, TempPath};
#[tokio::test]
async fn unterminated_processor_response_is_bounded() {
let mut reader = BufReader::new(tokio::io::repeat(b'x'));
let mut bytes = Vec::new();
let error = read_bounded_line(&mut reader, &mut bytes)
.await
.unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
assert_eq!(bytes.len(), MAX_RESPONSE_BYTES + 1);
let mut reader = BufReader::new(&b"true\nfalse\n"[..]);
bytes.clear();
read_bounded_line(&mut reader, &mut bytes).await.unwrap();
assert_eq!(bytes, b"true\n");
bytes.clear();
read_bounded_line(&mut reader, &mut bytes).await.unwrap();
assert_eq!(bytes, b"false\n");
}
fn create_program_file(content: &str) -> TempPath {
let mut program_file = NamedTempFile::new().unwrap();
program_file.write_all(content.as_bytes()).unwrap();
program_file.flush().unwrap();
let program_path = program_file.into_temp_path();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&program_path).unwrap().permissions();
perms.set_mode(0o755);
fs::set_permissions(&program_path, perms).unwrap();
}
program_path
}
#[tokio::test]
async fn test_simple_allow() {
let program = r#"#!/bin/bash
while IFS= read -r line; do
echo "true"
done
"#;
let program_path = create_program_file(program);
let engine = ProcRuleEngine::new(program_path.to_str().unwrap().to_string());
let result = engine
.evaluate(Method::GET, "https://example.com/test", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
let result = engine
.evaluate(Method::POST, "https://github.com/api", "192.168.1.1")
.await;
assert!(matches!(result.action, Action::Allow));
drop(program_path);
}
#[tokio::test]
async fn test_json_filter() {
let program = r#"#!/usr/bin/env python3
import json
import sys
for line in sys.stdin:
try:
request = json.loads(line)
if request.get('host') == 'github.com':
print('true')
else:
print('false')
sys.stdout.flush()
except:
print('false')
sys.stdout.flush()
"#;
let program_path = create_program_file(program);
let engine = ProcRuleEngine::new(program_path.to_str().unwrap().to_string());
let result = engine
.evaluate(Method::GET, "https://github.com/test", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
let result = engine
.evaluate(Method::GET, "https://example.com/test", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Deny));
drop(program_path);
}
#[tokio::test]
async fn test_json_response() {
let program = r#"#!/usr/bin/env python3
import json
import sys
for line in sys.stdin:
try:
request = json.loads(line)
if 'blocked' in request.get('host', ''):
response = {'allow': False, 'deny_message': f"Host {request['host']} is blocked"}
else:
response = {'allow': True}
print(json.dumps(response))
sys.stdout.flush()
except Exception as e:
print(json.dumps({'allow': False, 'deny_message': str(e)}))
sys.stdout.flush()
"#;
let program_path = create_program_file(program);
let engine = ProcRuleEngine::new(program_path.to_str().unwrap().to_string());
let result = engine
.evaluate(Method::GET, "https://example.com/test", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
assert_eq!(result.context, None);
let result = engine
.evaluate(Method::GET, "https://blocked.com/test", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Deny));
assert_eq!(
result.context,
Some("Host blocked.com is blocked".to_string())
);
drop(program_path);
}
#[tokio::test]
async fn test_restart_on_exit() {
let program = r#"#!/usr/bin/env python3
import json
import sys
# Read exactly one line, respond, then exit
line = sys.stdin.readline()
request = json.loads(line.strip())
# Simple response to verify process restart works
response = {"allow": True, "deny_message": f"Handled {request['path']}"}
print(json.dumps(response))
sys.stdout.flush()
sys.exit(0) # Always exit after handling one request
"#;
let program_path = create_program_file(program);
let engine = ProcRuleEngine::new(program_path.to_str().unwrap().to_string());
let result = engine
.evaluate(Method::GET, "https://example.com/1", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
let result = engine
.evaluate(Method::GET, "https://example.com/2", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
drop(program_path);
}
#[tokio::test]
async fn test_stateful_process() {
let program = r#"#!/usr/bin/env python3
import json
import sys
request_count = 0
for line in sys.stdin:
request_count += 1
request = json.loads(line.strip())
# Only allow requests to {request_count}.com
expected_host = f"{request_count}.com"
if request['host'] == expected_host:
response = {"allow": True}
else:
response = {"allow": False, "deny_message": f"Request {request_count}: Expected {expected_host}, got {request['host']}"}
print(json.dumps(response))
sys.stdout.flush()
"#;
let program_path = create_program_file(program);
let engine = ProcRuleEngine::new(program_path.to_str().unwrap().to_string());
let mut total_requests = 0;
for _ in 1..=10 {
total_requests += 1;
let allowed_url = format!("https://{}.com/test", total_requests);
let result = engine
.evaluate(Method::GET, &allowed_url, "127.0.0.1")
.await;
assert!(
matches!(result.action, Action::Allow),
"Request {} to {}.com should be allowed",
total_requests,
total_requests
);
total_requests += 1;
let denied_url = "https://wrong.com/test";
let result = engine.evaluate(Method::GET, denied_url, "127.0.0.1").await;
assert!(
matches!(result.action, Action::Deny),
"Request {} to wrong.com should be denied",
total_requests
);
assert!(
result
.context
.as_ref()
.is_some_and(|msg| msg.contains(&format!("Request {}", total_requests))),
"Deny message should indicate this is request {} in the process",
total_requests
);
}
let result = engine
.evaluate(Method::GET, "https://21.com/test", "127.0.0.1")
.await;
assert!(
matches!(result.action, Action::Allow),
"Request 21 to 21.com should be allowed"
);
let result = engine
.evaluate(Method::GET, "https://1.com/test", "127.0.0.1")
.await;
assert!(
matches!(result.action, Action::Deny),
"Request 22 should deny 1.com (expecting 22.com)"
);
assert!(
result
.context
.as_ref()
.is_some_and(|msg| msg.contains("Request 22")),
"Should indicate this is request 22 in the process lifecycle"
);
drop(program_path);
}
#[tokio::test]
async fn test_killed_on_empty_response() {
let program = r#"#!/usr/bin/env python3
import sys
counter = 0
for line in sys.stdin:
counter += 1
if counter == 1:
print('true')
elif counter == 2:
print('') # Empty response - should cause process to be killed
else:
print('false') # After restart
sys.stdout.flush()
"#;
let program_path = create_program_file(program);
let engine = ProcRuleEngine::new(program_path.to_str().unwrap().to_string());
let result = engine
.evaluate(Method::GET, "https://example.com/1", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
let result = engine
.evaluate(Method::GET, "https://example.com/2", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
let result = engine
.evaluate(Method::GET, "https://example.com/3", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
drop(program_path);
}
}