eryx 0.7.0

A Python sandbox with async callbacks powered by WebAssembly
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
//! Integration tests for secrets placeholder substitution.
//!
//! These tests require the `embedded` feature and a built runtime.
//! Run with: `mise run test` or `cargo test --features embedded`

#![cfg(feature = "embedded")]
#![allow(clippy::unwrap_used, clippy::expect_used)]

use eryx::{NetConfig, Sandbox};
use std::sync::Arc;
use tokio::sync::Mutex;

/// Mock HTTP server for testing secret substitution.
///
/// Records received requests so we can verify that real secrets were sent.
#[derive(Debug, Default)]
struct MockHttpServer {
    requests: Arc<Mutex<Vec<String>>>,
}

impl MockHttpServer {
    fn new() -> Self {
        Self {
            requests: Arc::new(Mutex::new(Vec::new())),
        }
    }

    async fn start(&self, port: u16) -> tokio::task::JoinHandle<()> {
        let requests = self.requests.clone();
        tokio::spawn(async move {
            let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}"))
                .await
                .expect("Failed to bind mock server");

            while let Ok((mut socket, _)) = listener.accept().await {
                let requests = requests.clone();
                tokio::spawn(async move {
                    use tokio::io::{AsyncReadExt, AsyncWriteExt};
                    let mut buf = vec![0u8; 4096];
                    if let Ok(n) = socket.read(&mut buf).await {
                        buf.truncate(n);
                        if let Ok(request) = String::from_utf8(buf) {
                            requests.lock().await.push(request);

                            // Send minimal HTTP response
                            let response = "HTTP/1.1 200 OK\r\n\
                                          Content-Type: application/json\r\n\
                                          Content-Length: 27\r\n\
                                          \r\n\
                                          {\"message\":\"success\"}";
                            let _ = socket.write_all(response.as_bytes()).await;
                        }
                    }
                });
            }
        })
    }

    async fn get_requests(&self) -> Vec<String> {
        self.requests.lock().await.clone()
    }
}

#[tokio::test]
async fn test_secret_substitution_in_http_request() {
    // Start mock server
    let server = MockHttpServer::new();
    let _handle = server.start(18080).await;
    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

    // Create sandbox with secret
    let sandbox = Sandbox::embedded()
        .with_secret(
            "TEST_API_KEY",
            "real-secret-value-12345",
            vec!["127.0.0.1".to_string()],
        )
        .with_network(NetConfig::permissive()) // Allow localhost for testing
        .scrub_stdout(true)
        .scrub_stderr(true)
        .build()
        .expect("Failed to create sandbox");

    // Execute Python code that makes HTTP request with secret
    let result = sandbox
        .execute(
            r#"
import os
import socket

# Get the secret (will be a placeholder)
api_key = os.environ.get("TEST_API_KEY", "")
print(f"Secret in Python: {api_key}")

# Make HTTP request with the secret in header
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 18080))

request = f"GET /test HTTP/1.1\r\n"
request += "Host: 127.0.0.1\r\n"
request += f"Authorization: Bearer {api_key}\r\n"
request += "\r\n"

sock.send(request.encode())
response = sock.recv(4096).decode()
sock.close()

print(f"Response received: {response[:50]}")
"#,
        )
        .await
        .expect("Failed to execute Python code");

    // Verify placeholder was scrubbed from stdout
    assert!(
        result.stdout.contains("[REDACTED]"),
        "Placeholder should be scrubbed from stdout"
    );
    assert!(
        !result.stdout.contains("ERYX_SECRET_PLACEHOLDER_"),
        "Placeholder should not appear in stdout"
    );
    assert!(
        !result.stdout.contains("real-secret-value-12345"),
        "Real secret should never appear in stdout"
    );

    // Give server time to receive request
    tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

    // Verify the real secret was sent to the server
    let requests = server.get_requests().await;
    assert!(
        !requests.is_empty(),
        "Server should have received a request"
    );

    let first_request = &requests[0];
    assert!(
        first_request.contains("real-secret-value-12345"),
        "Real secret should be in the HTTP request: {}",
        first_request
    );
    assert!(
        first_request.contains("Authorization: Bearer real-secret-value-12345"),
        "Authorization header should contain real secret"
    );
}

#[tokio::test]
async fn test_secret_blocked_for_unauthorized_host() {
    // Create sandbox with secret restricted to specific host
    let sandbox = Sandbox::embedded()
        .with_secret(
            "RESTRICTED_KEY",
            "secret-value",
            vec!["api.example.com".to_string()],
        )
        .with_network(NetConfig::permissive())
        .build()
        .expect("Failed to create sandbox");

    // Try to use secret with unauthorized host - should fail
    let result = sandbox
        .execute(
            r#"
import os
import socket

api_key = os.environ.get("RESTRICTED_KEY", "")

# Try to connect to localhost (not in allowed_hosts)
try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("127.0.0.1", 18081))

    request = f"GET /test HTTP/1.1\r\n"
    request += "Host: 127.0.0.1\r\n"
    request += f"Authorization: Bearer {api_key}\r\n"
    request += "\r\n"

    sock.send(request.encode())
    print("ERROR: Request should have been blocked!")
except Exception as e:
    print(f"Expected error: {e}")
"#,
        )
        .await;

    // The execution itself should succeed, but the secret substitution should fail
    // when the TCP write happens, resulting in an error in the Python code
    assert!(result.is_ok());
    let output = result.unwrap();

    // Should see an error in output (connection refused or similar)
    assert!(
        output.stdout.contains("Expected error") || output.stderr.contains("error"),
        "Should see error when secret is blocked for host"
    );
}

#[tokio::test]
async fn test_placeholder_not_in_stderr() {
    let sandbox = Sandbox::embedded()
        .with_secret("TEST_KEY", "secret", vec![])
        .scrub_stderr(true)
        .build()
        .expect("Failed to create sandbox");

    let result = sandbox
        .execute(
            r#"
import os
import sys

key = os.environ.get("TEST_KEY", "")
sys.stderr.write(f"Error with key: {key}\n")
"#,
        )
        .await
        .expect("Failed to execute");

    // Verify placeholder is scrubbed from stderr
    assert!(
        result.stderr.contains("[REDACTED]"),
        "Placeholder should be scrubbed from stderr"
    );
    assert!(
        !result.stderr.contains("ERYX_SECRET_PLACEHOLDER_"),
        "Placeholder should not appear in stderr"
    );
}

#[tokio::test]
async fn test_multiple_secrets() {
    let sandbox = Sandbox::embedded()
        .with_secret("KEY1", "secret1", vec![])
        .with_secret("KEY2", "secret2", vec![])
        .scrub_stdout(true)
        .build()
        .expect("Failed to create sandbox");

    let result = sandbox
        .execute(
            r#"
import os

key1 = os.environ.get("KEY1", "")
key2 = os.environ.get("KEY2", "")

print(f"Key1: {key1}")
print(f"Key2: {key2}")
"#,
        )
        .await
        .expect("Failed to execute");

    // Both placeholders should be scrubbed
    assert_eq!(
        result.stdout.matches("[REDACTED]").count(),
        2,
        "Both secrets should be scrubbed"
    );
}

#[tokio::test]
async fn test_scrubbing_can_be_disabled() {
    let sandbox = Sandbox::embedded()
        .with_secret("DEBUG_KEY", "debug-secret", vec![])
        .scrub_stdout(false) // Disable scrubbing for debugging
        .build()
        .expect("Failed to create sandbox");

    let result = sandbox
        .execute(
            r#"
import os
key = os.environ.get("DEBUG_KEY", "")
print(f"Debug key: {key}")
"#,
        )
        .await
        .expect("Failed to execute");

    // Placeholder should NOT be scrubbed when disabled
    assert!(
        result.stdout.contains("ERYX_SECRET_PLACEHOLDER_"),
        "Placeholder should appear when scrubbing is disabled"
    );
    assert!(
        !result.stdout.contains("[REDACTED]"),
        "Should not see [REDACTED] when scrubbing is disabled"
    );
}

#[tokio::test]
async fn test_http2_detection() {
    let sandbox = Sandbox::embedded()
        .with_secret("API_KEY", "secret", vec!["example.com".to_string()])
        .with_network(NetConfig::default().allow_host("example.com"))
        .build()
        .expect("Failed to create sandbox");

    // Try to send HTTP/2 preface - should fail with clear error
    let result = sandbox
        .execute(
            r#"
import socket

try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Note: This will fail at DNS/connect level since example.com isn't actually accessible
    # But if we could connect, sending HTTP/2 preface would be caught
    sock.connect(("example.com", 443))

    # HTTP/2 connection preface
    sock.send(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
    print("ERROR: Should have detected HTTP/2!")
except Exception as e:
    print(f"Expected connection error: {e}")
"#,
        )
        .await;

    // Should get connection error (can't actually reach example.com in tests)
    assert!(result.is_ok());
}

/// When result scrubbing is opted into (`scrub_result(true)`), a secret placeholder
/// placed into `result` is redacted and the real secret never appears.
#[tokio::test]
async fn test_placeholder_scrubbed_from_result() {
    let sandbox = Sandbox::embedded()
        .with_secret("TEST_KEY", "supersecret", vec![])
        .scrub_result(true)
        .build()
        .expect("Failed to create sandbox");

    let out = sandbox
        .execute(
            r#"
import os
result = {"leaked": os.environ.get("TEST_KEY", "")}
"#,
        )
        .await
        .expect("Failed to execute");

    let result = out.result.expect("expected a result");
    assert!(
        result.contains("[REDACTED]"),
        "placeholder should be scrubbed from result, got: {result}"
    );
    assert!(
        !result.contains("ERYX_SECRET_PLACEHOLDER_"),
        "raw placeholder must not appear in result: {result}"
    );
    assert!(
        !result.contains("supersecret"),
        "real secret must never appear in result: {result}"
    );
}

/// Result scrubbing is OFF by default (it's a programmatic side channel). Even with
/// stdout scrubbing on, an unscrubbed `result` still carries the placeholder — but
/// never the real secret value (placeholders are substituted only at egress).
#[tokio::test]
async fn test_result_not_scrubbed_by_default() {
    let sandbox = Sandbox::embedded()
        .with_secret("TEST_KEY", "supersecret", vec![])
        .scrub_stdout(true) // stdout scrubbing on, result scrubbing left default (off)
        .build()
        .expect("Failed to create sandbox");

    let out = sandbox
        .execute(
            r#"
import os
result = {"leaked": os.environ.get("TEST_KEY", "")}
"#,
        )
        .await
        .expect("Failed to execute");

    let result = out.result.expect("expected a result");
    assert!(
        result.contains("ERYX_SECRET_PLACEHOLDER_"),
        "placeholder should remain in result when scrub_result is off: {result}"
    );
    assert!(
        !result.contains("[REDACTED]"),
        "result should not be scrubbed by default: {result}"
    );
    assert!(
        !result.contains("supersecret"),
        "real secret must never appear in result regardless of scrubbing: {result}"
    );
}

/// Result scrubbing is governed by its own flag, independent of `scrub_stdout`:
/// with stdout scrubbing OFF but `scrub_result(true)`, the result is still scrubbed.
#[tokio::test]
async fn test_result_scrubbing_independent_of_stdout() {
    let sandbox = Sandbox::embedded()
        .with_secret("TEST_KEY", "supersecret", vec![])
        .scrub_stdout(false)
        .scrub_result(true)
        .build()
        .expect("Failed to create sandbox");

    let out = sandbox
        .execute(
            r#"
import os
print(os.environ.get("TEST_KEY", ""))
result = {"leaked": os.environ.get("TEST_KEY", "")}
"#,
        )
        .await
        .expect("Failed to execute");

    // stdout is NOT scrubbed (placeholder visible), but result IS.
    assert!(
        out.stdout.contains("ERYX_SECRET_PLACEHOLDER_"),
        "stdout should keep the placeholder when scrub_stdout is off: {}",
        out.stdout
    );
    let result = out.result.expect("expected a result");
    assert!(
        result.contains("[REDACTED]"),
        "result should be scrubbed when scrub_result is on: {result}"
    );
    assert!(
        !result.contains("ERYX_SECRET_PLACEHOLDER_"),
        "raw placeholder must not appear in scrubbed result: {result}"
    );
}