csp_e2e_receive.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. //! Example for usage of the Chat Server E2EE Protocol, connecting to the chat server and receiving incoming
  2. //! messages.
  3. #![expect(unused_crate_dependencies, reason = "Example triggered false positive")]
  4. #![expect(
  5. clippy::integer_division_remainder_used,
  6. reason = "Some internal of tokio::select triggers this"
  7. )]
  8. #![expect(
  9. unreachable_code,
  10. unused_variables,
  11. clippy::todo,
  12. reason = "TODO(LIB-16): Finalise this, then remove me"
  13. )]
  14. use core::cell::RefCell;
  15. use std::{io, sync::Arc};
  16. use anyhow::bail;
  17. use clap::{ArgAction, Parser};
  18. use libthreema::{
  19. cli::{
  20. config::{FullIdentityConfig, FullIdentityConfigOptions},
  21. provider::{InMemoryDb, InMemoryDbInitBuilder},
  22. },
  23. common::ClientInfo,
  24. csp::{
  25. CspProtocol, CspProtocolContext, CspProtocolInstruction, CspStateUpdate,
  26. payload::{IncomingPayload, MessageAck, MessageWithMetadataBox, OutgoingFrame, OutgoingPayload},
  27. },
  28. csp_e2e::{
  29. CspE2eProtocol, CspE2eProtocolContextInit,
  30. contacts::{
  31. create::{CreateContactsInstruction, CreateContactsResponse},
  32. lookup::ContactsLookupResponse,
  33. update::{UpdateContactsInstruction, UpdateContactsResponse},
  34. },
  35. message::task::incoming::{
  36. IncomingMessageInstruction, IncomingMessageLoop, IncomingMessageResponse, IncomingMessageTask,
  37. },
  38. reflect::{ReflectInstruction, ReflectResponse},
  39. transaction::{
  40. begin::{BeginTransactionInstruction, BeginTransactionResponse},
  41. commit::{CommitTransactionInstruction, CommitTransactionResponse},
  42. },
  43. },
  44. https::cli::https_client_builder,
  45. utils::logging::init_stderr_logging,
  46. };
  47. use libthreema_dependencies::data_encoding::HEXLOWER_PERMISSIVE;
  48. use tokio::{
  49. io::{AsyncReadExt as _, AsyncWriteExt as _},
  50. net::TcpStream,
  51. signal,
  52. sync::mpsc,
  53. };
  54. use tracing::{Level, debug, error, info, trace, warn};
  55. #[derive(Parser)]
  56. #[command()]
  57. struct CspE2eReceiveCommand {
  58. #[command(flatten)]
  59. config: FullIdentityConfigOptions,
  60. /// Turn on debugging information.
  61. /// Use -v -vv to control log level.
  62. #[arg(short, action = ArgAction::Count)]
  63. verbose: u8,
  64. }
  65. enum IncomingPayloadForCspE2e {
  66. Message(MessageWithMetadataBox),
  67. MessageAck(MessageAck),
  68. }
  69. enum OutgoingPayloadForCspE2e {
  70. MessageAck(MessageAck),
  71. }
  72. impl From<OutgoingPayloadForCspE2e> for OutgoingPayload {
  73. fn from(payload: OutgoingPayloadForCspE2e) -> Self {
  74. match payload {
  75. OutgoingPayloadForCspE2e::MessageAck(message_ack) => Self::MessageAck(message_ack),
  76. }
  77. }
  78. }
  79. /// Payload queues for the main process.
  80. struct PayloadQueuesForCspE2e {
  81. incoming: mpsc::Receiver<IncomingPayloadForCspE2e>,
  82. outgoing: mpsc::Sender<OutgoingPayloadForCspE2e>,
  83. }
  84. /// Payload queues for the protocol flow runner.
  85. struct PayloadQueuesForCsp {
  86. incoming: mpsc::Sender<IncomingPayloadForCspE2e>,
  87. outgoing: mpsc::Receiver<OutgoingPayloadForCspE2e>,
  88. }
  89. struct CspProtocolRunner {
  90. /// The TCP stream.
  91. stream: TcpStream,
  92. /// An instance of the [`CspProtocol`] state machine.
  93. protocol: CspProtocol,
  94. }
  95. impl CspProtocolRunner {
  96. /// Initiate a CSP protocol connection and hand out the initial `client_hello` message
  97. #[tracing::instrument(skip_all)]
  98. async fn new(
  99. server_address: Vec<(String, u16)>,
  100. context: CspProtocolContext,
  101. ) -> anyhow::Result<(Self, OutgoingFrame)> {
  102. // Connect via TCP
  103. debug!(?server_address, "Establishing TCP connection to chat server",);
  104. let tcp_stream = TcpStream::connect(
  105. server_address
  106. .first()
  107. .expect("CSP config should have at least one address"),
  108. )
  109. .await?;
  110. // Create the protocol
  111. let (csp_protocol, client_hello) = CspProtocol::new(context);
  112. Ok((
  113. Self {
  114. stream: tcp_stream,
  115. protocol: csp_protocol,
  116. },
  117. client_hello,
  118. ))
  119. }
  120. /// Do the handshake with the chat server by exchanging the following messages:
  121. ///
  122. /// ```txt
  123. /// C -- client-hello -> S
  124. /// C <- server-hello -- S
  125. /// C ---- login ---- -> S
  126. /// C <-- login-ack ---- S
  127. /// ```
  128. #[tracing::instrument(skip_all)]
  129. async fn run_handshake_flow(&mut self, client_hello: OutgoingFrame) -> anyhow::Result<()> {
  130. // Send the client hello
  131. debug!(length = client_hello.0.len(), "Sending client hello");
  132. self.send(&client_hello.0).await?;
  133. // Handshake by polling the CSP state
  134. for iteration in 1_usize.. {
  135. trace!("Iteration #{iteration}");
  136. // Receive required bytes and add them
  137. let bytes = self.receive_required().await?;
  138. self.protocol.add_chunks(&[&bytes])?;
  139. // Handle instruction
  140. let Some(instruction) = self.protocol.poll()? else {
  141. continue;
  142. };
  143. // We do not expect an incoming payload at this stage
  144. if let Some(incoming_payload) = instruction.incoming_payload {
  145. let message = "Unexpected incoming payload during handshake";
  146. error!(?incoming_payload, message);
  147. bail!(message)
  148. }
  149. // Send any outgoing frame
  150. if let Some(frame) = instruction.outgoing_frame {
  151. self.send(&frame.0).await?;
  152. }
  153. // Check if we've completed the handshake
  154. if let Some(CspStateUpdate::PostHandshake(login_ack_data)) = instruction.state_update {
  155. info!(?login_ack_data, "Handshake complete");
  156. break;
  157. }
  158. }
  159. Ok(())
  160. }
  161. /// Run the payload exchange flow until stopped.
  162. #[tracing::instrument(skip_all)]
  163. async fn run_payload_flow(&mut self, mut queues: PayloadQueuesForCsp) -> anyhow::Result<()> {
  164. let mut read_buffer = [0_u8; 8192];
  165. let mut next_instruction: Option<CspProtocolInstruction> = None;
  166. for iteration in 1_usize.. {
  167. trace!("Iteration #{iteration}");
  168. // Poll for an instruction, if necessary
  169. if next_instruction.is_none() {
  170. next_instruction = self.protocol.poll()?;
  171. }
  172. // Wait for more input, if necessary
  173. if next_instruction.is_none() {
  174. next_instruction = tokio::select! {
  175. // Forward any incoming chunks from the TCP stream
  176. _ = self.stream.readable() => {
  177. let length = self.try_receive(&mut read_buffer)?;
  178. // Add chunks (poll in the next iteration)
  179. self.protocol
  180. .add_chunks(&[read_buffer.get(..length)
  181. .expect("Amount of read bytes should be available")])?;
  182. None
  183. },
  184. // Forward any outgoing payloads
  185. outgoing_payload = queues.outgoing.recv() => {
  186. if let Some(outgoing_payload) = outgoing_payload {
  187. let outgoing_payload = OutgoingPayload::from(outgoing_payload);
  188. debug!(?outgoing_payload, "Sending payload");
  189. Some(self.protocol.create_payload(&outgoing_payload)?)
  190. } else {
  191. break
  192. }
  193. }
  194. };
  195. }
  196. // Handle instruction
  197. let Some(current_instruction) = next_instruction.take() else {
  198. continue;
  199. };
  200. // We do not expect any state updates at this stage
  201. if let Some(state_update) = current_instruction.state_update {
  202. let message = "Unexpected state update after handshake";
  203. error!(?state_update, message);
  204. bail!(message)
  205. }
  206. // Handle any incoming payload
  207. if let Some(incoming_payload) = current_instruction.incoming_payload {
  208. debug!(?incoming_payload, "Received payload");
  209. match incoming_payload {
  210. IncomingPayload::EchoRequest(echo_payload) => {
  211. // Respond to echo request
  212. next_instruction = Some(
  213. self.protocol
  214. .create_payload(&OutgoingPayload::EchoResponse(echo_payload))?,
  215. );
  216. },
  217. IncomingPayload::MessageWithMetadataBox(payload) => {
  218. // Forward message
  219. queues
  220. .incoming
  221. .send(IncomingPayloadForCspE2e::Message(payload))
  222. .await?;
  223. },
  224. IncomingPayload::MessageAck(payload) => {
  225. // Forward message ack
  226. queues
  227. .incoming
  228. .send(IncomingPayloadForCspE2e::MessageAck(payload))
  229. .await?;
  230. },
  231. IncomingPayload::EchoResponse(_)
  232. | IncomingPayload::QueueSendComplete
  233. | IncomingPayload::DeviceCookieChangeIndication
  234. | IncomingPayload::CloseError(_)
  235. | IncomingPayload::ServerAlert(_)
  236. | IncomingPayload::UnknownPayload { .. } => {},
  237. }
  238. }
  239. // Send any outgoing frame
  240. if let Some(frame) = current_instruction.outgoing_frame {
  241. self.send(&frame.0).await?;
  242. }
  243. }
  244. Ok(())
  245. }
  246. /// Shut down the TCP connection
  247. #[tracing::instrument(skip_all)]
  248. async fn shutdown(&mut self) -> anyhow::Result<()> {
  249. info!("Shutting down TCP connection");
  250. Ok(self.stream.shutdown().await?)
  251. }
  252. /// Send bytes to the server over the TCP connection
  253. #[tracing::instrument(skip_all, fields(bytes_length = bytes.len()))]
  254. async fn send(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
  255. trace!(length = bytes.len(), "Sending bytes");
  256. self.stream.write_all(bytes).await?;
  257. Ok(())
  258. }
  259. #[tracing::instrument(skip_all)]
  260. async fn receive_required(&mut self) -> anyhow::Result<Vec<u8>> {
  261. // Get the minimum amount of bytes we'll need to receive
  262. let length = self.protocol.next_required_length()?;
  263. let mut buffer = vec![0; length];
  264. trace!(?length, "Reading bytes");
  265. // If there is nothing to read, return immediately
  266. if length == 0 {
  267. return Ok(buffer);
  268. }
  269. // Read the exact number of bytes required
  270. let _ = self.stream.read_exact(&mut buffer).await?;
  271. // Read more if available
  272. match self.stream.try_read_buf(&mut buffer) {
  273. Ok(0) => {
  274. // Remote shut down our reading end gracefully.
  275. //
  276. // IMPORTANT: An implementation needs to ensure that it stops gracefully by processing any
  277. // remaining payloads prior to stopping the protocol. This example implementation ensures this
  278. // by handling all pending instructions prior to polling for more data. The only case we bail
  279. // is therefore when our instruction queue is already dry.
  280. bail!("TCP reading end closed")
  281. },
  282. Ok(length) => {
  283. trace!(length, "Got additional bytes");
  284. },
  285. Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
  286. trace!("No additional bytes available");
  287. },
  288. Err(error) => {
  289. return Err(error.into());
  290. },
  291. }
  292. debug!(length = buffer.len(), "Received bytes");
  293. Ok(buffer)
  294. }
  295. #[tracing::instrument(skip_all)]
  296. fn try_receive(&mut self, buffer: &mut [u8]) -> anyhow::Result<usize> {
  297. match self.stream.try_read(buffer) {
  298. Ok(0) => {
  299. // Remote shut down our reading end. But we still need to process the previously
  300. // read bytes.
  301. warn!("TCP reading end closed");
  302. Ok(0)
  303. },
  304. Ok(length) => {
  305. debug!(length, "Received bytes");
  306. Ok(length)
  307. },
  308. Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
  309. trace!("No bytes to receive");
  310. Ok(0)
  311. },
  312. Err(error) => Err(error.into()),
  313. }
  314. }
  315. }
  316. struct CspE2eProtocolRunner {
  317. /// An instance of the [`CspE2eProtocol`] state machine.
  318. protocol: CspE2eProtocol,
  319. /// HTTP client.
  320. http_client: reqwest::Client,
  321. }
  322. impl CspE2eProtocolRunner {
  323. #[tracing::instrument(skip_all)]
  324. fn new(http_client: reqwest::Client, context: CspE2eProtocolContextInit) -> anyhow::Result<Self> {
  325. Ok(Self {
  326. protocol: CspE2eProtocol::new(context),
  327. http_client,
  328. })
  329. }
  330. /// Run the receive flow until stopped.
  331. #[tracing::instrument(skip_all)]
  332. async fn run_receive_flow(&mut self, mut queues: PayloadQueuesForCspE2e) -> anyhow::Result<()> {
  333. let mut pending_task: Option<IncomingMessageTask> = None;
  334. for iteration in 1_usize.. {
  335. trace!("Receive flow iteration #{iteration}");
  336. // Handle any incoming payloads until we have a task
  337. let Some(task) = &mut pending_task else {
  338. match queues.incoming.recv().await {
  339. Some(IncomingPayloadForCspE2e::Message(message)) => {
  340. trace!(
  341. message = HEXLOWER_PERMISSIVE.encode(&message.bytes),
  342. "Raw incoming message"
  343. );
  344. info!(?message, "Incoming message");
  345. pending_task = Some(self.protocol.handle_incoming_message(message));
  346. },
  347. Some(IncomingPayloadForCspE2e::MessageAck(message_ack)) => {
  348. warn!(?message_ack, "Unexpected message-ack");
  349. },
  350. None => {},
  351. }
  352. continue;
  353. };
  354. // Handle task
  355. match task.poll(self.protocol.context())? {
  356. IncomingMessageLoop::Instruction(IncomingMessageInstruction::FetchSender(instruction)) => {
  357. // Run both requests simultaneously
  358. let work_directory_request_future = async {
  359. match instruction.work_directory_request {
  360. Some(work_directory_request) => {
  361. work_directory_request.send(&self.http_client).await.map(Some)
  362. },
  363. None => Ok(None),
  364. }
  365. };
  366. let (directory_result, work_directory_result) = tokio::join!(
  367. instruction.directory_request.send(&self.http_client),
  368. work_directory_request_future,
  369. );
  370. // Forward response
  371. task.response(IncomingMessageResponse::FetchSender(ContactsLookupResponse {
  372. directory_result,
  373. work_directory_result: work_directory_result.transpose(),
  374. }))?;
  375. },
  376. IncomingMessageLoop::Instruction(IncomingMessageInstruction::CreateContact(instruction)) => {
  377. match instruction {
  378. CreateContactsInstruction::BeginTransaction(instruction) => {
  379. // Begin transaction and forward response, if any
  380. let response = self.begin_transaction(instruction).await?;
  381. if let Some(response) = response {
  382. task.response(IncomingMessageResponse::CreateContact(
  383. CreateContactsResponse::BeginTransactionResponse(response),
  384. ))?;
  385. }
  386. },
  387. CreateContactsInstruction::ReflectAndCommitTransaction(instruction) => {
  388. // Reflect and commit transaction and forward response
  389. task.response(IncomingMessageResponse::CreateContact(
  390. CreateContactsResponse::CommitTransactionResponse(
  391. self.reflect_and_commit_transaction(instruction).await?,
  392. ),
  393. ))?;
  394. },
  395. }
  396. },
  397. IncomingMessageLoop::Instruction(IncomingMessageInstruction::UpdateContact(instruction)) => {
  398. match instruction {
  399. UpdateContactsInstruction::BeginTransaction(instruction) => {
  400. // Begin transaction and forward response, if any
  401. let response = self.begin_transaction(instruction).await?;
  402. if let Some(response) = response {
  403. task.response(IncomingMessageResponse::UpdateContact(
  404. UpdateContactsResponse::BeginTransactionResponse(response),
  405. ))?;
  406. }
  407. },
  408. UpdateContactsInstruction::ReflectAndCommitTransaction(instruction) => {
  409. // Reflect and commit transaction and forward response
  410. task.response(IncomingMessageResponse::UpdateContact(
  411. UpdateContactsResponse::CommitTransactionResponse(
  412. self.reflect_and_commit_transaction(instruction).await?,
  413. ),
  414. ))?;
  415. },
  416. }
  417. },
  418. IncomingMessageLoop::Instruction(IncomingMessageInstruction::ReflectMessage(instruction)) => {
  419. task.response(IncomingMessageResponse::ReflectMessage(
  420. self.reflect(instruction).await?,
  421. ))?;
  422. },
  423. IncomingMessageLoop::Done(result) => {
  424. // Send message acknowledgement, if any
  425. if let Some(outgoing_message_ack) = result.outgoing_message_ack {
  426. queues
  427. .outgoing
  428. .send(OutgoingPayloadForCspE2e::MessageAck(outgoing_message_ack))
  429. .await?;
  430. }
  431. pending_task = None;
  432. // TODO(LIB-16). Enqueue outgoing message task, if any
  433. },
  434. }
  435. }
  436. Ok(())
  437. }
  438. #[tracing::instrument(skip_all)]
  439. async fn begin_transaction(
  440. &self,
  441. instruction: BeginTransactionInstruction,
  442. ) -> anyhow::Result<Option<BeginTransactionResponse>> {
  443. match instruction {
  444. BeginTransactionInstruction::TransactionRejected => {
  445. // TODO(LIB-16). Await TransactionEnded
  446. Ok(None)
  447. },
  448. BeginTransactionInstruction::BeginTransaction { message } => {
  449. // TODO(LIB-16). Send `BeginTransaction, await BeginTransactionAck or TransactionRejected,
  450. // then return BeginTransactionResponse(message)
  451. Ok(Some(BeginTransactionResponse::BeginTransactionReply(todo!())))
  452. },
  453. BeginTransactionInstruction::AbortTransaction { message } => {
  454. // TODO(LIB-16). Send `CommitTransaction`, await CommitTransactionAck, then return
  455. // AbortTransaction(CommitTransactionAck)
  456. Ok(Some(BeginTransactionResponse::AbortTransactionResponse(todo!())))
  457. },
  458. }
  459. }
  460. #[tracing::instrument(skip_all)]
  461. async fn reflect_and_commit_transaction(
  462. &self,
  463. instruction: CommitTransactionInstruction,
  464. ) -> anyhow::Result<CommitTransactionResponse> {
  465. // TODO(LIB-16). Reflect messages, then immediately commit. Await CommitAck and gather any
  466. // reflect-acks
  467. Ok(CommitTransactionResponse {
  468. acknowledged_reflect_ids: todo!(),
  469. commit_transaction_ack: todo!(),
  470. })
  471. }
  472. #[tracing::instrument(skip_all)]
  473. async fn reflect(&self, instruction: ReflectInstruction) -> anyhow::Result<ReflectResponse> {
  474. // TODO(LIB-16). Reflect messages, then wait for corresponding reflect-acks
  475. Ok(ReflectResponse {
  476. acknowledged_reflect_ids: todo!(),
  477. })
  478. }
  479. }
  480. #[tokio::main]
  481. async fn main() -> anyhow::Result<()> {
  482. // Parse arguments for command
  483. let arguments = CspE2eReceiveCommand::parse();
  484. // Configure logging
  485. let log_level = match arguments.verbose {
  486. 1 => Level::DEBUG,
  487. 2 => Level::TRACE,
  488. _ => Level::INFO,
  489. };
  490. init_stderr_logging(log_level);
  491. // Create HTTP client
  492. let http_client = https_client_builder().build()?;
  493. let config = FullIdentityConfig::from_options(&http_client, arguments.config).await?;
  494. // Create CSP E2EE protocol context
  495. let mut database = InMemoryDb::from(InMemoryDbInitBuilder::default().build()?);
  496. let csp_e2e_context = CspE2eProtocolContextInit {
  497. client_info: ClientInfo::Libthreema,
  498. config: Arc::clone(&config.minimal.common.config),
  499. csp_e2e: config.csp_e2e_context(),
  500. d2x: config.d2x_context_init(Box::new(RefCell::new(database.d2d_nonce_provider()))),
  501. providers: database.csp_e2e_protocol_providers(),
  502. };
  503. // Create payload queues
  504. let (csp_e2e_queues, csp_queues) = {
  505. let incoming_payload = mpsc::channel(4);
  506. let outgoing_payload = mpsc::channel(4);
  507. (
  508. PayloadQueuesForCspE2e {
  509. incoming: incoming_payload.1,
  510. outgoing: outgoing_payload.0,
  511. },
  512. PayloadQueuesForCsp {
  513. incoming: incoming_payload.0,
  514. outgoing: outgoing_payload.1,
  515. },
  516. )
  517. };
  518. // Create CSP protocol and establish a connection
  519. let (mut csp_runner, client_hello) = CspProtocolRunner::new(
  520. config
  521. .minimal
  522. .common
  523. .config
  524. .chat_server_address
  525. .addresses(&config.csp_server_group),
  526. config
  527. .csp_context_init()
  528. .try_into()
  529. .expect("Configuration should be valid"),
  530. )
  531. .await?;
  532. // Run the handshake flow
  533. csp_runner.run_handshake_flow(client_hello).await?;
  534. // Create CSP E2E protocol
  535. let mut csp_e2e_protocol = CspE2eProtocolRunner::new(http_client, csp_e2e_context)?;
  536. // Run the protocols
  537. tokio::select! {
  538. _ = csp_runner.run_payload_flow(csp_queues) => {},
  539. _ = csp_e2e_protocol.run_receive_flow(csp_e2e_queues) => {},
  540. _ = signal::ctrl_c() => {},
  541. };
  542. // Shut down
  543. csp_runner.shutdown().await?;
  544. Ok(())
  545. }
  546. #[test]
  547. fn verify_cli() {
  548. use clap::CommandFactory;
  549. CspE2eReceiveCommand::command().debug_assert();
  550. }