httpjail 0.6.2

Monitor and restrict HTTP/HTTPS requests from processes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
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,
}

/// State for a running process
/// When dropped, the child process is automatically killed due to kill_on_drop(true)
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
    }

    /// Explicitly kill a process by taking ownership and dropping it
    /// This is more self-documenting than relying on implicit drops
    #[inline]
    fn kill_process(process_state: ProcessState) {
        // The process is killed when ProcessState is dropped due to kill_on_drop(true)
        drop(process_state);
    }

    /// Ensure a process is running, restarting if necessary
    /// Takes a mutable reference to the guard to avoid multiple lock acquisitions
    async fn ensure_process_running(
        &self,
        process_guard: &mut Option<ProcessState>,
    ) -> Result<(), String> {
        // Check if existing process is still alive
        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 is still running, put it back
                    *process_guard = Some(process_state);
                    return Ok(());
                }
                Err(e) => {
                    error!("Failed to check process status: {}, restarting", e);
                    Self::kill_process(process_state);
                }
            }
        }

        // Start new process if needed
        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); // Ensures process is killed when Child is dropped

            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(())
    }

    /// Send a request to the program and get a response
    /// Returns Err if the process needs to be restarted
    async fn send_request_to_process(
        &self,
        process_guard: &mut Option<ProcessState>,
        json_request: &str,
    ) -> Result<(bool, Option<String>, Option<u64>), String> {
        // Ensure we have a running process
        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())?;

        // Send request
        let mut request_line = json_request.to_string();
        request_line.push('\n');

        let timeout = Duration::from_secs(5);
        // A stopped processor can fill its stdin pipe before we start the
        // response timeout. Bound writes and flushes by the same deadline.
        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());
            }
        }

        // Bound both wait time and memory even when the processor never sends a newline.
        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)) => {
                // EOF - process exited
                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);

                // Check for empty or whitespace-only response - this is malformed
                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());
                }

                // Parse response
                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;

        // Try twice: once normally, and once after restart if any error occurs
        for attempt in 0..2 {
            debug!(
                "Sending request to program for {} {} from {} (attempt {})",
                method,
                url,
                requester_ip,
                attempt + 1
            );

            // Try to get a response from the process
            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" {
                        // An unresponsive processor must not hold the shared mutex
                        // through another full timeout for the same request.
                        return EvaluationResult::deny()
                            .with_context("Program evaluation timed out".to_string());
                    }
                    if attempt == 0 {
                        debug!("Retrying with fresh process");
                        // Process will be restarted on next iteration by send_request_to_process
                    }
                }
            }
        }

        // Both attempts failed
        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() {
                // Explicitly kill the process on drop
                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");
    }

    /// Helper function to create an executable program file with the given content
    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() {
        // Program that exits after every request
        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());

        // First request - process starts, responds, and exits
        let result = engine
            .evaluate(Method::GET, "https://example.com/1", "127.0.0.1")
            .await;
        assert!(matches!(result.action, Action::Allow));

        // Second request - verifies that after process exit, a new process is started
        // automatically without any delay or error
        let result = engine
            .evaluate(Method::GET, "https://example.com/2", "127.0.0.1")
            .await;
        assert!(matches!(result.action, Action::Allow));

        // Both requests should succeed, proving that process restart is seamless
        drop(program_path);
    }

    #[tokio::test]
    async fn test_stateful_process() {
        // Test that process stays alive and maintains state across multiple requests
        // Each request N only allows domain N.com
        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());

        // Make 10 iterations testing sequential numbering
        let mut total_requests = 0;
        for _ in 1..=10 {
            // Test allowed domain - each request N only allows N.com
            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
            );

            // Test denied domain - wrong number should be denied
            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
            );
        }

        // Final test: verify the process is still using the same instance
        // After 20 requests (10 iterations * 2), request 21 should only allow 21.com
        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"
        );

        // Request 22 should expect 22.com
        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() {
        // Program that returns empty response on second request
        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());

        // First request - should work
        let result = engine
            .evaluate(Method::GET, "https://example.com/1", "127.0.0.1")
            .await;
        assert!(matches!(result.action, Action::Allow));

        // Second request - empty response should kill process and retry succeeds
        let result = engine
            .evaluate(Method::GET, "https://example.com/2", "127.0.0.1")
            .await;
        assert!(matches!(result.action, Action::Allow)); // Retry gets 'true' from fresh process

        // Third request - should be second request in new process (which returns empty)
        // Then retries and gets 'true' from yet another fresh process
        let result = engine
            .evaluate(Method::GET, "https://example.com/3", "127.0.0.1")
            .await;
        assert!(matches!(result.action, Action::Allow)); // Gets empty, retries, gets 'true' from fresh

        drop(program_path);
    }
}