use std::time::Duration;
use std::time::Instant;
use bytes::Bytes;
use rings_core::ecc::PublicKey;
use rings_test_support::with_hang_guard;
use super::loop_network::open_policy;
use super::loop_network::EchoWorld;
use super::loop_network::LoopNetwork;
use super::loop_network::SourceWorld;
use super::loop_network::EVENT_BOUND;
use crate::error::Error;
use crate::error::Result;
use crate::onion::circuit::OnionAlgebra;
use crate::onion::https::OnionHttpsCall;
use crate::onion::https::OnionHttpsClient;
use crate::onion::https::OnionHttpsEgress;
use crate::onion::https::OnionHttpsRequest;
use crate::onion::https::OnionHttpsResponse;
use crate::onion::https::OnionHttpsWorld;
use crate::onion::https::ONION_HTTPS_RESPONSE_TIMEOUT;
use crate::onion::native::NativeOnionCircuitHandle;
use crate::onion::proxy::OnionProxyRoute;
use crate::onion::session::client::OnionCreditWindow;
use crate::onion::session::client::ONION_SESSION_DEADLINE_MS;
use crate::onion::session::dial::OnionSessionRequest;
use crate::onion::session::dial::OnionStreamEvent;
use crate::onion::session::dial::OnionStreamReceiver;
use crate::onion::session::dial::ONION_SESSION_OPEN_TIMEOUT;
use crate::onion::session::frame::OnionFrame;
use crate::onion::session::serve::OnionExitSessions;
use crate::onion::session::serve::OnionWorld;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionLoopClass;
use crate::onion::OnionProxyTarget;
use crate::onion::OnionRouteError;
use crate::onion::OnionServiceName;
fn target() -> OnionProxyTarget {
OnionProxyTarget::parse_authority("example.com:443").expect("authority")
}
async fn network<W: OnionWorld>(
symbol: OnionServiceName,
world: W,
policy: OnionExitPolicy,
) -> Result<LoopNetwork> {
LoopNetwork::new(move |accounting, link_sender| {
OnionAlgebra::default().register(
symbol,
OnionExitSessions::new(world, policy, accounting.clone(), link_sender.clone()),
)
})
.await
}
fn request(network: &LoopNetwork, symbol: OnionServiceName) -> Result<OnionSessionRequest> {
Ok(OnionSessionRequest {
route: network.route(symbol.clone())?,
symbol,
target: target(),
class: OnionLoopClass::DEFAULT,
window: OnionCreditWindow::DEFAULT,
})
}
fn stream_event_bound() -> Duration {
let deadline = u64::try_from(ONION_SESSION_DEADLINE_MS).expect("Δ fits in u64 milliseconds");
Duration::from_millis(deadline).saturating_add(EVENT_BOUND)
}
fn https_request_bound() -> Duration {
ONION_SESSION_OPEN_TIMEOUT
.saturating_add(ONION_HTTPS_RESPONSE_TIMEOUT)
.saturating_add(EVENT_BOUND)
}
async fn collect(receiver: &mut OnionStreamReceiver) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
let bound = stream_event_bound();
loop {
match with_hang_guard("the loop stream's next event", bound, receiver.next()).await {
Some(OnionStreamEvent::Data(data)) => bytes.extend_from_slice(&data),
Some(OnionStreamEvent::Fin) => return Ok(bytes),
Some(OnionStreamEvent::Failed) | None => {
return Err(Error::OnionRouteError(OnionRouteError::SessionFailed))
}
}
}
}
#[tokio::test]
async fn test_tcp_loop_echoes_a_multi_frame_stream() -> Result<()> {
let network = network(OnionServiceName::tcp(), EchoWorld, open_policy()).await?;
let stream = network
.client
.runtime
.open(request(&network, OnionServiceName::tcp())?)
.await?;
let (mut sender, mut receiver) = stream.split();
let sent = (0..40_000_u32)
.map(|index| u8::try_from(index % 251).expect("small"))
.collect::<Vec<_>>();
sender.send(Bytes::from(sent.clone())).await?;
sender.fin().await?;
let echoed = collect(&mut receiver).await?;
assert_eq!(echoed, sent);
Ok(())
}
#[tokio::test]
async fn test_a_denied_target_is_refused_at_the_open() -> Result<()> {
let deny = OnionExitPolicy::from_target_strings(vec!["other.example:443".to_string()], vec![])?;
let network = network(OnionServiceName::tcp(), EchoWorld, deny).await?;
let opened = network
.client
.runtime
.open(request(&network, OnionServiceName::tcp())?)
.await;
assert!(matches!(
opened,
Err(Error::OnionRouteError(OnionRouteError::ExitRefused))
));
Ok(())
}
#[tokio::test]
async fn test_a_session_ended_before_the_answer_is_not_refused() -> Result<()> {
let network = network(OnionServiceName::tcp(), EchoWorld, open_policy()).await?;
let [g, mut r02, h, r11] = network.route_hops();
r02.delegatee_public_key = PublicKey([0xff; 33]);
let route = network.route_over(OnionServiceName::tcp(), [g, r02, h, r11])?;
let opened = network
.client
.runtime
.open(OnionSessionRequest {
route,
..request(&network, OnionServiceName::tcp())?
})
.await;
assert!(matches!(
opened,
Err(Error::OnionRouteError(OnionRouteError::LoopBuild(_)))
));
Ok(())
}
fn respond(target: &OnionProxyTarget, request: &OnionHttpsRequest) -> OnionHttpsResponse {
OnionHttpsResponse {
status: 200,
headers: vec![("x-target".to_string(), target.authority())],
body: [
request.method.as_bytes(),
b" ",
request.path.as_bytes(),
b" ",
]
.concat()
.into_iter()
.chain(request.body.iter().copied())
.collect(),
}
}
#[tokio::test]
async fn test_https_loop_fetches_through_the_session_target() -> Result<()> {
let network = LoopNetwork::new(|accounting, link_sender| {
OnionAlgebra::default().register(
OnionServiceName::https(),
OnionExitSessions::new(
OnionHttpsWorld::with_egress(
open_policy(),
accounting.clone(),
OnionHttpsEgress::Test(respond),
),
open_policy(),
accounting.clone(),
link_sender.clone(),
),
)
})
.await?;
let (target, call) = OnionHttpsCall::from_url(
"https://example.com/search?q=loop",
crate::onion::https::OnionHttpsClientRequest {
method: "POST".to_string(),
body: vec![0x42; 20_000],
..Default::default()
},
)?;
let route = OnionProxyRoute {
target,
route: network.route(OnionServiceName::https())?,
};
let response = with_hang_guard(
"test_https_loop_fetches_through_the_session_target",
https_request_bound(),
OnionHttpsClient::new(network.client.runtime.clone()).request(&route, call),
)
.await?;
assert_eq!(response.status, 200);
assert_eq!(response.headers, vec![(
"x-target".to_string(),
"example.com:443".to_string()
)]);
assert_eq!(
response.body,
[
b"POST /search?q=loop ".as_slice(),
[0x42; 20_000].as_slice()
]
.concat()
);
Ok(())
}
#[tokio::test]
async fn test_caller_apis_open_tcp_and_https_sessions_at_chosen_loop_class() -> Result<()> {
let class = OnionLoopClass::KiB64;
let payload_len = 20_000;
assert!(payload_len > OnionFrame::data_capacity(OnionLoopClass::DEFAULT));
assert!(payload_len <= OnionFrame::data_capacity(class));
let network = LoopNetwork::new(|accounting, link_sender| {
OnionAlgebra::default()
.register(
OnionServiceName::tcp(),
OnionExitSessions::new(
EchoWorld,
open_policy(),
accounting.clone(),
link_sender.clone(),
),
)
.register(
OnionServiceName::https(),
OnionExitSessions::new(
OnionHttpsWorld::with_egress(
open_policy(),
accounting.clone(),
OnionHttpsEgress::Test(respond),
),
open_policy(),
accounting.clone(),
link_sender.clone(),
),
)
})
.await?;
let handle = NativeOnionCircuitHandle::new(network.client.runtime.clone());
let opened = with_hang_guard(
"open_tcp_stream_with_class(KiB64)",
ONION_SESSION_OPEN_TIMEOUT.saturating_add(EVENT_BOUND),
handle.open_tcp_stream_with_class(network.route(OnionServiceName::tcp())?, target(), class),
)
.await?;
let (local, mut peer) = tokio::io::duplex(64 * 1024);
let local: rings_gateway::BoxGatewayDuplex = Box::new(local);
opened.relay(local);
let sent = (0..payload_len)
.map(|index| u8::try_from(index % 251).expect("small"))
.collect::<Vec<_>>();
tokio::io::AsyncWriteExt::write_all(&mut peer, &sent)
.await
.expect("write local stream");
tokio::io::AsyncWriteExt::shutdown(&mut peer)
.await
.expect("shutdown local write half");
let mut echoed = Vec::new();
with_hang_guard(
"tcp KiB64 echo read_to_end",
stream_event_bound(),
tokio::io::AsyncReadExt::read_to_end(&mut peer, &mut echoed),
)
.await
.expect("read echoed stream");
assert_eq!(echoed, sent);
let (https_target, call) = OnionHttpsCall::from_url(
"https://example.com/class?b=64kib",
crate::onion::https::OnionHttpsClientRequest {
method: "POST".to_string(),
body: sent.clone(),
class: Some(class),
..Default::default()
},
)?;
assert_eq!(call.class(), class);
let https_route = OnionProxyRoute {
target: https_target,
route: network.route(OnionServiceName::https())?,
};
let response = with_hang_guard(
"request_https with KiB64",
https_request_bound(),
handle.request_https(&https_route, call),
)
.await?;
assert_eq!(response.status, 200);
assert_eq!(
response.body,
[b"POST /class?b=64kib ".as_slice(), sent.as_slice()].concat()
);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "benchmark"]
async fn bench_tcp_download_rate() -> Result<()> {
const DOWNLOAD: usize = 8 << 20;
let network = network(
OnionServiceName::tcp(),
SourceWorld(DOWNLOAD),
open_policy(),
)
.await?;
let stream = network
.client
.runtime
.open(request(&network, OnionServiceName::tcp())?)
.await?;
let (_sender, mut receiver) = stream.split();
let started = Instant::now();
let received = collect(&mut receiver).await?;
let seconds = started.elapsed().as_secs_f64();
let rate = f64::from(u32::try_from(received.len()).expect("small")) / seconds;
println!(
"tcp download: {} bytes in {seconds:.2} s = {rate:.0} B/s",
received.len()
);
assert_eq!(received.len(), DOWNLOAD);
assert!(rate >= 1_000_000.0, "{rate:.0} B/s is under 1 MB/s");
Ok(())
}