workmux 0.1.173

An opinionated workflow tool that orchestrates git worktrees and tmux
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! HTTP CONNECT proxy for domain-based network restrictions.
//!
//! Runs as a host-resident proxy alongside the RPC server. Containers set
//! `HTTPS_PROXY` / `HTTP_PROXY` env vars to route all outbound HTTPS through
//! this proxy. The proxy verifies auth, checks domain allowlist, resolves DNS
//! on the host side (rejecting private IPs), and tunnels traffic.
//!
//! Combined with iptables inside the container (default-deny egress, only
//! allow proxy and RPC ports), this prevents the sandbox from accessing
//! unapproved destinations even if it ignores the proxy env vars.

use anyhow::{Context, Result};
use std::io::{BufRead, BufReader, Write};
use std::net::{IpAddr, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
use tracing::{debug, warn};

use crate::sandbox::rpc::generate_token;

/// Maximum concurrent proxy connections. Matches RPC server cap.
const MAX_CONNECTIONS: usize = 16;

/// Maximum size of the CONNECT request (line + headers).
/// Prevents memory exhaustion from oversized requests.
const MAX_REQUEST_SIZE: usize = 8 * 1024;

/// Timeout for reading the initial CONNECT request (prevents slowloris).
const AUTH_TIMEOUT: Duration = Duration::from_secs(5);

/// Timeout for connecting to the upstream target.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// The only destination port allowed via CONNECT.
const ALLOWED_PORT: u16 = 443;

/// HTTP CONNECT proxy server with domain allowlist and private IP rejection.
pub struct NetworkProxy {
    listener: TcpListener,
    port: u16,
    token: String,
    allowed_domains: Vec<String>,
}

/// Handle to a running proxy server thread.
pub struct ProxyHandle {
    _handle: thread::JoinHandle<()>,
}

impl NetworkProxy {
    /// Bind to a random port on all interfaces (same as RPC server).
    pub fn bind(allowed_domains: &[String]) -> Result<Self> {
        let listener =
            TcpListener::bind("0.0.0.0:0").context("Failed to bind network proxy listener")?;
        let port = listener.local_addr()?.port();
        let token = generate_token();
        debug!(port, "network proxy bound");
        Ok(Self {
            listener,
            port,
            token,
            allowed_domains: allowed_domains.to_vec(),
        })
    }

    /// Get the port the proxy is listening on.
    pub fn port(&self) -> u16 {
        self.port
    }

    /// Get the auth token for this proxy session.
    pub fn token(&self) -> &str {
        &self.token
    }

    /// Spawn the proxy accept loop in a background thread.
    pub fn spawn(self) -> ProxyHandle {
        let ctx = Arc::new(ProxyContext {
            token: self.token,
            allowed_domains: self.allowed_domains,
        });
        let active = Arc::new(AtomicUsize::new(0));

        let handle = thread::spawn(move || {
            for stream in self.listener.incoming() {
                match stream {
                    Ok(stream) => {
                        let current = active.load(Ordering::Relaxed);
                        if current >= MAX_CONNECTIONS {
                            warn!(current, "proxy connection limit reached, dropping");
                            drop(stream);
                            continue;
                        }
                        active.fetch_add(1, Ordering::Relaxed);
                        let ctx = Arc::clone(&ctx);
                        let active = Arc::clone(&active);
                        thread::spawn(move || {
                            if let Err(e) = handle_proxy_connection(stream, &ctx) {
                                debug!(error = %e, "proxy connection ended");
                            }
                            active.fetch_sub(1, Ordering::Relaxed);
                        });
                    }
                    Err(e) => {
                        debug!(error = %e, "proxy accept error, shutting down");
                        break;
                    }
                }
            }
        });

        ProxyHandle { _handle: handle }
    }
}

/// Shared context for proxy connection handlers.
struct ProxyContext {
    token: String,
    allowed_domains: Vec<String>,
}

/// Check if a domain matches a pattern (case-insensitive).
///
/// Supports exact match and wildcard prefix (`*.example.com` matches
/// `foo.example.com` but not `example.com` itself).
fn domain_matches(domain: &str, pattern: &str) -> bool {
    let domain = domain.to_ascii_lowercase();
    let pattern = pattern.to_ascii_lowercase();
    if let Some(suffix) = pattern.strip_prefix('*') {
        // suffix is ".example.com"
        domain.ends_with(&suffix)
    } else {
        domain == pattern
    }
}

/// Check if an IP address is private/reserved and should be blocked.
fn is_private_ip(addr: &IpAddr) -> bool {
    match addr {
        IpAddr::V4(ip) => {
            ip.is_private()
                || ip.is_loopback()
                || ip.is_link_local()
                || ip.is_broadcast()
                || ip.is_unspecified()
                || ip.is_multicast()
                // CGNAT range 100.64.0.0/10
                || (ip.octets()[0] == 100 && (ip.octets()[1] & 0xC0) == 64)
        }
        IpAddr::V6(ip) => {
            // Check IPv4-mapped addresses (::ffff:x.x.x.x)
            if let Some(mapped) = ip.to_ipv4_mapped() {
                return is_private_ip(&IpAddr::V4(mapped));
            }
            ip.is_loopback()
                || ip.is_unspecified()
                || ip.is_multicast()
                // ULA fc00::/7
                || (ip.segments()[0] & 0xfe00) == 0xfc00
                // Link-local fe80::/10
                || (ip.segments()[0] & 0xffc0) == 0xfe80
        }
    }
}

/// Constant-time byte comparison to prevent timing side-channel attacks.
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

/// Parse and handle a single proxy connection.
fn handle_proxy_connection(stream: TcpStream, ctx: &ProxyContext) -> Result<()> {
    let peer = stream.peer_addr().ok();
    debug!(?peer, "proxy connection accepted");

    // Set auth timeout to prevent slowloris
    stream.set_read_timeout(Some(AUTH_TIMEOUT))?;

    let mut reader = BufReader::new(&stream);
    let mut writer = stream.try_clone().context("Failed to clone proxy stream")?;

    // Read all headers (bounded)
    let mut total_read = 0usize;
    let mut request_line = String::new();
    let mut proxy_auth: Option<String> = None;

    // Read request line
    let n = reader.read_line(&mut request_line)?;
    debug!(
        ?peer,
        request_line = request_line.trim(),
        bytes = n,
        "proxy request line"
    );
    total_read += n;
    if total_read > MAX_REQUEST_SIZE {
        write_error(&mut writer, 400, "Request too large")?;
        return Ok(());
    }

    // Read headers until empty line
    loop {
        let mut header_line = String::new();
        let n = reader.read_line(&mut header_line)?;
        total_read += n;
        if total_read > MAX_REQUEST_SIZE {
            write_error(&mut writer, 400, "Request too large")?;
            return Ok(());
        }

        let trimmed = header_line.trim();
        if trimmed.is_empty() {
            break;
        }

        // Parse Proxy-Authorization header (case-insensitive per HTTP spec)
        if let Some((name, value)) = trimmed.split_once(':')
            && name.trim().eq_ignore_ascii_case("Proxy-Authorization")
        {
            proxy_auth = Some(value.trim().to_string());
        }
    }

    // Parse CONNECT request line: "CONNECT host:port HTTP/1.1\r\n"
    let request_line = request_line.trim();
    let parts: Vec<&str> = request_line.split_whitespace().collect();
    if parts.len() < 2 || parts[0] != "CONNECT" {
        write_error(&mut writer, 400, "Expected CONNECT method")?;
        return Ok(());
    }

    let target = parts[1];
    let (hostname, port) = parse_host_port(target)?;

    debug!(hostname, port, "CONNECT request");

    // Verify auth token
    let expected = format!("Basic {}", base64_encode(&format!("workmux:{}", ctx.token)));
    match proxy_auth {
        None => {
            debug!(hostname, "proxy auth missing");
            write_error(&mut writer, 407, "Proxy authentication required")?;
            return Ok(());
        }
        Some(ref auth) if !constant_time_eq(auth.as_bytes(), expected.as_bytes()) => {
            debug!(hostname, "proxy auth failed");
            write_error(&mut writer, 407, "Invalid proxy credentials")?;
            return Ok(());
        }
        _ => {}
    }

    // Clear read timeout for authenticated tunneling
    stream.set_read_timeout(None)?;

    // Reject non-443 ports
    if port != ALLOWED_PORT {
        warn!(hostname, port, "rejected: non-443 port");
        write_error(&mut writer, 403, "Only port 443 is allowed")?;
        return Ok(());
    }

    // Normalize hostname
    let hostname = hostname.to_ascii_lowercase();
    let hostname = hostname.strip_suffix('.').unwrap_or(&hostname);

    // Reject IP literal hostnames
    if hostname.parse::<IpAddr>().is_ok() {
        warn!(hostname, "rejected: IP literal hostname");
        write_error(&mut writer, 403, "IP literal hostnames not allowed")?;
        return Ok(());
    }

    // Check domain allowlist
    let allowed = ctx
        .allowed_domains
        .iter()
        .any(|pattern| domain_matches(hostname, pattern));
    if !allowed {
        warn!(hostname, "rejected: domain not in allowlist");
        write_error(&mut writer, 403, "Domain not allowed")?;
        return Ok(());
    }

    // Resolve DNS on host side
    let addrs: Vec<SocketAddr> = match format!("{}:{}", hostname, port).to_socket_addrs() {
        Ok(addrs) => addrs.collect(),
        Err(e) => {
            warn!(hostname, error = %e, "DNS resolution failed");
            write_error(&mut writer, 502, "DNS resolution failed")?;
            return Ok(());
        }
    };

    // Filter out private IPs
    let public_addrs: Vec<&SocketAddr> = addrs.iter().filter(|a| !is_private_ip(&a.ip())).collect();

    if public_addrs.is_empty() {
        warn!(hostname, "rejected: all resolved IPs are private");
        write_error(&mut writer, 403, "All resolved IPs are private")?;
        return Ok(());
    }

    // Connect to first public IP (TOCTOU-safe: use validated SocketAddr directly)
    let target_addr = *public_addrs[0];
    let target_stream = match TcpStream::connect_timeout(&target_addr, CONNECT_TIMEOUT) {
        Ok(s) => s,
        Err(e) => {
            debug!(hostname, addr = %target_addr, error = %e, "connect failed");
            write_error(&mut writer, 502, "Connection to target failed")?;
            return Ok(());
        }
    };

    debug!(hostname, addr = %target_addr, "tunnel established");

    // Send 200 Connection Established
    writer.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")?;
    writer.flush()?;

    // Drain any bytes the BufReader consumed from the socket but hasn't yielded
    // (e.g. a TLS ClientHello pipelined in the same TCP segment as the CONNECT).
    let buffered = reader.buffer();
    if !buffered.is_empty() {
        let mut target_ref = &target_stream;
        target_ref
            .write_all(buffered)
            .context("Failed to forward buffered data to target")?;
    }

    // Bidirectional tunnel
    tunnel(reader.into_inner(), &target_stream)?;

    Ok(())
}

/// Parse "host:port" from CONNECT target.
fn parse_host_port(target: &str) -> Result<(&str, u16)> {
    // Handle IPv6 literals like [::1]:443
    if let Some(bracket_end) = target.find(']') {
        let host = &target[..=bracket_end];
        let port_str = target[bracket_end + 1..].strip_prefix(':').unwrap_or("443");
        let port: u16 = port_str.parse().context("Invalid port")?;
        return Ok((host, port));
    }

    match target.rsplit_once(':') {
        Some((host, port_str)) => {
            let port: u16 = port_str.parse().context("Invalid port")?;
            Ok((host, port))
        }
        None => Ok((target, 443)),
    }
}

/// Write an HTTP error response.
fn write_error(writer: &mut impl Write, code: u16, reason: &str) -> Result<()> {
    let response = format!(
        "HTTP/1.1 {} {}\r\nContent-Length: {}\r\n\r\n{}",
        code,
        reason,
        reason.len(),
        reason,
    );
    writer.write_all(response.as_bytes())?;
    writer.flush()?;
    Ok(())
}

/// Simple base64 encoding (avoids adding a dependency for this one use).
fn base64_encode(input: &str) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let bytes = input.as_bytes();
    let mut result = String::with_capacity(bytes.len().div_ceil(3) * 4);

    for chunk in bytes.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
        let triple = (b0 << 16) | (b1 << 8) | b2;

        result.push(ALPHABET[((triple >> 18) & 0x3F) as usize] as char);
        result.push(ALPHABET[((triple >> 12) & 0x3F) as usize] as char);
        if chunk.len() > 1 {
            result.push(ALPHABET[((triple >> 6) & 0x3F) as usize] as char);
        } else {
            result.push('=');
        }
        if chunk.len() > 2 {
            result.push(ALPHABET[(triple & 0x3F) as usize] as char);
        } else {
            result.push('=');
        }
    }

    result
}

/// Bidirectional byte tunnel between two TCP streams.
fn tunnel(client: &TcpStream, target: &TcpStream) -> Result<()> {
    let mut client_read = client.try_clone()?;
    let mut target_write = target.try_clone()?;
    let mut target_read = target.try_clone()?;
    let mut client_write = client.try_clone()?;

    // client -> target
    let t1 = thread::spawn(move || {
        let _ = std::io::copy(&mut client_read, &mut target_write);
        let _ = target_write.shutdown(std::net::Shutdown::Write);
    });

    // target -> client
    let t2 = thread::spawn(move || {
        let _ = std::io::copy(&mut target_read, &mut client_write);
        let _ = client_write.shutdown(std::net::Shutdown::Write);
    });

    t1.join().ok();
    t2.join().ok();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── domain_matches tests ────────────────────────────────────────────

    #[test]
    fn domain_exact_match() {
        assert!(domain_matches("example.com", "example.com"));
        assert!(domain_matches("api.anthropic.com", "api.anthropic.com"));
    }

    #[test]
    fn domain_case_insensitive() {
        assert!(domain_matches("Example.COM", "example.com"));
        assert!(domain_matches("example.com", "Example.COM"));
    }

    #[test]
    fn domain_wildcard_match() {
        assert!(domain_matches("foo.googleapis.com", "*.googleapis.com"));
        assert!(domain_matches("bar.baz.googleapis.com", "*.googleapis.com"));
    }

    #[test]
    fn domain_wildcard_does_not_match_base() {
        // *.example.com should NOT match example.com itself (standard behavior)
        assert!(!domain_matches("example.com", "*.example.com"));
    }

    #[test]
    fn domain_no_match() {
        assert!(!domain_matches("evil.com", "example.com"));
        assert!(!domain_matches("notexample.com", "example.com"));
        assert!(!domain_matches("evil.com", "*.example.com"));
    }

    // ── is_private_ip tests ─────────────────────────────────────────────

    #[test]
    fn private_ip_rfc1918() {
        assert!(is_private_ip(&"10.0.0.1".parse().unwrap()));
        assert!(is_private_ip(&"172.16.0.1".parse().unwrap()));
        assert!(is_private_ip(&"192.168.1.1".parse().unwrap()));
    }

    #[test]
    fn private_ip_loopback() {
        assert!(is_private_ip(&"127.0.0.1".parse().unwrap()));
        assert!(is_private_ip(&"::1".parse().unwrap()));
    }

    #[test]
    fn private_ip_link_local() {
        assert!(is_private_ip(&"169.254.1.1".parse().unwrap()));
    }

    #[test]
    fn private_ip_cgnat() {
        assert!(is_private_ip(&"100.64.0.1".parse().unwrap()));
        assert!(is_private_ip(&"100.127.255.255".parse().unwrap()));
    }

    #[test]
    fn private_ip_multicast() {
        assert!(is_private_ip(&"224.0.0.1".parse().unwrap()));
    }

    #[test]
    fn private_ip_ipv6_ula() {
        assert!(is_private_ip(&"fc00::1".parse().unwrap()));
        assert!(is_private_ip(&"fd12::1".parse().unwrap()));
    }

    #[test]
    fn private_ip_ipv6_link_local() {
        assert!(is_private_ip(&"fe80::1".parse().unwrap()));
    }

    #[test]
    fn private_ip_v4_mapped_v6() {
        // ::ffff:127.0.0.1 is IPv4-mapped IPv6 for loopback
        assert!(is_private_ip(&"::ffff:127.0.0.1".parse().unwrap()));
        // ::ffff:10.0.0.1 is IPv4-mapped IPv6 for RFC1918
        assert!(is_private_ip(&"::ffff:10.0.0.1".parse().unwrap()));
        // ::ffff:8.8.8.8 is IPv4-mapped IPv6 for public IP
        assert!(!is_private_ip(&"::ffff:8.8.8.8".parse().unwrap()));
    }

    #[test]
    fn public_ip_allowed() {
        assert!(!is_private_ip(&"8.8.8.8".parse().unwrap()));
        assert!(!is_private_ip(&"1.1.1.1".parse().unwrap()));
        assert!(!is_private_ip(&"2607:f8b0:4004:800::200e".parse().unwrap()));
    }

    #[test]
    fn not_private_ip_100_non_cgnat() {
        // 100.0.0.1 is NOT in CGNAT range (100.64.0.0/10)
        assert!(!is_private_ip(&"100.0.0.1".parse().unwrap()));
    }

    // ── parse_host_port tests ───────────────────────────────────────────

    #[test]
    fn parse_host_port_standard() {
        let (host, port) = parse_host_port("example.com:443").unwrap();
        assert_eq!(host, "example.com");
        assert_eq!(port, 443);
    }

    #[test]
    fn parse_host_port_non_standard() {
        let (host, port) = parse_host_port("example.com:8443").unwrap();
        assert_eq!(host, "example.com");
        assert_eq!(port, 8443);
    }

    #[test]
    fn parse_host_port_no_port() {
        let (host, port) = parse_host_port("example.com").unwrap();
        assert_eq!(host, "example.com");
        assert_eq!(port, 443);
    }

    // ── base64 encoding test ────────────────────────────────────────────

    #[test]
    fn base64_encode_basic_auth() {
        assert_eq!(base64_encode("workmux:mytoken"), "d29ya211eDpteXRva2Vu");
        assert_eq!(base64_encode(""), "");
        assert_eq!(base64_encode("a"), "YQ==");
        assert_eq!(base64_encode("ab"), "YWI=");
        assert_eq!(base64_encode("abc"), "YWJj");
    }

    // ── proxy server lifecycle tests ────────────────────────────────────

    #[test]
    fn proxy_binds_to_random_port() {
        let proxy = NetworkProxy::bind(&["example.com".to_string()]).unwrap();
        assert!(proxy.port() > 0);
    }

    #[test]
    fn proxy_token_is_nonempty() {
        let proxy = NetworkProxy::bind(&[]).unwrap();
        assert!(!proxy.token().is_empty());
    }

    #[test]
    fn proxy_rejects_missing_auth() {
        let proxy = NetworkProxy::bind(&["example.com".to_string()]).unwrap();
        let port = proxy.port();
        let _handle = proxy.spawn();

        std::thread::sleep(Duration::from_millis(50));

        let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).unwrap();
        stream
            .write_all(b"CONNECT example.com:443 HTTP/1.1\r\n\r\n")
            .unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        reader.read_line(&mut response).unwrap();
        assert!(response.contains("407"));
    }

    #[test]
    fn proxy_rejects_wrong_auth() {
        let proxy = NetworkProxy::bind(&["example.com".to_string()]).unwrap();
        let port = proxy.port();
        let _handle = proxy.spawn();

        std::thread::sleep(Duration::from_millis(50));

        let auth = format!("Basic {}", base64_encode("workmux:wrong-token"));
        let request = format!(
            "CONNECT example.com:443 HTTP/1.1\r\nProxy-Authorization: {}\r\n\r\n",
            auth
        );

        let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).unwrap();
        stream.write_all(request.as_bytes()).unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        reader.read_line(&mut response).unwrap();
        assert!(response.contains("407"));
    }

    #[test]
    fn proxy_accepts_lowercase_auth_header() {
        let proxy = NetworkProxy::bind(&["example.com".to_string()]).unwrap();
        let port = proxy.port();
        let token = proxy.token().to_string();
        let _handle = proxy.spawn();

        std::thread::sleep(Duration::from_millis(50));

        // Use lowercase "proxy-authorization" like hyper/reqwest do
        let auth = format!("Basic {}", base64_encode(&format!("workmux:{}", token)));
        let request = format!(
            "CONNECT example.com:443 HTTP/1.1\r\nproxy-authorization: {}\r\n\r\n",
            auth
        );

        let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).unwrap();
        stream.write_all(request.as_bytes()).unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        reader.read_line(&mut response).unwrap();
        // Should NOT be 407 -- lowercase header must be accepted
        assert!(
            !response.contains("407"),
            "lowercase proxy-authorization should be accepted, got: {}",
            response.trim()
        );
    }

    #[test]
    fn proxy_rejects_non_443_port() {
        let proxy = NetworkProxy::bind(&["example.com".to_string()]).unwrap();
        let port = proxy.port();
        let token = proxy.token().to_string();
        let _handle = proxy.spawn();

        std::thread::sleep(Duration::from_millis(50));

        let auth = format!("Basic {}", base64_encode(&format!("workmux:{}", token)));
        let request = format!(
            "CONNECT example.com:80 HTTP/1.1\r\nProxy-Authorization: {}\r\n\r\n",
            auth
        );

        let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).unwrap();
        stream.write_all(request.as_bytes()).unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        reader.read_line(&mut response).unwrap();
        assert!(response.contains("403"));
    }

    #[test]
    fn proxy_rejects_unlisted_domain() {
        let proxy = NetworkProxy::bind(&["allowed.com".to_string()]).unwrap();
        let port = proxy.port();
        let token = proxy.token().to_string();
        let _handle = proxy.spawn();

        std::thread::sleep(Duration::from_millis(50));

        let auth = format!("Basic {}", base64_encode(&format!("workmux:{}", token)));
        let request = format!(
            "CONNECT denied.com:443 HTTP/1.1\r\nProxy-Authorization: {}\r\n\r\n",
            auth
        );

        let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).unwrap();
        stream.write_all(request.as_bytes()).unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        reader.read_line(&mut response).unwrap();
        assert!(response.contains("403"));
    }

    /// Verify that bytes pipelined after CONNECT headers (e.g. a TLS
    /// ClientHello in the same TCP segment) are forwarded to the target
    /// rather than silently dropped by BufReader::into_inner().
    #[test]
    fn pipelined_data_forwarded_through_tunnel() {
        use std::io::Read;

        // "Target" server that will receive forwarded data
        let target_listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let target_addr = target_listener.local_addr().unwrap();

        // Accept target connection in background and read the forwarded bytes
        let target_handle = thread::spawn(move || {
            let (mut conn, _) = target_listener.accept().unwrap();
            conn.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
            let mut buf = vec![0u8; 26];
            conn.read_exact(&mut buf).unwrap();
            buf
        });

        // Simulated proxy listener
        let proxy_listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let proxy_addr = proxy_listener.local_addr().unwrap();

        // Build pipelined payload: CONNECT headers + extra data in one write
        let extra_data = b"SIMULATED_TLS_CLIENT_HELLO";
        let mut pipelined = Vec::new();
        pipelined
            .extend_from_slice(b"CONNECT example.com:443 HTTP/1.1\r\nHost: example.com\r\n\r\n");
        pipelined.extend_from_slice(extra_data);

        // Client sends everything at once (simulates pipelining)
        let mut client = TcpStream::connect(proxy_addr).unwrap();
        client.write_all(&pipelined).unwrap();
        client.flush().unwrap();

        // Proxy accepts and reads with BufReader (mirrors handle_proxy_connection)
        let (proxy_stream, _) = proxy_listener.accept().unwrap();
        // Ensure all data is in kernel buffer before BufReader reads
        thread::sleep(Duration::from_millis(50));
        let mut reader = BufReader::new(&proxy_stream);

        // Parse headers
        loop {
            let mut line = String::new();
            reader.read_line(&mut line).unwrap();
            if line.trim().is_empty() {
                break;
            }
        }

        // Connect to target and drain buffered bytes (the fix under test)
        let mut target_stream = TcpStream::connect(target_addr).unwrap();
        let buffer = reader.buffer();
        assert!(
            !buffer.is_empty(),
            "BufReader should have buffered the pipelined data"
        );
        target_stream.write_all(buffer).unwrap();
        target_stream.flush().unwrap();
        drop(target_stream);

        // Verify target received exactly the pipelined data
        let received = target_handle.join().unwrap();
        assert_eq!(received, extra_data);
    }

    #[test]
    fn proxy_rejects_ip_literal_hostname() {
        let proxy = NetworkProxy::bind(&["8.8.8.8".to_string()]).unwrap();
        let port = proxy.port();
        let token = proxy.token().to_string();
        let _handle = proxy.spawn();

        std::thread::sleep(Duration::from_millis(50));

        let auth = format!("Basic {}", base64_encode(&format!("workmux:{}", token)));
        let request = format!(
            "CONNECT 8.8.8.8:443 HTTP/1.1\r\nProxy-Authorization: {}\r\n\r\n",
            auth
        );

        let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).unwrap();
        stream.write_all(request.as_bytes()).unwrap();
        stream.flush().unwrap();

        let mut response = String::new();
        let mut reader = BufReader::new(&stream);
        reader.read_line(&mut response).unwrap();
        assert!(response.contains("403"));
    }
}