soth-mitm 0.2.0

Rust intercepting proxy crate with deterministic handler/event contracts for SOTH.
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
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
use super::super::connection_meta::{
    parse_unix_client_addr_meta, process_info_from_unix_client_addr,
    socket_family_from_flow_context,
};
use super::build_handler_flow_hooks;
use crate::config::MitmConfig;
use crate::handler::InterceptHandler;
use crate::metrics::ProxyMetricsStore;
use crate::observe::FlowContext;
use crate::protocol::ApplicationProtocol;
use crate::server::{
    FlowHooks, RawRequest as SidecarRawRequest, RawResponse as SidecarRawResponse,
};
use crate::types::FlowId;
use crate::types::ProcessInfo as PolicyProcessInfo;
use crate::types::{ProcessInfo, RawRequest, RawResponse};
use crate::HandlerDecision;
use bytes::Bytes;
use futures::FutureExt;
use http::HeaderMap;
use std::panic::AssertUnwindSafe;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use uuid::Uuid;

#[test]
fn parses_unix_client_addr_metadata() {
    let parsed = parse_unix_client_addr_meta("unix:pid=4242,path=/tmp/soth-mitm.sock")
        .expect("unix metadata should parse");
    assert_eq!(parsed.pid, Some(4242));
    assert_eq!(parsed.path, Some(PathBuf::from("/tmp/soth-mitm.sock")));
}

#[test]
fn unix_client_addr_maps_socket_family_and_process_info() {
    let context = FlowContext {
        flow_id: FlowId(9),
        client_addr: "unix:pid=1234,path=/tmp/soth.sock".to_string(),
        server_host: "127.0.0.1".to_string(),
        server_port: 11434,
        protocol: ApplicationProtocol::Http1,
    };
    let socket_family = socket_family_from_flow_context(&context);
    assert!(matches!(
        socket_family,
        crate::types::SocketFamily::UnixDomain { .. }
    ));
    let process = process_info_from_unix_client_addr(&context.client_addr)
        .expect("pid metadata should map to process info");
    assert_eq!(process.pid, 1234);
}

#[tokio::test]
async fn request_timeout_cancels_future_and_records_metric() {
    let drop_seen = Arc::new(AtomicBool::new(false));
    let handler = Arc::new(CancellableRequestHandler {
        drop_seen: Arc::clone(&drop_seen),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        Arc::clone(&metrics_store),
        Duration::from_millis(10),
        Duration::from_millis(200),
        true,
    );
    let context = sample_context(101);
    register_connection(&hooks, context.clone()).await;

    let decision = hooks
        .on_request(context.clone(), sample_sidecar_request())
        .await;
    assert!(
        matches!(decision, crate::HandlerDecision::Allow),
        "timed-out request handler should default to Allow"
    );

    wait_for(Duration::from_millis(200), || {
        drop_seen.load(Ordering::Relaxed)
    })
    .await;
    assert!(
        drop_seen.load(Ordering::Relaxed),
        "timed-out request future should be dropped (cancelled)"
    );
    assert_eq!(
        metrics_store.snapshot().handler_timeout_count,
        1,
        "request timeout must increment handler timeout metric"
    );
}

#[tokio::test]
async fn request_panic_recover_true_defaults_allow_and_records_metric() {
    let handler = Arc::new(PanicRequestHandler);
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        Arc::clone(&metrics_store),
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let context = sample_context(102);
    register_connection(&hooks, context.clone()).await;

    let decision = hooks.on_request(context, sample_sidecar_request()).await;
    assert!(
        matches!(decision, crate::HandlerDecision::Allow),
        "panic with recover=true should default to Allow"
    );
    assert_eq!(
        metrics_store.snapshot().handler_panic_count,
        1,
        "panic should increment handler panic metric"
    );
}

#[tokio::test]
async fn request_panic_recover_false_bubbles_panic() {
    let handler = Arc::new(PanicRequestHandler);
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        Arc::clone(&metrics_store),
        Duration::from_millis(100),
        Duration::from_millis(100),
        false,
    );
    let context = sample_context(103);
    register_connection(&hooks, context.clone()).await;

    let panic = AssertUnwindSafe(async {
        let _ = hooks.on_request(context, sample_sidecar_request()).await;
    })
    .catch_unwind()
    .await;
    assert!(panic.is_err(), "panic should bubble when recover=false");
    assert_eq!(
        metrics_store.snapshot().handler_panic_count,
        1,
        "panic should still be counted before unwind"
    );
}

#[tokio::test]
async fn response_fire_and_forget_does_not_block_forward_path() {
    let completed = Arc::new(AtomicUsize::new(0));
    let handler = Arc::new(DelayedResponseHandler {
        delay: Duration::from_millis(80),
        completed: Arc::clone(&completed),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        Arc::clone(&metrics_store),
        Duration::from_millis(200),
        Duration::from_millis(500),
        true,
    );
    let context = sample_context(104);
    register_connection(&hooks, context.clone()).await;

    let started = Instant::now();
    hooks.on_response(context, sample_sidecar_response()).await;
    assert!(
        started.elapsed() < Duration::from_millis(30),
        "on_response should return quickly and run handler asynchronously"
    );

    wait_for(Duration::from_millis(500), || {
        completed.load(Ordering::Relaxed) == 1
    })
    .await;
    assert_eq!(
        completed.load(Ordering::Relaxed),
        1,
        "response callback should eventually complete in spawned task"
    );
}

#[tokio::test]
async fn response_timeout_records_metric_without_blocking() {
    let completed = Arc::new(AtomicUsize::new(0));
    let handler = Arc::new(DelayedResponseHandler {
        delay: Duration::from_millis(200),
        completed: Arc::clone(&completed),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        Arc::clone(&metrics_store),
        Duration::from_millis(200),
        Duration::from_millis(20),
        true,
    );
    let context = sample_context(105);
    register_connection(&hooks, context.clone()).await;

    hooks.on_response(context, sample_sidecar_response()).await;
    wait_for(Duration::from_millis(400), || {
        metrics_store.snapshot().handler_timeout_count >= 1
    })
    .await;
    assert!(
        metrics_store.snapshot().handler_timeout_count >= 1,
        "response timeout should increment handler timeout metric"
    );
    assert_eq!(
        completed.load(Ordering::Relaxed),
        0,
        "timed-out response callback future should be cancelled before completion"
    );
}

#[tokio::test]
async fn stream_end_invokes_connection_close_once() {
    let stream_end_count = Arc::new(AtomicUsize::new(0));
    let close_count = Arc::new(AtomicUsize::new(0));
    let handler = Arc::new(StreamLifecycleHandler {
        stream_end_count: Arc::clone(&stream_end_count),
        close_count: Arc::clone(&close_count),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        metrics_store,
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let context = sample_context(106);
    register_connection(&hooks, context.clone()).await;

    hooks.on_stream_end(context).await;
    assert_eq!(stream_end_count.load(Ordering::Relaxed), 1);
    assert_eq!(close_count.load(Ordering::Relaxed), 1);
}

#[tokio::test]
async fn lifecycle_sync_callbacks_use_response_timeout_budget() {
    let close_count = Arc::new(AtomicUsize::new(0));
    let handler = Arc::new(SlowLifecycleCloseHandler {
        close_delay: Duration::from_millis(80),
        close_count: Arc::clone(&close_count),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        Arc::clone(&metrics_store),
        Duration::from_millis(10),
        Duration::from_millis(200),
        true,
    );
    let context = sample_context(207);
    register_connection(&hooks, context.clone()).await;

    let started = Instant::now();
    hooks.on_stream_end(context).await;
    assert!(
        started.elapsed() >= Duration::from_millis(70),
        "lifecycle close callback should honor lifecycle timeout budget (response timeout), not request timeout"
    );
    assert_eq!(close_count.load(Ordering::Relaxed), 1);
}

#[tokio::test]
async fn duplicate_stream_end_callbacks_are_deduplicated() {
    let stream_end_count = Arc::new(AtomicUsize::new(0));
    let close_count = Arc::new(AtomicUsize::new(0));
    let handler = Arc::new(StreamLifecycleHandler {
        stream_end_count: Arc::clone(&stream_end_count),
        close_count: Arc::clone(&close_count),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        metrics_store,
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let context = sample_context(206);
    register_connection(&hooks, context.clone()).await;

    hooks.on_stream_end(context.clone()).await;
    hooks.on_stream_end(context).await;

    assert_eq!(
        stream_end_count.load(Ordering::Relaxed),
        1,
        "stream end callback must fire once per flow"
    );
    assert_eq!(
        close_count.load(Ordering::Relaxed),
        1,
        "connection close callback must fire once per flow"
    );
}

#[tokio::test]
async fn late_response_after_stream_end_does_not_resurrect_dispatcher() {
    let completed = Arc::new(AtomicUsize::new(0));
    let handler = Arc::new(DelayedResponseHandler {
        delay: Duration::from_millis(120),
        completed: Arc::clone(&completed),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        Arc::clone(&metrics_store),
        Duration::from_millis(200),
        Duration::from_millis(400),
        true,
    );
    let context = sample_context(208);
    register_connection(&hooks, context.clone()).await;

    hooks
        .on_response(context.clone(), sample_sidecar_response())
        .await;
    let hooks_for_end = Arc::clone(&hooks);
    let context_for_end = context.clone();
    let finalize = tokio::spawn(async move {
        hooks_for_end.on_stream_end(context_for_end).await;
    });
    tokio::time::sleep(Duration::from_millis(20)).await;
    hooks.on_response(context, sample_sidecar_response()).await;

    tokio::time::timeout(Duration::from_secs(1), finalize)
        .await
        .expect("stream_end should complete")
        .expect("stream_end task should not panic");
    tokio::time::sleep(Duration::from_millis(160)).await;

    assert_eq!(
        completed.load(Ordering::Relaxed),
        1,
        "late response after stream_end should not create a new flow dispatcher"
    );
    let _ = metrics_store.snapshot();
}

#[tokio::test]
async fn should_intercept_tls_receives_process_info_from_connect_path() {
    let observed_pid = Arc::new(AtomicU32::new(0));
    let handler = Arc::new(ProcessAwareTlsHandler {
        observed_pid: Arc::clone(&observed_pid),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        metrics_store,
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let context = sample_context(107);
    let policy_process = Some(PolicyProcessInfo {
        pid: 4242,
        bundle_id: Some("com.soth.tests".to_string()),
        exe_name: Some("curl".to_string()),
        exe_path: None,
        parent_pid: None,
        parent_process_name: None,
    });

    let _ = hooks.should_intercept_tls(context, policy_process).await;
    assert_eq!(
        observed_pid.load(Ordering::Relaxed),
        4242,
        "process info should flow into TLS intercept decision hook"
    );
}

#[tokio::test]
async fn downstream_tls_failure_bypasses_intercept_for_same_process() {
    let handler = Arc::new(PassThroughTlsHandler);
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        metrics_store,
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let failing_context = sample_context(109);
    register_connection(&hooks, failing_context.clone()).await;

    hooks
        .on_tls_failure(
            failing_context,
            "downstream handshake failed: downstream rustls handshake failed: tls handshake eof"
                .to_string(),
        )
        .await;

    let next_context = sample_context(110);
    let should_intercept = hooks
        .should_intercept_tls(next_context, Some(fixture_policy_process_info(7001)))
        .await;
    assert!(
        !should_intercept,
        "process with downstream TLS EOF should temporarily bypass interception"
    );
}

#[tokio::test]
async fn downstream_tls_failure_bypasses_intercept_for_same_host_without_process_info() {
    let handler = Arc::new(PassThroughTlsHandler);
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        metrics_store,
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let failing_context = sample_context(121);
    hooks
        .on_connection_open(failing_context.clone(), None)
        .await;

    hooks
        .on_tls_failure(
            failing_context,
            "downstream handshake failed: downstream rustls handshake failed: tls handshake eof"
                .to_string(),
        )
        .await;

    let next_context = sample_context(122);
    let should_intercept = hooks.should_intercept_tls(next_context, None).await;
    assert!(
        !should_intercept,
        "host with downstream TLS EOF should temporarily bypass interception even without process attribution"
    );

    let mut sibling_host_context = sample_context(123);
    sibling_host_context.server_host = "api2.example.com".to_string();
    let sibling_host_should_intercept =
        hooks.should_intercept_tls(sibling_host_context, None).await;
    assert!(
        !sibling_host_should_intercept,
        "bypass should apply to sibling hosts that share the same parent domain"
    );

    let mut other_host_context = sample_context(124);
    other_host_context.server_host = "api.other-example.net".to_string();
    let other_host_should_intercept = hooks.should_intercept_tls(other_host_context, None).await;
    assert!(
        other_host_should_intercept,
        "bypass should not spill over to unrelated hosts"
    );
}

#[tokio::test]
async fn upstream_tls_failure_does_not_bypass_intercept_for_process() {
    let handler = Arc::new(PassThroughTlsHandler);
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        metrics_store,
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let context = sample_context(111);
    register_connection(&hooks, context.clone()).await;

    hooks
        .on_tls_failure(
            context,
            "upstream handshake failed: certificate verify failed: unknown ca".to_string(),
        )
        .await;

    let next_context = sample_context(112);
    let should_intercept = hooks
        .should_intercept_tls(next_context, Some(fixture_policy_process_info(7001)))
        .await;
    assert!(
        should_intercept,
        "upstream TLS failures should not disable interception for local process"
    );
}

#[tokio::test]
async fn stream_end_without_response_activity_does_not_trigger_process_fail_open_bypass() {
    let handler = Arc::new(PassThroughTlsHandler);
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        metrics_store,
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let flow_context = sample_context(125);
    register_connection(&hooks, flow_context.clone()).await;

    let first_should_intercept = hooks
        .should_intercept_tls(
            flow_context.clone(),
            Some(fixture_policy_process_info(7001)),
        )
        .await;
    assert!(
        first_should_intercept,
        "baseline process flow should be intercepted"
    );

    hooks.on_stream_end(flow_context).await;

    let next_context = sample_context(126);
    let second_should_intercept = hooks
        .should_intercept_tls(next_context, Some(fixture_policy_process_info(7001)))
        .await;
    assert!(
        second_should_intercept,
        "stream end without response activity should not trigger process fail-open bypass"
    );
}

#[tokio::test]
async fn request_connection_meta_includes_tls_info_for_http2_flow() {
    let observed_tls_proto = Arc::new(std::sync::Mutex::new(None::<String>));
    let observed_tls_sni = Arc::new(std::sync::Mutex::new(None::<String>));
    let handler = Arc::new(TlsMetaCaptureHandler {
        observed_tls_proto: Arc::clone(&observed_tls_proto),
        observed_tls_sni: Arc::clone(&observed_tls_sni),
    });
    let metrics_store = Arc::new(ProxyMetricsStore::default());
    let hooks = build_hooks(
        handler,
        metrics_store,
        Duration::from_millis(100),
        Duration::from_millis(100),
        true,
    );
    let mut context = sample_context(108);
    context.protocol = ApplicationProtocol::Http2;
    register_connection(&hooks, context.clone()).await;

    let _ = hooks.on_request(context, sample_sidecar_request()).await;

    let negotiated = observed_tls_proto.lock().expect("tls proto lock").clone();
    let sni = observed_tls_sni.lock().expect("tls sni lock").clone();
    assert_eq!(negotiated.as_deref(), Some("h2"));
    assert_eq!(sni.as_deref(), Some("api.example.com"));
}

fn build_hooks<H: InterceptHandler>(
    handler: Arc<H>,
    metrics_store: Arc<ProxyMetricsStore>,
    request_timeout: Duration,
    response_timeout: Duration,
    recover_from_panics: bool,
) -> Arc<dyn FlowHooks> {
    let mut config = MitmConfig::default();
    config.process_attribution.enabled = false;
    config.handler.request_timeout_ms = request_timeout.as_millis() as u64;
    config.handler.response_timeout_ms = response_timeout.as_millis() as u64;
    config.handler.recover_from_panics = recover_from_panics;
    build_handler_flow_hooks(&config, handler, metrics_store)
}

fn sample_context(flow_id: u64) -> FlowContext {
    FlowContext {
        flow_id: FlowId(flow_id),
        client_addr: "127.0.0.1:56000".to_string(),
        server_host: "api.example.com".to_string(),
        server_port: 443,
        protocol: ApplicationProtocol::Http1,
    }
}

async fn register_connection(hooks: &Arc<dyn FlowHooks>, context: FlowContext) {
    hooks
        .on_connection_open(context, Some(fixture_policy_process_info(7001)))
        .await;
}

fn fixture_policy_process_info(pid: u32) -> PolicyProcessInfo {
    PolicyProcessInfo {
        pid,
        bundle_id: Some("com.soth.fixture".to_string()),
        exe_name: Some("fixture-client".to_string()),
        exe_path: None,
        parent_pid: None,
        parent_process_name: None,
    }
}

fn sample_sidecar_request() -> SidecarRawRequest {
    SidecarRawRequest {
        method: "GET".to_string(),
        path: "/v1/test".to_string(),
        headers: HeaderMap::new(),
        body: Bytes::new(),
    }
}

fn sample_sidecar_response() -> SidecarRawResponse {
    SidecarRawResponse {
        status: 200,
        headers: HeaderMap::new(),
        body: Bytes::from_static(b"{\"ok\":true}"),
    }
}

async fn wait_for<F>(timeout: Duration, predicate: F)
where
    F: Fn() -> bool,
{
    let start = Instant::now();
    while !predicate() && start.elapsed() < timeout {
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
}

#[derive(Debug)]
struct PanicRequestHandler;

impl InterceptHandler for PanicRequestHandler {
    async fn on_request(&self, _request: &RawRequest) -> HandlerDecision {
        panic!("intentional panic in on_request");
    }
}

#[derive(Debug)]
struct DelayedResponseHandler {
    delay: Duration,
    completed: Arc<AtomicUsize>,
}

impl InterceptHandler for DelayedResponseHandler {
    async fn on_request(&self, _request: &RawRequest) -> HandlerDecision {
        HandlerDecision::Allow
    }

    fn on_response(&self, _response: &RawResponse) -> impl std::future::Future<Output = ()> + Send {
        let delay = self.delay;
        let completed = Arc::clone(&self.completed);
        async move {
            tokio::time::sleep(delay).await;
            completed.fetch_add(1, Ordering::Relaxed);
        }
    }
}

#[derive(Debug)]
struct StreamLifecycleHandler {
    stream_end_count: Arc<AtomicUsize>,
    close_count: Arc<AtomicUsize>,
}

impl InterceptHandler for StreamLifecycleHandler {
    async fn on_request(&self, _request: &RawRequest) -> HandlerDecision {
        HandlerDecision::Allow
    }

    fn on_stream_end(&self, _connection_id: Uuid) -> impl std::future::Future<Output = ()> + Send {
        let stream_end_count = Arc::clone(&self.stream_end_count);
        async move {
            stream_end_count.fetch_add(1, Ordering::Relaxed);
        }
    }

    fn on_connection_close(&self, _connection_id: Uuid) {
        self.close_count.fetch_add(1, Ordering::Relaxed);
    }
}

#[derive(Debug)]
struct SlowLifecycleCloseHandler {
    close_delay: Duration,
    close_count: Arc<AtomicUsize>,
}

impl InterceptHandler for SlowLifecycleCloseHandler {
    async fn on_request(&self, _request: &RawRequest) -> HandlerDecision {
        HandlerDecision::Allow
    }

    fn on_connection_close(&self, _connection_id: Uuid) {
        std::thread::sleep(self.close_delay);
        self.close_count.fetch_add(1, Ordering::Relaxed);
    }
}

#[derive(Debug)]
struct ProcessAwareTlsHandler {
    observed_pid: Arc<AtomicU32>,
}

impl InterceptHandler for ProcessAwareTlsHandler {
    fn should_intercept_tls(&self, _host: &str, process_info: Option<&ProcessInfo>) -> bool {
        let pid = process_info.map(|value| value.pid).unwrap_or(0);
        self.observed_pid.store(pid, Ordering::Relaxed);
        true
    }
}

#[derive(Debug)]
struct PassThroughTlsHandler;

impl InterceptHandler for PassThroughTlsHandler {
    fn should_intercept_tls(&self, _host: &str, _process_info: Option<&ProcessInfo>) -> bool {
        true
    }
}

#[derive(Debug)]
struct TlsMetaCaptureHandler {
    observed_tls_proto: Arc<std::sync::Mutex<Option<String>>>,
    observed_tls_sni: Arc<std::sync::Mutex<Option<String>>>,
}

impl InterceptHandler for TlsMetaCaptureHandler {
    fn on_request(
        &self,
        request: &RawRequest,
    ) -> impl std::future::Future<Output = HandlerDecision> + Send {
        let observed_tls_proto = Arc::clone(&self.observed_tls_proto);
        let observed_tls_sni = Arc::clone(&self.observed_tls_sni);
        let tls_info = request.connection_meta.tls_info.clone();
        async move {
            let mut proto_guard = observed_tls_proto.lock().expect("proto lock");
            let mut sni_guard = observed_tls_sni.lock().expect("sni lock");
            *proto_guard = tls_info
                .as_ref()
                .and_then(|value| value.negotiated_proto.clone());
            *sni_guard = tls_info.and_then(|value| value.sni);
            HandlerDecision::Allow
        }
    }
}

#[derive(Debug)]
struct CancellableRequestHandler {
    drop_seen: Arc<AtomicBool>,
}

#[derive(Debug)]
struct DropProbe {
    drop_seen: Arc<AtomicBool>,
}

impl Drop for DropProbe {
    fn drop(&mut self) {
        self.drop_seen.store(true, Ordering::Relaxed);
    }
}

impl InterceptHandler for CancellableRequestHandler {
    fn on_request(
        &self,
        _request: &RawRequest,
    ) -> impl std::future::Future<Output = HandlerDecision> + Send {
        let drop_seen = Arc::clone(&self.drop_seen);
        async move {
            let _probe = DropProbe { drop_seen };
            tokio::time::sleep(Duration::from_secs(60)).await;
            HandlerDecision::Block {
                status: 403,
                body: Bytes::from_static(b"late"),
            }
        }
    }
}