microsandbox 0.5.8

`microsandbox` is the core library for the microsandbox project.
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
//! Integration tests for secret substitution through HTTP CONNECT tunnels.

use std::io;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;

use microsandbox::{NetworkPolicy, Sandbox};
use rcgen::CertificateParams;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use test_utils::msb_test;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::JoinHandle;
use tokio_rustls::TlsAcceptor;

// Constants

const CURL_IMAGE: &str = "mirror.gcr.io/curlimages/curl";
const REAL_SECRET: &str = "real-secret-connect";
const PLACEHOLDER: &str = "MSB_API_KEY";

// Types

/// Minimal HTTP CONNECT proxy that splices one tunnelled connection.
struct ConnectProxy {
    port: u16,
    handle: Option<JoinHandle<io::Result<()>>>,
}

/// Minimal HTTPS server that records the Authorization header of one request.
struct TargetHttps {
    port: u16,
    handle: Option<JoinHandle<io::Result<String>>>,
}

/// Minimal proxy fixture that records a `Proxy-Authorization` CONNECT header.
struct ProxyAuthCapture {
    port: u16,
    handle: Option<JoinHandle<io::Result<Option<String>>>>,
}

// Methods

impl ConnectProxy {
    async fn start(target_port: u16) -> io::Result<Self> {
        let v4 = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).await?;
        let port = v4.local_addr()?.port();
        let v6 = TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))).await?;

        let handle = tokio::spawn(async move {
            let (client, _) = tokio::select! {
                a = v4.accept() => a?,
                a = v6.accept() => a?,
            };
            handle_connect(client, target_port).await
        });

        Ok(Self {
            port,
            handle: Some(handle),
        })
    }

    fn port(&self) -> u16 {
        self.port
    }

    async fn join(&mut self) -> io::Result<()> {
        self.handle
            .take()
            .expect("proxy fixture already consumed")
            .await
            .map_err(io::Error::other)?
    }
}

impl Drop for ConnectProxy {
    fn drop(&mut self) {
        if let Some(h) = self.handle.take() {
            h.abort();
        }
    }
}

impl TargetHttps {
    async fn start() -> io::Result<Self> {
        let v4 = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).await?;
        let port = v4.local_addr()?.port();
        let v6 = TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))).await?;
        let acceptor = TlsAcceptor::from(test_server_tls_config());

        let handle = tokio::spawn(async move {
            let (stream, _) = tokio::select! {
                a = v4.accept() => a?,
                a = v6.accept() => a?,
            };
            let tls = acceptor.accept(stream).await?;
            received_auth_header(tls).await
        });

        Ok(Self {
            port,
            handle: Some(handle),
        })
    }

    fn port(&self) -> u16 {
        self.port
    }

    async fn received_auth(&mut self) -> io::Result<String> {
        self.handle
            .take()
            .expect("target fixture already consumed")
            .await
            .map_err(io::Error::other)?
    }
}

impl Drop for TargetHttps {
    fn drop(&mut self) {
        if let Some(h) = self.handle.take() {
            h.abort();
        }
    }
}

impl ProxyAuthCapture {
    async fn start() -> io::Result<Self> {
        let v4 = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).await?;
        let port = v4.local_addr()?.port();
        let v6 = TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))).await?;

        let handle = tokio::spawn(async move {
            let (client, _) = tokio::select! {
                a = v4.accept() => a?,
                a = v6.accept() => a?,
            };
            read_proxy_auth_header(client).await
        });

        Ok(Self {
            port,
            handle: Some(handle),
        })
    }

    fn port(&self) -> u16 {
        self.port
    }

    async fn try_received_auth(&mut self, timeout: std::time::Duration) -> Option<String> {
        let handle = self.handle.take().expect("proxy fixture already consumed");
        match tokio::time::timeout(timeout, handle).await {
            Ok(joined) => joined.ok().and_then(|res| res.ok()).flatten(),
            Err(_) => None,
        }
    }
}

impl Drop for ProxyAuthCapture {
    fn drop(&mut self) {
        if let Some(h) = self.handle.take() {
            h.abort();
        }
    }
}

// Functions

async fn handle_connect(client: TcpStream, target_port: u16) -> io::Result<()> {
    let (read_half, write_half) = client.into_split();
    let mut reader = BufReader::new(read_half);

    let mut request_line = String::new();
    reader.read_line(&mut request_line).await?;
    let target = parse_connect_target(&request_line).ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("expected CONNECT request, got: {request_line:?}"),
        )
    })?;

    loop {
        let mut line = String::new();
        reader.read_line(&mut line).await?;
        if line == "\r\n" || line.is_empty() {
            break;
        }
    }

    // host.microsandbox.internal only resolves inside the VM; rewrite to loopback.
    let connect_addr = if target.starts_with("host.microsandbox.internal:") {
        format!("127.0.0.1:{target_port}")
    } else {
        target
    };

    let mut upstream = TcpStream::connect(&connect_addr).await?;
    let buffered_client_bytes = reader.buffer().to_vec();

    let mut client_write = write_half;
    client_write
        .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
        .await?;
    if !buffered_client_bytes.is_empty() {
        upstream.write_all(&buffered_client_bytes).await?;
    }

    let mut client_read = reader.into_inner();
    let (mut up_read, mut up_write) = upstream.into_split();

    let client_to_upstream = tokio::io::copy(&mut client_read, &mut up_write);
    let upstream_to_client = tokio::io::copy(&mut up_read, &mut client_write);
    tokio::pin!(client_to_upstream);
    tokio::pin!(upstream_to_client);

    tokio::select! {
        result = &mut client_to_upstream => {
            result?;
        }
        result = &mut upstream_to_client => {
            result?;
        }
    }

    Ok(())
}

fn parse_connect_target(line: &str) -> Option<String> {
    let mut parts = line.split_whitespace();
    let method = parts.next()?;
    let target = parts.next()?;
    if !method.eq_ignore_ascii_case("CONNECT") {
        return None;
    }
    Some(target.to_string())
}

async fn read_proxy_auth_header(client: TcpStream) -> io::Result<Option<String>> {
    let mut reader = BufReader::new(client);
    let mut proxy_auth = None;

    loop {
        let mut line = String::new();
        reader.read_line(&mut line).await?;
        let trimmed = line.trim_end_matches(['\r', '\n']);
        if trimmed.is_empty() {
            break;
        }
        if let Some((name, value)) = trimmed.split_once(':')
            && name.eq_ignore_ascii_case("proxy-authorization")
        {
            proxy_auth = Some(value.trim().to_string());
        }
    }

    reader
        .into_inner()
        .write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 0\r\n\r\n")
        .await?;

    Ok(proxy_auth)
}

async fn received_auth_header(
    mut stream: tokio_rustls::server::TlsStream<TcpStream>,
) -> io::Result<String> {
    let mut buf = Vec::new();
    loop {
        let mut chunk = [0u8; 4096];
        let n = stream.read(&mut chunk).await?;
        if n == 0 {
            break;
        }
        buf.extend_from_slice(&chunk[..n]);
        if buf.windows(4).any(|w| w == b"\r\n\r\n") {
            break;
        }
    }

    let headers = String::from_utf8_lossy(&buf);
    let auth = headers
        .lines()
        .find_map(|line| {
            let (name, value) = line.split_once(':')?;
            name.eq_ignore_ascii_case("authorization")
                .then(|| value.trim().to_string())
        })
        .unwrap_or_default();

    stream
        .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
        .await?;
    stream.shutdown().await?;

    Ok(auth)
}

fn test_server_tls_config() -> Arc<rustls::ServerConfig> {
    let _ = rustls::crypto::ring::default_provider().install_default();
    let key_pair = rcgen::KeyPair::generate().expect("generate key");
    let params = CertificateParams::new(vec!["host.microsandbox.internal".to_string()])
        .expect("cert params");
    let cert = params.self_signed(&key_pair).expect("self-sign cert");
    let chain = vec![CertificateDer::from(cert.der().to_vec())];
    let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der()));
    Arc::new(
        rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(chain, key)
            .expect("server config"),
    )
}

async fn teardown(sb: Sandbox, name: &str) {
    let _ = sb.stop().await;
    let _ = Sandbox::remove(name).await;
}

// Tests

#[msb_test]
async fn https_connect_proxy_substitutes_secret_in_authorization_header() {
    let _ = rustls::crypto::ring::default_provider().install_default();

    let mut target = TargetHttps::start().await.expect("target fixture");
    let target_port = target.port();
    let mut proxy = ConnectProxy::start(target_port)
        .await
        .expect("proxy fixture");
    let proxy_port = proxy.port();
    let name = "http-connect-secret-auth";

    let sb = Sandbox::builder(name)
        .image(CURL_IMAGE)
        .cpus(1)
        .memory(256)
        .user("0")
        .replace()
        .secret(|s| {
            s.env("API_KEY")
                .value(REAL_SECRET)
                .allow_host("host.microsandbox.internal")
        })
        .network(|n| {
            n.policy(NetworkPolicy::allow_all()).tls(|t| {
                t.intercepted_ports(vec![target_port])
                    .verify_upstream(false)
            })
        })
        .create()
        .await
        .expect("create sandbox");

    let out = sb
        .shell(format!(
            r#"curl -k --http1.1 -m 30 -sS -o /dev/null \
  -w 'code=%{{http_code}}' \
  -H "Authorization: Bearer $API_KEY" \
  --proxytunnel \
  --proxy http://host.microsandbox.internal:{proxy_port} \
  https://host.microsandbox.internal:{target_port}/api"#
        ))
        .await
        .expect("curl through connect proxy");

    let stdout = out.stdout().unwrap_or_default();
    if !stdout.contains("code=200") {
        let proxy_status = tokio::time::timeout(std::time::Duration::from_secs(3), proxy.join())
            .await
            .map_err(|_| "proxy timed out".to_string())
            .and_then(|res| res.map_err(|err| err.to_string()));
        let target_auth =
            tokio::time::timeout(std::time::Duration::from_secs(3), target.received_auth())
                .await
                .map_err(|_| "target timed out".to_string())
                .and_then(|res| res.map_err(|err| err.to_string()));
        panic!(
            "expected 200 from target, got: {stdout} (stderr: {}), proxy={proxy_status:?}, target={target_auth:?}",
            out.stderr().unwrap_or_default()
        );
    }

    let auth = target.received_auth().await.expect("target auth");
    assert_eq!(
        auth,
        format!("Bearer {REAL_SECRET}"),
        "proxy must substitute placeholder in tunnelled HTTPS request; got: {auth:?}"
    );

    let _ = proxy.join().await;
    teardown(sb, name).await;
}

#[msb_test]
async fn https_connect_proxy_blocks_secret_for_wrong_host() {
    let _ = rustls::crypto::ring::default_provider().install_default();

    let mut target = TargetHttps::start().await.expect("target fixture");
    let target_port = target.port();
    let proxy = ConnectProxy::start(target_port)
        .await
        .expect("proxy fixture");
    let proxy_port = proxy.port();
    let name = "http-connect-secret-wrong-host";

    let sb = Sandbox::builder(name)
        .image(CURL_IMAGE)
        .cpus(1)
        .memory(256)
        .user("0")
        .replace()
        .secret(|s| {
            s.env("API_KEY")
                .value(REAL_SECRET)
                .allow_host("api.allowed.test")
        })
        .network(|n| {
            n.policy(NetworkPolicy::allow_all()).tls(|t| {
                t.intercepted_ports(vec![target_port])
                    .verify_upstream(false)
            })
        })
        .create()
        .await
        .expect("create sandbox");

    let out = sb
        .shell(format!(
            r#"set +e
curl -k --http1.1 -m 10 -sS -o /dev/null \
  -w 'code=%{{http_code}}' \
  -H "Authorization: Bearer $API_KEY" \
  --proxytunnel \
  --proxy http://host.microsandbox.internal:{proxy_port} \
  https://host.microsandbox.internal:{target_port}/api
echo "status=$?"
"#
        ))
        .await
        .expect("curl wrong host");

    let stdout = out.stdout().unwrap_or_default();
    if stdout.trim_end().ends_with("status=0") {
        let auth =
            tokio::time::timeout(std::time::Duration::from_secs(5), target.received_auth()).await;
        let auth_val = match auth {
            Ok(Ok(a)) => a,
            _ => String::new(),
        };
        panic!(
            "expected curl to fail when secret host does not match tunnel target; got: {stdout:?}; target auth: {auth_val:?}"
        );
    }

    let auth =
        tokio::time::timeout(std::time::Duration::from_secs(5), target.received_auth()).await;
    let auth_val = match auth {
        Ok(Ok(a)) => a,
        _ => String::new(),
    };
    assert!(
        !auth_val.contains(REAL_SECRET) && !auth_val.contains(PLACEHOLDER),
        "real secret must not reach target when host does not match; got: {auth_val:?}"
    );

    drop(proxy);
    teardown(sb, name).await;
}

#[msb_test]
async fn https_connect_proxy_leaves_non_intercepted_target_port_opaque() {
    let _ = rustls::crypto::ring::default_provider().install_default();

    let mut target = TargetHttps::start().await.expect("target fixture");
    let target_port = target.port();
    let mut proxy = ConnectProxy::start(target_port)
        .await
        .expect("proxy fixture");
    let proxy_port = proxy.port();
    let intercepted_port = if target_port == 443 { 444 } else { 443 };
    let name = "http-connect-secret-non-intercepted";

    let sb = Sandbox::builder(name)
        .image(CURL_IMAGE)
        .cpus(1)
        .memory(256)
        .user("0")
        .replace()
        .secret(|s| {
            s.env("API_KEY")
                .value(REAL_SECRET)
                .allow_host("host.microsandbox.internal")
        })
        .network(|n| {
            n.policy(NetworkPolicy::allow_all()).tls(|t| {
                t.intercepted_ports(vec![intercepted_port])
                    .verify_upstream(false)
            })
        })
        .create()
        .await
        .expect("create sandbox");

    let out = sb
        .shell(format!(
            r#"curl -k --http1.1 -m 30 -sS -o /dev/null \
  -w 'code=%{{http_code}}' \
  -H "Authorization: Bearer $API_KEY" \
  --proxytunnel \
  --proxy http://host.microsandbox.internal:{proxy_port} \
  https://host.microsandbox.internal:{target_port}/api"#
        ))
        .await
        .expect("curl through connect proxy");

    let stdout = out.stdout().unwrap_or_default();
    if !stdout.contains("code=200") {
        let proxy_status = tokio::time::timeout(std::time::Duration::from_secs(3), proxy.join())
            .await
            .map_err(|_| "proxy timed out".to_string())
            .and_then(|res| res.map_err(|err| err.to_string()));
        let target_auth =
            tokio::time::timeout(std::time::Duration::from_secs(3), target.received_auth())
                .await
                .map_err(|_| "target timed out".to_string())
                .and_then(|res| res.map_err(|err| err.to_string()));
        panic!(
            "expected 200 from opaque target tunnel, got: {stdout} (stderr: {}), proxy={proxy_status:?}, target={target_auth:?}",
            out.stderr().unwrap_or_default()
        );
    }

    let auth = target.received_auth().await.expect("target auth");
    assert!(
        auth.contains(PLACEHOLDER),
        "non-intercepted target port must receive the placeholder unchanged; got: {auth:?}"
    );
    assert!(
        !auth.contains(REAL_SECRET),
        "non-intercepted target port must not receive the real secret; got: {auth:?}"
    );

    let _ = proxy.join().await;
    teardown(sb, name).await;
}

#[msb_test]
async fn https_connect_proxy_blocks_secret_in_outer_connect_headers() {
    let mut proxy = ProxyAuthCapture::start()
        .await
        .expect("proxy capture fixture");
    let proxy_port = proxy.port();
    let name = "http-connect-secret-outer-header";

    let sb = Sandbox::builder(name)
        .image(CURL_IMAGE)
        .cpus(1)
        .memory(256)
        .user("0")
        .replace()
        .secret(|s| {
            s.env("API_KEY")
                .value(REAL_SECRET)
                .allow_host("host.microsandbox.internal")
        })
        .network(|n| n.policy(NetworkPolicy::allow_all()))
        .create()
        .await
        .expect("create sandbox");

    let out = sb
        .shell(format!(
            r#"set +e
curl -k --http1.1 -m 10 -sS -o /dev/null \
  --proxytunnel \
  --proxy http://host.microsandbox.internal:{proxy_port} \
  --proxy-header "Proxy-Authorization: Bearer $API_KEY" \
  https://example.com/
echo "status=$?"
"#
        ))
        .await
        .expect("curl through connect proxy");

    let stdout = out.stdout().unwrap_or_default();
    assert!(
        !stdout.trim_end().ends_with("status=0"),
        "expected curl to fail when the outer CONNECT header carries a protected placeholder; got: {stdout:?}"
    );

    let proxy_auth = proxy
        .try_received_auth(std::time::Duration::from_secs(5))
        .await
        .unwrap_or_default();
    assert!(
        !proxy_auth.contains(PLACEHOLDER) && !proxy_auth.contains(REAL_SECRET),
        "CONNECT proxy must not receive a raw placeholder or real secret in outer headers; got: {proxy_auth:?}"
    );

    teardown(sb, name).await;
}