mod harness;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use alksocks::consumer::{BindDataPlane, BindReply1, BindSession, Socks5ChannelSession};
use alksocks::egress::{BindAcceptError, BindAcceptFactoryError};
use alksocks::error::SocksSessionError;
use alksocks::rfc1928::consts;
use alksocks::rfc1928::util::target_addr::{TargetAddr, ToTargetAddr};
use alksocks::SocksError as SocksErrorKind;
use harness::{
echo_egress, refusing_accept, refusing_accept_factory, wire_consumer_side_with, ECHO_BIND_PORT,
};
fn bind_scoped() -> alkcall::core::auth::Identity {
harness::both_scopes_identity()
}
async fn no_leaked_channels(topo: &harness::ConsumerSideTopology) {
let deadline = std::time::Duration::from_secs(5);
let consumer_ids = topo.consumer.manager().channel_ids();
assert!(
consumer_ids.iter().all(|&id| id == 0),
"consumer leaked channel entries: {consumer_ids:?}"
);
tokio::time::timeout(deadline, async {
loop {
let producer_ids = topo.producer_manager.channel_ids();
if producer_ids.iter().all(|&id| id == 0) {
return;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("the producer's handler-exit teardown reaps the entry");
}
fn reply_code_of(err: &SocksSessionError) -> Option<u8> {
match err {
SocksSessionError::Rfc(SocksErrorKind::ReplyError(code)) => Some(code.as_u8()),
_ => None,
}
}
#[tokio::test]
async fn bind_round_trip_reply1_reply2_then_pass_through() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(harness::echo_accept()),
Some(bind_scoped()),
)
.await;
let mut session = BindSession::bind(
topo.consumer.as_ref(),
("bind.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("the session binds");
let channel_id = session.channel_id();
assert!(channel_id >= 1, "a producer-allocated id");
assert!(topo.consumer.manager().has_channel(channel_id));
let BindReply1 { bind_addr, .. } = session.reply1().expect("reply#1's handle");
assert_eq!(
bind_addr,
TargetAddr::Ip(std::net::SocketAddr::from(([127, 0, 0, 1], ECHO_BIND_PORT))),
"reply#1 carries the advertised BND.ADDR"
);
let mut plane = session
.await_inbound()
.await
.expect("reply#2 read")
.expect("the plane exists before reply#2");
assert_eq!(
plane.peer,
TargetAddr::Ip(std::net::SocketAddr::from(([10, 0, 0, 7], 44444))),
"reply#2 carries the accepted peer"
);
plane.write_all(b"ping").await.expect("write");
plane.flush().await.expect("flush");
let mut buf = [0u8; 4];
tokio::time::timeout(
std::time::Duration::from_secs(10),
plane.read_exact(&mut buf),
)
.await
.expect("echo timed out")
.expect("read the echo");
assert_eq!(&buf, b"ping");
drop(plane);
assert!(session.close().await, "the adopted channel entry existed");
no_leaked_channels(&topo).await;
}
#[tokio::test]
async fn bind_data_plane_accessors_into_inner_and_socket_mut() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(harness::echo_accept()),
Some(bind_scoped()),
)
.await;
let mut session = BindSession::bind(
topo.consumer.as_ref(),
("plane.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("the session binds");
session
.reply1()
.expect("reply#1's handle")
.raw_mut()
.get_socket_mut()
.write_all(b"pre")
.await
.expect("pre-reply#2 write");
let mut plane = session
.await_inbound()
.await
.expect("reply#2 read")
.expect("the plane");
plane
.get_socket_mut()
.write_all(b"raw")
.await
.expect("write");
let mut inner = plane.into_inner();
let mut buf = [0u8; 6];
tokio::time::timeout(
std::time::Duration::from_secs(10),
inner.read_exact(&mut buf),
)
.await
.expect("echo timed out")
.expect("read the echo");
assert_eq!(&buf, b"preraw", "both write paths rode the same pipe");
drop(inner);
assert!(session.close().await, "the entry existed");
no_leaked_channels(&topo).await;
}
#[tokio::test]
async fn bind_command_gate_refusal_is_a_typed_reply_code_error() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(harness::echo_accept()),
Some(harness::consumer_identity()),
)
.await;
let err = BindSession::bind(
topo.consumer.as_ref(),
("gate.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect_err("the gate refuses a socks5:open-only identity");
assert_eq!(
reply_code_of(&err),
Some(consts::SOCKS5_REPLY_CONNECTION_NOT_ALLOWED),
"the command gate's 0x02 rides the session error: {err:?}"
);
no_leaked_channels(&topo).await;
}
#[tokio::test]
async fn bind_factory_failure_surfaces_reply1_code() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(refusing_accept_factory(BindAcceptFactoryError::Refused(
"port held".into(),
))),
Some(bind_scoped()),
)
.await;
let err = BindSession::bind(
topo.consumer.as_ref(),
("factory.fail", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect_err("the factory refused");
assert_eq!(
reply_code_of(&err),
Some(consts::SOCKS5_REPLY_CONNECTION_REFUSED),
"the factory refusal maps to reply#1's code: {err:?}"
);
no_leaked_channels(&topo).await;
}
#[tokio::test]
async fn bind_accept_stage_failure_surfaces_reply2_code() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(refusing_accept(BindAcceptError::NotAllowed(
"policy".into(),
))),
Some(bind_scoped()),
)
.await;
let mut session = BindSession::bind(
topo.consumer.as_ref(),
("accept.fail", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("reply#1 succeeded; the factory resolved");
let err = match session.await_inbound().await {
Err(err) => err,
Ok(Some(_)) => panic!("the accept-stage refusal must not yield a data plane"),
Ok(None) => panic!("the plane existed before reply#2"),
};
assert_eq!(
reply_code_of(&err),
Some(consts::SOCKS5_REPLY_CONNECTION_NOT_ALLOWED),
"reply#2's mapped code surfaces at await_inbound: {err:?}"
);
assert!(session.close().await, "the entry existed");
no_leaked_channels(&topo).await;
}
#[tokio::test]
async fn bind_quiet_wait_garbage_from_the_client_ends_the_session() {
let parked: alksocks::egress::BindAcceptFactory =
std::sync::Arc::new(move |_target: TargetAddr| {
Box::pin(async move {
Ok(alksocks::egress::BindAccept::new(
std::net::SocketAddr::from(([127, 0, 0, 1], ECHO_BIND_PORT)),
std::future::pending::<
Result<alksocks::egress::BindTargetHandle, BindAcceptError>,
>(),
))
})
});
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(parked),
Some(bind_scoped()),
)
.await;
let mut session = BindSession::bind(
topo.consumer.as_ref(),
("quiet.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("reply#1 succeeded");
session
.reply1()
.expect("reply#1's handle")
.raw_mut()
.get_socket_mut()
.write_all(&[0x05, 0x02])
.await
.expect("garbage written");
let err = match session.await_inbound().await {
Err(err) => err,
Ok(Some(_)) => panic!("the garbage must not yield a data plane"),
Ok(None) => panic!("the plane existed before reply#2"),
};
assert!(
matches!(err, SocksSessionError::Io(_)),
"the quiet-wait garbage surfaces as the EOF'd reply#2 read: {err:?}"
);
assert!(session.close().await, "the entry existed");
no_leaked_channels(&topo).await;
}
#[tokio::test]
async fn bind_and_connect_serve_on_the_same_registration() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
Some(echo_egress()),
Some(harness::echo_accept()),
Some(bind_scoped()),
)
.await;
let mut connect_session = Socks5ChannelSession::connect(
topo.consumer.as_ref(),
("echo.test", 443u16).to_target_addr().unwrap(),
)
.await
.expect("the connect session");
connect_session
.split()
.expect("pipe")
.1
.write_all(b"tcp")
.await
.expect("write");
let (mut read, _) = connect_session.split().expect("pipe");
let mut buf = [0u8; 3];
tokio::time::timeout(
std::time::Duration::from_secs(10),
read.read_exact(&mut buf),
)
.await
.expect("echo timed out")
.expect("read the echo");
assert_eq!(&buf, b"tcp");
connect_session.close().await;
let mut bind_session = BindSession::bind(
topo.consumer.as_ref(),
("bind.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("the bind session");
let mut plane = bind_session
.await_inbound()
.await
.expect("reply#2")
.expect("the plane");
plane.write_all(b"bind").await.expect("write");
plane.flush().await.expect("flush");
let mut buf = [0u8; 4];
tokio::time::timeout(
std::time::Duration::from_secs(10),
plane.read_exact(&mut buf),
)
.await
.expect("echo timed out")
.expect("read the echo");
assert_eq!(&buf, b"bind");
drop(plane);
bind_session.close().await;
no_leaked_channels(&topo).await;
}
#[tokio::test]
async fn bind_drop_teardown_reaps_and_connection_stays_healthy() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(harness::echo_accept()),
Some(bind_scoped()),
)
.await;
let mut session = BindSession::bind(
topo.consumer.as_ref(),
("dropped.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("the session binds");
let BindReply1 { bind_addr, .. } = session.reply1().expect("reply#1's handle");
assert_eq!(
bind_addr,
TargetAddr::Ip(std::net::SocketAddr::from(([127, 0, 0, 1], ECHO_BIND_PORT)))
);
drop(session);
no_leaked_channels(&topo).await;
let mut fresh = BindSession::bind(
topo.consumer.as_ref(),
("fresh.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("fresh bind after the drop");
let mut plane = fresh
.await_inbound()
.await
.expect("reply#2")
.expect("the plane");
plane.write_all(b"again").await.expect("write");
plane.flush().await.expect("flush");
let mut buf = [0u8; 5];
tokio::time::timeout(
std::time::Duration::from_secs(10),
plane.read_exact(&mut buf),
)
.await
.expect("echo timed out")
.expect("read the fresh echo");
assert_eq!(&buf, b"again");
drop(plane);
fresh.close().await;
no_leaked_channels(&topo).await;
}
#[test]
fn bind_session_type_is_send() {
fn assert_send<T: Send>() {}
assert_send::<BindSession>();
assert_send::<BindDataPlane>();
assert_send::<BindReply1<'static>>();
}
#[tokio::test]
async fn double_await_inbound_returns_the_spent_shape_and_bytes_survive() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(harness::echo_accept()),
Some(bind_scoped()),
)
.await;
let mut session = BindSession::bind(
topo.consumer.as_ref(),
("reentry.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("the session binds");
let mut plane = session
.await_inbound()
.await
.expect("reply#2 read")
.expect("the plane exists before reply#2");
plane.write_all(b"ping").await.expect("write");
plane.flush().await.expect("flush");
let mut buf = [0u8; 4];
tokio::time::timeout(
std::time::Duration::from_secs(10),
plane.read_exact(&mut buf),
)
.await
.expect("echo timed out")
.expect("read the echo");
assert_eq!(&buf, b"ping", "the first plane's round-trip");
drop(plane);
let second = session
.await_inbound()
.await
.expect("the spent shape is an Ok, not an error");
assert!(second.is_none(), "the phase was consumed");
assert!(session.close().await, "the entry existed");
no_leaked_channels(&topo).await;
let mut fresh = BindSession::bind(
topo.consumer.as_ref(),
("after.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("fresh bind after the spent call");
let mut plane = fresh
.await_inbound()
.await
.expect("reply#2")
.expect("the plane");
plane.write_all(b"again").await.expect("write");
plane.flush().await.expect("flush");
let mut buf = [0u8; 5];
tokio::time::timeout(
std::time::Duration::from_secs(10),
plane.read_exact(&mut buf),
)
.await
.expect("echo timed out")
.expect("read the fresh echo");
assert_eq!(&buf, b"again", "the fresh session's bytes are intact");
drop(plane);
fresh.close().await;
no_leaked_channels(&topo).await;
}
#[tokio::test]
async fn reply1_twice_is_a_view_and_the_reader_yields_one_plane() {
let topo = wire_consumer_side_with(
harness::echo_dial(),
None,
Some(harness::echo_accept()),
Some(bind_scoped()),
)
.await;
let mut session = BindSession::bind(
topo.consumer.as_ref(),
("view.test", ECHO_BIND_PORT).to_target_addr().unwrap(),
)
.await
.expect("the session binds");
let expected = TargetAddr::Ip(std::net::SocketAddr::from(([127, 0, 0, 1], ECHO_BIND_PORT)));
let BindReply1 { bind_addr, .. } = session.reply1().expect("reply#1's handle");
assert_eq!(bind_addr, expected);
let BindReply1 { bind_addr, .. } = session.reply1().expect("reply#1's handle again");
assert_eq!(bind_addr, expected, "a view, not a reader");
let mut plane = session
.await_inbound()
.await
.expect("reply#2 read")
.expect("the plane");
plane.write_all(b"once").await.expect("write");
plane.flush().await.expect("flush");
let mut buf = [0u8; 4];
tokio::time::timeout(
std::time::Duration::from_secs(10),
plane.read_exact(&mut buf),
)
.await
.expect("echo timed out")
.expect("read the echo");
assert_eq!(&buf, b"once");
drop(plane);
assert!(
session
.await_inbound()
.await
.expect("spent shape")
.is_none(),
"no second plane after the reader ran"
);
session.close().await;
no_leaked_channels(&topo).await;
}