alksocks 0.3.2

SOCKS5 (RFC 1928) proxy protocol over alkcall channels: targeted-forked fast-socks5 typestate core plus producer/consumer sessions. Producer/consumer protocol crate.
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
//! The three I/O-plane seam types (ADR-004), each a function-shaped
//! callback with its error vocabulary: the dial seam (CONNECT), the
//! egress seam (UDP ASSOCIATE), and the accept seam (TCP BIND). These
//! types are the inversion point (AGENTS.md convention 7): the
//! protocol layer
//! never names a substrate type; the feature-gated providers
//! (`local`/`composed`, batch 2) and the test harness construct them.
//!
//! **Function, not trait** (ADR-004): [`DialFn`], [`EgressFactory`],
//! and [`BindAcceptFactory`] are function-shaped callbacks: "produce
//! boxed halves for a resource" is a function, not a trait (the
//! alktunnels ADR-004 finding, extended to all three SOCKS5 seams by
//! POC #1/#2/#5). [`Egress`] is the one trait: the per-association
//! egress is a returned object, not a service. The re-evaluation
//! threshold is three real implementations as trait impls in practice
//! (the alktunnels ADR-004 posture).
//!
//! Contracts (POC-pinned, load-bearing API surface):
//!
//! - **Ownership rides the handle structurally** ([`TargetHandle`],
//!   [`BindTargetHandle`]): the payloads own their halves; any
//!   keep-alive state a substrate needs (e.g. a composed variant's
//!   channel session) rides inside the halves (a provider-side owner
//!   wrapper), so dropping the handle drops everything it dialed or
//!   accepted. No `_` bindings of owning values: the
//!   teardown-at-birth discipline, compiler-enforced by the shape.
//! - **The egress speaks inner bytes**: [`Egress::send`] takes the
//!   payload only; [`Egress::next_reply`] returns `addr + data`; the
//!   frame codec lives on the wire side, applied exactly once
//!   ([`crate::wire`]).
//! - **The readiness contract** ([`Egress::next_reply`]): `Pending`
//!   when no reply is ready; an instantly-ready `Ok(None)` starves a
//!   biased `select!` into livelock (POC #2's structural finding).
//! - **The accept future owns its resources end-to-end**
//!   ([`BindAccept`]): the quiet wait's `select!` drop IS the
//!   client-gone teardown (ADR-004/ADR-007).
//! - **Refusal is RFC-faithful**: every error type maps to RFC 1928
//!   reply codes via `to_reply_error()`; a dial/egress/accept failure
//!   is reply-code-shaped (never coerced to a channels-level error;
//!   session-level refusal stays channels-level, target-level refusal
//!   is in-stream).
//!
//! The readiness-contract behavioral tests (an instant-`Ok(None)`
//! egress must not starve the datagram stage, including the
//! zero-yield shape (the gate review's R-1,
//! tasks/implementation/review-protocol-core.md) live in the producer
//! module's test suite, next to the stage they pin. This module
//! carries the error→reply-code mapping tables, the sync-lift factory
//! constructor, and the compile-shape assertions.

use std::future::Future;
use std::net::SocketAddr;
use std::sync::Arc;

use bytes::Bytes;
use futures::future::BoxFuture;
use tokio::io::{AsyncRead, AsyncWrite};

pub use crate::rfc1928::util::target_addr::TargetAddr;
use crate::rfc1928::ReplyError;

/// The dialed CONNECT target: boxed halves, `+ Sync` per the
/// `ChannelPlan` payload bound (ADR-004). Ownership rides the handle
/// structurally: the payloads own their connection halves; keep-alive
/// state a substrate needs must ride inside the halves (a provider-side
/// owner wrapper), never in a separate binding the compiler could see
/// dropped early.
pub struct TargetHandle {
    pub read: Box<dyn AsyncRead + Send + Sync + Unpin>,
    pub write: Box<dyn AsyncWrite + Send + Sync + Unpin>,
}

impl std::fmt::Debug for TargetHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TargetHandle").finish_non_exhaustive()
    }
}

/// The dial seam (ADR-004): the substrate dial function, injected at
/// registration/assembly. Called once per CONNECT at the command-read
/// interception point with the RFC 1928 target the client requested
/// (domain form passes through unresolved, per ADR-012; resolution is
/// the provider's job). Per-target refusal is the returned
/// [`SocksDialError`] (the producer replies with the mapped RFC code,
/// so no phantom data plane); session-level refusal stays channels-level.
pub type DialFn = Arc<
    dyn Fn(TargetAddr) -> BoxFuture<'static, Result<TargetHandle, SocksDialError>> + Send + Sync,
>;

/// A dial failure, mapped to RFC 1928 reply codes by
/// [`SocksDialError::to_reply_error`] (never a generic error;
/// AGENTS.md convention 2's faithful `ReplyError` mapping).
#[derive(Debug, thiserror::Error)]
pub enum SocksDialError {
    #[error("connection refused: {0}")]
    Refused(String),
    #[error("network unreachable: {0}")]
    NetworkUnreachable(String),
    #[error("host unreachable: {0}")]
    HostUnreachable(String),
    #[error("connection not allowed by ruleset: {0}")]
    NotAllowed(String),
    #[error("general failure: {0}")]
    General(String),
}

impl SocksDialError {
    /// The RFC 1928 reply code for the reply the producer sends on this
    /// refusal. `Refused` → `ConnectionRefused` (0x05),
    /// `NetworkUnreachable` → `NetworkUnreachable` (0x03),
    /// `HostUnreachable` → `HostUnreachable` (0x04), `NotAllowed` →
    /// `ConnectionNotAllowed` (0x02), `General` → `GeneralFailure`
    /// (0x01); the POC #1 mapping, table-tested in this module.
    pub fn to_reply_error(&self) -> ReplyError {
        match self {
            Self::Refused(_) => ReplyError::ConnectionRefused,
            Self::NetworkUnreachable(_) => ReplyError::NetworkUnreachable,
            Self::HostUnreachable(_) => ReplyError::HostUnreachable,
            Self::NotAllowed(_) => ReplyError::ConnectionNotAllowed,
            Self::General(_) => ReplyError::GeneralFailure,
        }
    }
}

/// One association's egress failure. Mapped to RFC reply codes only at
/// association setup ([`EgressError::to_reply_error`]; an egress that
/// cannot start refuses the ASSOCIATE pre-reply); per-datagram failures
/// are not per-datagram refusals, so the producer stage ends the
/// association on an `Err` from the seam (the lossy-datagram posture).
#[derive(Debug, thiserror::Error)]
pub enum EgressError {
    #[error("egress refused: {0}")]
    Refused(String),
    #[error("egress unreachable: {0}")]
    Unreachable(String),
    #[error("egress general failure: {0}")]
    General(String),
}

impl EgressError {
    /// The RFC 1928 reply code for the ASSOCIATE refusal: `Refused` →
    /// `ConnectionRefused` (0x05), `Unreachable` →
    /// `NetworkUnreachable` (0x03), `General` → `GeneralFailure`
    /// (0x01), the POC #2 mapping, table-tested in this module.
    pub fn to_reply_error(&self) -> ReplyError {
        match self {
            Self::Refused(_) => ReplyError::ConnectionRefused,
            Self::Unreachable(_) => ReplyError::NetworkUnreachable,
            Self::General(_) => ReplyError::GeneralFailure,
        }
    }
}

/// The per-association datagram egress, the ASSOCIATE seam's returned
/// object and the module's one trait (ADR-004: the factory is
/// function-shaped; the instance it returns is a trait object,
/// `Box<dyn Egress + Send>`, owned by the producer's datagram stage;
/// stage exit drops it, so egress state never outlives the channel).
///
/// The stage never sees which substrate backs the association
/// (convention 7 at the egress layer).
pub trait Egress {
    /// Egress one datagram to `addr`. Payload-only: the producer stage
    /// decoded the wire frame and hands the bare datagram here, and the
    /// egress never sees a length prefix (framing is applied exactly
    /// once, by the wire layer). A zero-length payload is a legal
    /// empty datagram, not a signal of any kind (the F-2 invariant).
    fn send(&mut self, addr: TargetAddr, payload: Bytes) -> BoxFuture<'_, Result<(), EgressError>>;

    /// Yield the next inbound datagram's *inner* bytes (`addr + data`,
    /// the RFC address encoding followed by the payload, exactly
    /// [`TargetAddr::to_be_bytes()`] + data). The length prefix is the
    /// wire layer's, added by the producer's frame writer; an egress
    /// that prefixes again is the double-framing bug class POC #2
    /// caught.
    ///
    /// # The readiness contract (load-bearing API surface)
    ///
    /// Must return `Pending` when no reply is ready. An
    /// instantly-ready `Ok(None)` starves a biased `select!` into
    /// livelock: the stage parks on `next_reply` ∥ the channel read,
    /// and a hot `Ok(None)` never yields to the channel branch (nor to
    /// the runtime's other tasks on a current-thread scheduler).
    /// `Ok(None)` is tolerated as a spurious wakeup (the stage
    /// re-parks), not as a readiness signal; implement the wait as a
    /// real async park. An `Err` ends the association (the stage
    /// returns; the egress drops with it).
    fn next_reply(&mut self) -> BoxFuture<'_, Result<Option<Bytes>, EgressError>>;
}

/// The egress seam (ADR-004): the per-association egress factory (the
/// [`DialFn`] analogue for the datagram stage), injected at
/// registration/assembly. Called once per UDP ASSOCIATE; the stage owns
/// the returned egress; stage exit drops it.
pub type EgressFactory =
    Arc<dyn Fn() -> BoxFuture<'static, Result<Box<dyn Egress + Send>, EgressError>> + Send + Sync>;

/// A convenience constructor: lift a sync factory into the async shape
/// the producer consumes. The sync result is captured and delivered
/// through the boxed future verbatim (an `Err` still refuses the
/// ASSOCIATE with the mapped code).
pub fn egress_factory<F>(f: F) -> EgressFactory
where
    F: Fn() -> Result<Box<dyn Egress + Send>, EgressError> + Send + Sync + 'static,
{
    Arc::new(move || {
        let result = f();
        Box::pin(async move { result })
    })
}

/// The one accepted inbound connection's handle, reply#2's BND.ADDR
/// carrier plus the data-plane halves. Ownership rides the handle
/// structurally: the payloads own their accepted halves; keep-alive
/// state a substrate needs (e.g. a composed variant's channel session)
/// rides inside the halves (a provider-side owner wrapper), so the
/// compiler enforces the teardown contract, with no `_` bindings of
/// owning values (the third teardown-at-birth witness, ADR-004).
pub struct BindTargetHandle {
    /// The accepted connection's peer address (reply#2's BND.ADDR, the
    /// RFC's "client IP and port of the incoming connection").
    pub peer: TargetAddr,
    pub read: Box<dyn AsyncRead + Send + Sync + Unpin>,
    pub write: Box<dyn AsyncWrite + Send + Sync + Unpin>,
}

impl std::fmt::Debug for BindTargetHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BindTargetHandle")
            .field("peer", &self.peer)
            .finish_non_exhaustive()
    }
}

/// One BIND session's accept source. `bind_addr` is the address
/// reply#1 advertises (BND.ADDR: the real bound listener on the local
/// variant, the advertised address on the composed one); the accept
/// future is awaited exactly once, in the producer's quiet-wait phase.
///
/// **The accept future owns its resources end-to-end** (ADR-004/
/// ADR-007): whatever the provider opened (the listener, the tunnel)
/// lives inside the future, so the quiet wait's `select!` drop of that
/// future IS the client-gone teardown; the listener closes when the
/// client vanishes, with no extra teardown path.
pub struct BindAccept {
    bind_addr: SocketAddr,
    accept: BoxFuture<'static, Result<BindTargetHandle, BindAcceptError>>,
}

impl BindAccept {
    /// Build the session's accept source: `bind_addr` for reply#1, the
    /// one-inbound-accept future (owned end-to-end; see the type
    /// docs).
    pub fn new(
        bind_addr: SocketAddr,
        accept: impl Future<Output = Result<BindTargetHandle, BindAcceptError>> + Send + 'static,
    ) -> Self {
        Self {
            bind_addr,
            accept: Box::pin(accept),
        }
    }

    /// The address reply#1 advertises (BND.ADDR).
    pub fn bind_addr(&self) -> SocketAddr {
        self.bind_addr
    }

    /// Await the one inbound accept (the quiet wait's accept branch,
    /// exactly once; the future is consumed).
    pub async fn accept(self) -> Result<BindTargetHandle, BindAcceptError> {
        self.accept.await
    }
}

impl std::fmt::Debug for BindAccept {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BindAccept")
            .field("bind_addr", &self.bind_addr)
            .finish_non_exhaustive()
    }
}

/// Accept-stage failures (post-reply#1): the producer maps them to RFC
/// reply codes for reply#2, and no data plane exists on refusal.
#[derive(Debug, thiserror::Error)]
pub enum BindAcceptError {
    #[error("accept refused: {0}")]
    Refused(String),
    #[error("accept not allowed: {0}")]
    NotAllowed(String),
    #[error("accept general failure: {0}")]
    General(String),
}

impl BindAcceptError {
    /// The RFC 1928 reply code for reply#2 on this refusal: `Refused` →
    /// `ConnectionRefused` (0x05), `NotAllowed` →
    /// `ConnectionNotAllowed` (0x02), `General` → `GeneralFailure`
    /// (0x01), the POC #5 mapping, table-tested in this module.
    pub fn to_reply_error(&self) -> ReplyError {
        match self {
            Self::Refused(_) => ReplyError::ConnectionRefused,
            Self::NotAllowed(_) => ReplyError::ConnectionNotAllowed,
            Self::General(_) => ReplyError::GeneralFailure,
        }
    }
}

/// Factory failures (pre-reply#1): the producer maps them to RFC reply
/// codes for reply#1, with no phantom listener.
#[derive(Debug, thiserror::Error)]
pub enum BindAcceptFactoryError {
    #[error("bind refused: {0}")]
    Refused(String),
    #[error("bind not allowed: {0}")]
    NotAllowed(String),
    #[error("bind resource shortage: {0}")]
    Shortage(String),
    #[error("bind general failure: {0}")]
    General(String),
}

impl BindAcceptFactoryError {
    /// The RFC 1928 reply code for reply#1 on this refusal: `Refused` →
    /// `ConnectionRefused` (0x05), `NotAllowed` →
    /// `ConnectionNotAllowed` (0x02), `Shortage`/`General` →
    /// `GeneralFailure` (0x01; the RFC's catch-all, since a resource
    /// shortage has no dedicated code), the POC #5 mapping,
    /// table-tested in this module.
    pub fn to_reply_error(&self) -> ReplyError {
        match self {
            Self::Refused(_) => ReplyError::ConnectionRefused,
            Self::NotAllowed(_) => ReplyError::ConnectionNotAllowed,
            Self::Shortage(_) => ReplyError::GeneralFailure,
            Self::General(_) => ReplyError::GeneralFailure,
        }
    }
}

/// The accept seam (ADR-004): the per-BIND accept factory, the
/// [`DialFn`]'s mirror, injected at registration/assembly. Called once
/// per TCP BIND with the requested target. The requested port is the
/// only field a real bind can honor (domains are meaningless as bind
/// addresses); the address policy is the factory's (ADR-006/ADR-012:
/// the callbacks refuse, with RFC reply codes).
///
/// Failure mapping is two-stage (ADR-007): factory failure
/// ([`BindAcceptFactoryError`]) → reply#1 with the mapped code;
/// accept-stage failure ([`BindAcceptError`]) → reply#2 with the
/// mapped code.
pub type BindAcceptFactory = Arc<
    dyn Fn(TargetAddr) -> BoxFuture<'static, Result<BindAccept, BindAcceptFactoryError>>
        + Send
        + Sync,
>;

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

    fn domain(port: u16) -> TargetAddr {
        TargetAddr::Domain("example.com".to_owned(), port)
    }

    #[test]
    fn dial_error_maps_all_variants_to_rfc_reply_codes() {
        for (err, code) in [
            (
                SocksDialError::Refused("x".into()),
                ReplyError::ConnectionRefused,
            ),
            (
                SocksDialError::NetworkUnreachable("x".into()),
                ReplyError::NetworkUnreachable,
            ),
            (
                SocksDialError::HostUnreachable("x".into()),
                ReplyError::HostUnreachable,
            ),
            (
                SocksDialError::NotAllowed("x".into()),
                ReplyError::ConnectionNotAllowed,
            ),
            (
                SocksDialError::General("x".into()),
                ReplyError::GeneralFailure,
            ),
        ] {
            assert_eq!(
                err.to_reply_error().as_u8(),
                code.as_u8(),
                "{err} must map to {code:?}"
            );
        }
    }

    #[test]
    fn egress_error_maps_all_variants_to_rfc_reply_codes() {
        for (err, code) in [
            (
                EgressError::Refused("x".into()),
                ReplyError::ConnectionRefused,
            ),
            (
                EgressError::Unreachable("x".into()),
                ReplyError::NetworkUnreachable,
            ),
            (EgressError::General("x".into()), ReplyError::GeneralFailure),
        ] {
            assert_eq!(
                err.to_reply_error().as_u8(),
                code.as_u8(),
                "{err} must map to {code:?}"
            );
        }
    }

    #[test]
    fn bind_accept_error_maps_all_variants_to_rfc_reply_codes() {
        for (err, code) in [
            (
                BindAcceptError::Refused("x".into()),
                ReplyError::ConnectionRefused,
            ),
            (
                BindAcceptError::NotAllowed("x".into()),
                ReplyError::ConnectionNotAllowed,
            ),
            (
                BindAcceptError::General("x".into()),
                ReplyError::GeneralFailure,
            ),
        ] {
            assert_eq!(
                err.to_reply_error().as_u8(),
                code.as_u8(),
                "{err} must map to {code:?}"
            );
        }
    }

    #[test]
    fn bind_accept_factory_error_maps_all_variants_to_rfc_reply_codes() {
        for (err, code) in [
            (
                BindAcceptFactoryError::Refused("x".into()),
                ReplyError::ConnectionRefused,
            ),
            (
                BindAcceptFactoryError::NotAllowed("x".into()),
                ReplyError::ConnectionNotAllowed,
            ),
            (
                BindAcceptFactoryError::Shortage("x".into()),
                ReplyError::GeneralFailure,
            ),
            (
                BindAcceptFactoryError::General("x".into()),
                ReplyError::GeneralFailure,
            ),
        ] {
            assert_eq!(
                err.to_reply_error().as_u8(),
                code.as_u8(),
                "{err} must map to {code:?}"
            );
        }
    }

    struct QueueEgress {
        replies: VecDeque<Bytes>,
    }

    impl Egress for QueueEgress {
        fn send(
            &mut self,
            _addr: TargetAddr,
            payload: Bytes,
        ) -> BoxFuture<'_, Result<(), EgressError>> {
            Box::pin(async move {
                self.replies.push_back(payload);
                Ok(())
            })
        }

        fn next_reply(&mut self) -> BoxFuture<'_, Result<Option<Bytes>, EgressError>> {
            Box::pin(async move { Ok(self.replies.pop_front()) })
        }
    }

    #[tokio::test]
    async fn egress_factory_lifts_a_sync_factory_into_the_async_shape() {
        let factory: EgressFactory = egress_factory(|| {
            Ok(Box::new(QueueEgress {
                replies: VecDeque::new(),
            }) as Box<dyn Egress + Send>)
        });
        let mut egress = factory().await.expect("Ok lifts verbatim");
        egress
            .send(domain(53), Bytes::from_static(b"query"))
            .await
            .expect("send succeeds");
        let reply = egress.next_reply().await.expect("next_reply succeeds");
        assert_eq!(
            reply.expect("the queued reply is ready"),
            Bytes::from_static(b"query")
        );
        assert!(egress.next_reply().await.expect("drained").is_none());
    }

    #[tokio::test]
    async fn egress_factory_delivers_a_sync_err_verbatim() {
        let factory: EgressFactory =
            egress_factory(|| Err(EgressError::Unreachable("no egress".into())));
        let err = match factory().await {
            Err(err) => err,
            Ok(_) => panic!("expected the sync Err to lift verbatim"),
        };
        assert_eq!(
            err.to_reply_error().as_u8(),
            ReplyError::NetworkUnreachable.as_u8()
        );
    }

    #[tokio::test]
    async fn dial_fn_shape_accepts_a_closure_and_yields_the_handle() {
        let dial: DialFn = Arc::new(|target: TargetAddr| {
            Box::pin(async move {
                assert_eq!(target, domain(443));
                let (client_read, target_read) = tokio::io::duplex(64);
                let (target_write, client_write) = tokio::io::duplex(64);
                std::mem::forget((client_read, client_write));
                Ok(TargetHandle {
                    read: Box::new(target_read) as Box<dyn AsyncRead + Send + Sync + Unpin>,
                    write: Box::new(target_write) as Box<dyn AsyncWrite + Send + Sync + Unpin>,
                })
            })
        });
        let handle = dial(domain(443)).await.expect("the dial resolves");
        let _ = (&handle.read, &handle.write);
    }

    #[tokio::test]
    async fn bind_accept_factory_shape_yields_bind_addr_then_the_handle() {
        let factory: BindAcceptFactory = Arc::new(|_target: TargetAddr| {
            Box::pin(async move {
                Ok(BindAccept::new(
                    SocketAddr::from(([127, 0, 0, 1], 2121)),
                    async {
                        let (client_read, target_read) = tokio::io::duplex(64);
                        let (target_write, client_write) = tokio::io::duplex(64);
                        std::mem::forget((client_read, client_write));
                        Ok(BindTargetHandle {
                            peer: TargetAddr::Ip(SocketAddr::from(([10, 0, 0, 7], 44444))),
                            read: Box::new(target_read) as Box<dyn AsyncRead + Send + Sync + Unpin>,
                            write: Box::new(target_write)
                                as Box<dyn AsyncWrite + Send + Sync + Unpin>,
                        })
                    },
                ))
            })
        });
        let accept = factory(domain(2121)).await.expect("the factory resolves");
        assert_eq!(accept.bind_addr(), SocketAddr::from(([127, 0, 0, 1], 2121)));
        let handle = accept.accept().await.expect("the accept resolves");
        assert_eq!(
            handle.peer,
            TargetAddr::Ip(SocketAddr::from(([10, 0, 0, 7], 44444)))
        );
    }

    #[test]
    fn seam_types_have_the_poc_compile_shapes() {
        fn assert_send<T: Send>() {}
        fn assert_send_sync<T: Send + Sync>() {}
        fn assert_unpin<T: Unpin>() {}

        assert_send_sync::<TargetHandle>();
        assert_send_sync::<BindTargetHandle>();
        assert_unpin::<TargetHandle>();
        assert_unpin::<BindTargetHandle>();

        assert_send_sync::<DialFn>();
        assert_send_sync::<EgressFactory>();
        assert_send_sync::<BindAcceptFactory>();

        assert_send::<BindAccept>();
        assert_unpin::<BindAccept>();

        assert_send_sync::<SocksDialError>();
        assert_send_sync::<EgressError>();
        assert_send_sync::<BindAcceptError>();
        assert_send_sync::<BindAcceptFactoryError>();
    }

    #[test]
    fn debug_impls_render_the_handle_surfaces() {
        // The three Debug impl bodies (review 002 N-8): the dialed
        // handle renders non-exhaustive; the accept handle carries the
        // peer; the accept source carries the bind address.
        let dialed = TargetHandle {
            read: Box::new(tokio::io::empty()),
            write: Box::new(tokio::io::sink()),
        };
        let rendered = format!("{dialed:?}");
        assert!(rendered.contains("TargetHandle"), "{rendered}");
        assert!(rendered.contains(".."), "{rendered}");

        let accepted = BindTargetHandle {
            peer: TargetAddr::Ip(SocketAddr::from(([10, 0, 0, 7], 44444))),
            read: Box::new(tokio::io::empty()),
            write: Box::new(tokio::io::sink()),
        };
        let rendered = format!("{accepted:?}");
        assert!(rendered.contains("BindTargetHandle"), "{rendered}");
        assert!(
            rendered.contains("10.0.0.7:44444"),
            "the peer is named: {rendered}"
        );

        let accept = BindAccept::new(
            SocketAddr::from(([127, 0, 0, 1], 2121)),
            std::future::pending::<Result<BindTargetHandle, BindAcceptError>>(),
        );
        let rendered = format!("{accept:?}");
        assert!(rendered.contains("BindAccept"), "{rendered}");
        assert!(
            rendered.contains("127.0.0.1:2121"),
            "the bind address is named: {rendered}"
        );
    }
}