//! Real gateway fixture over TLS 1.3 (LNEx v3). //! Run with VNOX_GATEWAY_BIN=/path/to/vnox-gateway cargo test --test gateway_interop -- --ignored. use std::{ path::PathBuf, process::{Child, Command, Stdio}, time::Duration, }; use vnox_client::{ identity, net::{self, NetCommand, NetEvent, NetHandle, TrustProblem, TrustStore}, }; struct Gateway { child: Child, directory: PathBuf, } impl Drop for Gateway { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); let _ = std::fs::remove_dir_all(&self.directory); } } async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> NetEvent { static STAGE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let stage = STAGE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; eprintln!("waiting for gateway fixture stage {stage}"); tokio::time::timeout(Duration::from_secs(8), async { loop { if let Some(event) = handle.try_recv() { if predicate(&event) { return event; } if let NetEvent::Disconnected { ref reason, .. } = event { panic!("unexpected disconnect: {reason}"); } if let NetEvent::Error { code, ref message } = event { panic!("gateway error {code}: {message}"); } if let NetEvent::WebhookError(ref result) = event { panic!( "unexpected webhook error at stage {stage}, request {}: {} ({})", result.request_id, result.message, result.code ); } } tokio::time::sleep(Duration::from_millis(5)).await; } }) .await .unwrap_or_else(|_| panic!("gateway event timeout at stage {stage}")) } /// First connection: the client must stop at the untrusted certificate, show the same /// fingerprint the gateway published, and connect only after the fingerprint is pinned. async fn connect_with_first_trust(handle: &NetHandle, address: &str, published: &str) { handle .send(NetCommand::Connect { address: address.into(), auto_reconnect: false, }) .await; let prompt = event(handle, |e| matches!(e, NetEvent::TrustProblem(_))).await; let NetEvent::TrustProblem(TrustProblem::Untrusted { fingerprint, .. }) = prompt else { panic!("expected the first-use trust prompt, got {prompt:?}"); }; assert_eq!( fingerprint, published, "the prompt must show the fingerprint published by the gateway" ); event(handle, |e| { matches!( e, NetEvent::Disconnected { will_retry: false, .. } ) }) .await; let key = net::trust::parse_address(address).unwrap().key; handle.trust().pin(&key, &fingerprint).unwrap(); handle .send(NetCommand::Connect { address: address.into(), auto_reconnect: false, }) .await; } fn free_port() -> u16 { std::net::TcpListener::bind("127.0.0.1:0") .unwrap() .local_addr() .unwrap() .port() } #[tokio::test] #[ignore = "requires a freshly built current VNOX gateway binary"] async fn native_network_connects_signed_v3_over_tls_and_exchanges_protobuf_chat() { let binary = std::env::var_os("VNOX_GATEWAY_BIN") .expect("set VNOX_GATEWAY_BIN to the current server binary"); let directory = std::env::temp_dir().join(format!("vnox-interop-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&directory).unwrap(); let port = free_port(); let config = format!( r#" [node] name = "interop-node" address = "127.0.0.1" [gateway] bind = "127.0.0.1:{port}" admin_bind = "127.0.0.1:0" message_rate_per_sec = 0 [voice] bind = "127.0.0.1:7700" [storage] data_dir = "{}" backend = "sqlite" sqlite_path = "{}/fixture.db" [server] mode = "private" "#, directory.display(), directory.display() ); let config_path = directory.join("config.toml"); std::fs::write(&config_path, config).unwrap(); let child = Command::new(binary) .arg("--config") .arg(config_path) .stdout(Stdio::null()) .stderr(Stdio::inherit()) .spawn() .unwrap(); let data_dir = directory.clone(); let _gateway = Gateway { child, directory }; let address = format!("127.0.0.1:{port}"); tokio::time::timeout(Duration::from_secs(8), async { loop { if tokio::net::TcpStream::connect(&address).await.is_ok() { break; } tokio::time::sleep(Duration::from_millis(20)).await; } }) .await .unwrap(); // In-memory identity only; never touch a real profile or encrypted vault. let alice_identity = identity::generate("interop-alice"); let alice_user_id = alice_identity.pubkey_hex.clone(); // Trust is kept in memory: never touch the real ~/.config/vnox/known_servers.json. let alice = net::spawn_with_trust(alice_identity, TrustStore::in_memory()); let published = std::fs::read_to_string(data_dir.join("tls").join("fingerprint.txt")) .unwrap() .trim() .to_string(); // A client that pinned another fingerprint is blocked before sending anything. let impostor = net::spawn_with_trust(identity::generate("interop-pin"), TrustStore::in_memory()); impostor .trust() .pin( &net::trust::parse_address(&address).unwrap().key, &"ab".repeat(32), ) .unwrap(); impostor .send(NetCommand::Connect { address: address.clone(), auto_reconnect: true, }) .await; let blocked = event(&impostor, |e| matches!(e, NetEvent::TrustProblem(_))).await; assert!(matches!( blocked, NetEvent::TrustProblem(TrustProblem::FingerprintChanged { ref actual, .. }) if actual == &published )); event(&impostor, |e| { matches!( e, NetEvent::Disconnected { will_retry: false, .. } ) }) .await; connect_with_first_trust(&alice, &address, &published).await; event( &alice, |e| matches!(e,NetEvent::Connected {node_name,..} if node_name=="interop-node"), ) .await; event( &alice, |e| matches!(e,NetEvent::ChannelState {channel_id,..} if channel_id=="general"), ) .await; alice.send(NetCommand::ChannelList).await; event(&alice, |e| matches!(e,NetEvent::ChannelListEvent {channels} if channels.iter().any(|c|c.channel_id=="general"))).await; alice .send(NetCommand::SendChat { channel_id: "general".into(), content: "Привет / hello {untrusted}".into(), reply_to: None, }) .await; let chat = event( &alice, |e| matches!(e,NetEvent::ChatMessage {content,..} if content=="Привет / hello {untrusted}"), ) .await; let NetEvent::ChatMessage { message_id, .. } = chat else { unreachable!() }; alice .send(NetCommand::MessageEdit { channel_id: "general".into(), message_id: message_id.clone(), content: "edited".into(), }) .await; event( &alice, |e| matches!(e,NetEvent::MessageEdited {content,..} if content=="edited"), ) .await; alice .send(NetCommand::MessageDelete { channel_id: "general".into(), message_id, }) .await; event(&alice, |e| matches!(e, NetEvent::MessageDeleted { .. })).await; alice .send(NetCommand::GuildCreate { name: "Webhook fixture guild".into(), }) .await; let guild = event(&alice, |e| matches!(e, NetEvent::GuildCreated { .. })).await; let NetEvent::GuildCreated { guild_id, .. } = guild else { unreachable!() }; alice .send(NetCommand::ChannelCreate { channel_id: "hook-fixture".into(), channel_name: "Integrations".into(), kind: "text".into(), guild_id: Some(guild_id), parent_id: None, position: 0, }) .await; event( &alice, |e| matches!(e,NetEvent::ChannelState {channel_id,..} if channel_id=="hook-fixture"), ) .await; use net::{WebhookOperation, wire::WebhookRequest}; alice .send(NetCommand::Webhook { operation: WebhookOperation::Create, request: WebhookRequest { channel_id: "hook-fixture".into(), name: "Fixture".into(), direction: "incoming".into(), provider: "generic".into(), request_id: "create-fixture".into(), ..Default::default() }, }) .await; let result = event( &alice, |e| matches!(e,NetEvent::WebhookResult(result) if result.request_id=="create-fixture"), ) .await; let NetEvent::WebhookResult(result) = result else { unreachable!() }; assert!(!result.secret.is_empty()); assert!( !format!("{result:?}").contains(&result.secret), "one-time secret must never enter Debug output" ); let first_secret = result.secret; let id = result.hook.unwrap().id; alice .send(NetCommand::Webhook { operation: WebhookOperation::List, request: WebhookRequest { channel_id: "hook-fixture".into(), request_id: "list-fixture".into(), ..Default::default() }, }) .await; event(&alice,|e|matches!(e,NetEvent::WebhookList(result) if result.request_id=="list-fixture" && result.hooks.iter().any(|hook|hook.id==id))).await; alice .send(NetCommand::Webhook { operation: WebhookOperation::Rotate, request: WebhookRequest { id: id.clone(), request_id: "rotate-fixture".into(), ..Default::default() }, }) .await; let rotated = event( &alice, |e| matches!(e,NetEvent::WebhookResult(result) if result.request_id=="rotate-fixture"), ) .await; let NetEvent::WebhookResult(rotated) = rotated else { unreachable!() }; assert!( !rotated.secret.is_empty() && rotated.secret != first_secret, "rotation must return a fresh secret" ); alice .send(NetCommand::Webhook { operation: WebhookOperation::Revoke, request: WebhookRequest { id, request_id: "revoke-fixture".into(), ..Default::default() }, }) .await; event(&alice,|e|matches!(e,NetEvent::WebhookResult(result) if result.request_id=="revoke-fixture" && result.secret.is_empty() && result.hook.as_ref().is_some_and(|hook|hook.revoked))).await; let guest_identity = identity::generate("webhook-unprivileged"); let guest_user_id = guest_identity.pubkey_hex.clone(); let guest = net::spawn_with_trust(guest_identity, TrustStore::in_memory()); guest .trust() .pin( &net::trust::parse_address(&format!("127.0.0.1:{port}")) .unwrap() .key, &published, ) .unwrap(); guest .send(NetCommand::Connect { address: format!("127.0.0.1:{port}"), auto_reconnect: false, }) .await; event(&guest, |e| matches!(e, NetEvent::Connected { .. })).await; guest .send(NetCommand::Webhook { operation: WebhookOperation::List, request: WebhookRequest { channel_id: "hook-fixture".into(), request_id: "denied-fixture".into(), ..Default::default() }, }) .await; event(&guest,|e|matches!(e,NetEvent::WebhookError(result) if result.request_id=="denied-fixture" && result.code==4)).await; alice .send(NetCommand::FriendRequest { target_user_id: guest_user_id.clone(), }) .await; event( &guest, |e| matches!(e,NetEvent::FriendRequested {user_id,..} if user_id==&alice_user_id), ) .await; guest .send(NetCommand::FriendAccept { user_id: alice_user_id.clone(), }) .await; event( &alice, |e| matches!(e,NetEvent::FriendAccepted {user_id,..} if user_id==&guest_user_id), ) .await; alice.send(NetCommand::FriendList).await; event(&alice,|e|matches!(e,NetEvent::FriendList {friends} if friends.iter().any(|friend|friend.user_id==guest_user_id))).await; // The server identity was stored after the first authenticated handshake. let identity_file: serde_json::Value = serde_json::from_slice(&std::fs::read(data_dir.join("server_identity.json")).unwrap()) .unwrap(); let record = alice .trust() .get( &net::trust::parse_address(&format!("127.0.0.1:{port}")) .unwrap() .key, ) .unwrap(); assert_eq!( record.identity.as_deref(), identity_file["pubkey_hex"].as_str() ); guest.send(NetCommand::Disconnect).await; alice.send(NetCommand::Disconnect).await; }