lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit 605c23d5d5edfdbf86e548b7ac0ce57cd0a7ca22
parent 2ce4ce5107b5ac27938bc271723c8dd52fd4d3ef
Author: triesap <tyson@radroots.org>
Date:   Tue, 20 Oct 2026 02:17:44 +0000

transport: Introduce neutral socket I/O and native provider

- Define owned frames and revocable admission without platform API leakage
- Retain bounded native DNS, pinned TCP, stock-root TLS and plaintext metering
- Verify real socket effects, cancellation, original bytes and parser bounds
- Keep the new package private with immutable provenance and passing coverage

Diffstat:
MCargo.lock | 15+++++++++++++++
MCargo.toml | 2++
Mcontracts/api_baselines/radroots_transport.txt | 37+++++++++++++++++++++++++++++++++++++
Mcontracts/coverage.toml | 1+
Mcontracts/crates/catalog.v2.toml | 20+++++++++++++++++++-
Mcontracts/crates/generated/package_groups.v1.toml | 6+++---
Mcontracts/crates/generated/platform_inventory.v1.toml | 4++--
Mcontracts/crates/generated/release_inventory.v2.toml | 4++--
Mcontracts/releases/publish_policy.toml | 1+
Mcrates/transport/README.md | 7+++++++
Mcrates/transport/src/host.rs | 4++++
Acrates/transport/src/host/websocket.rs | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr_native/Cargo.toml | 29+++++++++++++++++++++++++++++
Acrates/transport_nostr_native/LICENSE-APACHE | 201+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr_native/LICENSE-MIT | 21+++++++++++++++++++++
Acrates/transport_nostr_native/README.md | 9+++++++++
Acrates/transport_nostr_native/src/connector.rs | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr_native/src/lib.rs | 9+++++++++
Acrates/transport_nostr_native/src/socket.rs | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr_native/src/wire.rs | 240+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr_native/src/wire_tests.rs | 336+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr_native/tests/io.rs | 348+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
22 files changed, 1744 insertions(+), 8 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3788,6 +3788,21 @@ dependencies = [ ] [[package]] +name = "radroots_transport_nostr_native" +version = "0.1.0-alpha" +dependencies = [ + "futures", + "radroots_transport", + "radroots_transport_nostr", + "rustls", + "tokio", + "tokio-rustls", + "tokio-tungstenite", + "url", + "webpki-roots 0.26.11", +] + +[[package]] name = "radroots_transport_reticulum" version = "0.1.0-alpha" dependencies = [ diff --git a/Cargo.toml b/Cargo.toml @@ -19,6 +19,7 @@ members = [ "crates/geonames", "crates/nostrdb", "crates/transport_nostr", + "crates/transport_nostr_native", "crates/transport_reticulum", "crates/simplex_app_store", "crates/simplex_agent_proto", @@ -135,6 +136,7 @@ radroots_runtime_manager = { path = "crates/runtime_manager", version = "=0.1.0- radroots_service_host = { path = "crates/service_host", version = "=0.1.0-alpha", default-features = false } radroots_service_sqlite = { path = "crates/service_sqlite", version = "=0.1.0-alpha", default-features = false } radroots_transport_nostr = { package = "radroots_transport_nostr", path = "crates/transport_nostr", version = "=0.1.0-alpha", default-features = false } +radroots_transport_nostr_native = { package = "radroots_transport_nostr_native", path = "crates/transport_nostr_native", version = "=0.1.0-alpha", default-features = false } radroots_transport_reticulum = { path = "crates/transport_reticulum", version = "=0.1.0-alpha", default-features = false } radroots_simplex_agent_proto = { path = "crates/simplex_agent_proto", version = "=0.1.0-alpha", default-features = false } radroots_simplex_chat_proto = { path = "crates/simplex_chat_proto", version = "=0.1.0-alpha", default-features = false } diff --git a/contracts/api_baselines/radroots_transport.txt b/contracts/api_baselines/radroots_transport.txt @@ -168,6 +168,43 @@ pub radroots_transport::error::Error::UnsupportedOperation impl core::fmt::Display for radroots_transport::error::Error pub fn radroots_transport::error::Error::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub mod radroots_transport::host +pub mod radroots_transport::host::websocket +#[non_exhaustive] pub enum radroots_transport::host::websocket::Error +pub radroots_transport::host::websocket::Error::Closed +pub radroots_transport::host::websocket::Error::Policy +pub radroots_transport::host::websocket::Error::Protocol +pub radroots_transport::host::websocket::Error::Timeout +pub radroots_transport::host::websocket::Error::Unavailable +pub radroots_transport::host::websocket::Error::Unsupported +impl core::error::Error for radroots_transport::host::websocket::Error +impl core::fmt::Display for radroots_transport::host::websocket::Error +pub fn radroots_transport::host::websocket::Error::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_transport::host::websocket::Frame +pub radroots_transport::host::websocket::Frame::Binary(alloc::vec::Vec<u8>) +pub radroots_transport::host::websocket::Frame::Close(core::option::Option<radroots_transport::host::websocket::CloseFrame>) +pub radroots_transport::host::websocket::Frame::Ping(alloc::vec::Vec<u8>) +pub radroots_transport::host::websocket::Frame::Pong(alloc::vec::Vec<u8>) +pub radroots_transport::host::websocket::Frame::Text(alloc::string::String) +impl core::fmt::Debug for radroots_transport::host::websocket::Frame +pub fn radroots_transport::host::websocket::Frame::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_transport::host::websocket::CloseFrame +pub radroots_transport::host::websocket::CloseFrame::code: u16 +pub radroots_transport::host::websocket::CloseFrame::reason: alloc::string::String +impl core::fmt::Debug for radroots_transport::host::websocket::CloseFrame +pub fn radroots_transport::host::websocket::CloseFrame::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub trait radroots_transport::host::websocket::Admission: core::marker::Send + core::marker::Sync +pub fn radroots_transport::host::websocket::Admission::admitted_read(&self, &core::task::wake::Context<'_>) -> bool +pub fn radroots_transport::host::websocket::Admission::admitted_write(&self, &core::task::wake::Context<'_>) -> bool +pub fn radroots_transport::host::websocket::Admission::charge(&self, usize, usize, usize) -> bool +pub fn radroots_transport::host::websocket::Admission::permits_address(&self, core::net::ip_addr::IpAddr) -> bool +pub trait radroots_transport::host::websocket::Connector: core::fmt::Debug + core::marker::Send + core::marker::Sync +pub fn radroots_transport::host::websocket::Connector::connect<'a>(&'a self, &'a str, core::time::Duration, core::num::nonzero::NonZeroUsize, alloc::sync::Arc<dyn radroots_transport::host::websocket::Admission>) -> radroots_transport::host::websocket::IoFuture<'a, core::result::Result<alloc::sync::Arc<dyn radroots_transport::host::websocket::Socket>, radroots_transport::host::websocket::Error>> +pub fn radroots_transport::host::websocket::Connector::supports_ping(&self) -> bool +pub trait radroots_transport::host::websocket::Socket: core::marker::Send + core::marker::Sync +pub fn radroots_transport::host::websocket::Socket::close(&self) -> radroots_transport::host::websocket::IoFuture<'_, core::result::Result<(), radroots_transport::host::websocket::Error>> +pub fn radroots_transport::host::websocket::Socket::receive(&self) -> radroots_transport::host::websocket::IoFuture<'_, core::result::Result<core::option::Option<radroots_transport::host::websocket::Frame>, radroots_transport::host::websocket::Error>> +pub fn radroots_transport::host::websocket::Socket::send(&self, radroots_transport::host::websocket::Frame) -> radroots_transport::host::websocket::IoFuture<'_, core::result::Result<(), radroots_transport::host::websocket::Error>> +pub type radroots_transport::host::websocket::IoFuture<'a, T> = core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = T> + core::marker::Send + 'a)>> pub trait radroots_transport::host::HostBound: core::marker::Send + core::marker::Sync impl<T: core::marker::Send + core::marker::Sync + ?core::marker::Sized> radroots_transport::host::HostBound for T pub trait radroots_transport::host::MoveBound: core::marker::Send diff --git a/contracts/coverage.toml b/contracts/coverage.toml @@ -74,6 +74,7 @@ crates = [ "radroots_storage_sqlite", "radroots_sync", "radroots_transport_nostr", + "radroots_transport_nostr_native", "radroots_transport_reticulum", "radroots_replica_store", "radroots_replica_store_wasm", diff --git a/contracts/crates/catalog.v2.toml b/contracts/crates/catalog.v2.toml @@ -7,7 +7,7 @@ rust_version = "1.99.0" edition = "2024" resolver = "3" public_package_count = 21 -package_count = 54 +package_count = 55 digest_algorithm = "sha256-raw-bytes-v1" source_tree_digest_algorithm = "sha256-git-ls-tree-r-v1" native_introduction_tree_digest_algorithm = "sha256-git-tree-records-z-v1" @@ -409,6 +409,24 @@ compatibility = ["rust_api", "network", "features", "package"] replaces = [] [[package]] +name = "radroots_transport_nostr_native" +path = "crates/transport_nostr_native" +state = "active" +tier = "adapter" +visibility = "private_adapter" +publish = false +version = "0.1.0-alpha" +license = "MIT OR Apache-2.0" +platforms = ["native"] +groups = ["coverage_required"] +owners = ["transport"] +permitted_dependency_tiers = ["foundation", "domain", "spi", "adapter"] +provenance_kind = "native" +introduction_tree_sha256 = "41069127e5d92252c4610c17b277fc817529052c416a43f798124cd890f420f7" +compatibility = ["package_private", "rust_api", "network"] +replaces = [] + +[[package]] name = "radroots_geonames" path = "crates/geonames" state = "active" diff --git a/contracts/crates/generated/package_groups.v1.toml b/contracts/crates/generated/package_groups.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.package-groups.v1" -catalog_sha256 = "39ff80bd34966be30ef54f5591d9ca149b869864ac3bcf1c7b97d91041759caa" +catalog_sha256 = "ab9b926b02a729d897246902ac2bed7aa98c61ec002d5be959ecd1f624d14488" [[group]] id = "boundaries" @@ -9,8 +9,8 @@ reserved_packages = [] [[group]] id = "coverage_required" -packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_indexeddb", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] -active_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_indexeddb", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] +packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_indexeddb", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_nostr_native", "radroots_transport_reticulum", "xtask"] +active_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_indexeddb", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_nostr_native", "radroots_transport_reticulum", "xtask"] reserved_packages = [] [[group]] diff --git a/contracts/crates/generated/platform_inventory.v1.toml b/contracts/crates/generated/platform_inventory.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.platform-inventory.v1" -catalog_sha256 = "39ff80bd34966be30ef54f5591d9ca149b869864ac3bcf1c7b97d91041759caa" +catalog_sha256 = "ab9b926b02a729d897246902ac2bed7aa98c61ec002d5be959ecd1f624d14488" [[platform]] id = "any" @@ -7,7 +7,7 @@ packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", [[platform]] id = "native" -packages = ["radroots_core_bindings", "radroots_event_bindings", "radroots_geonames", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_nostrdb", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_app_store", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade_bindings", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] +packages = ["radroots_core_bindings", "radroots_event_bindings", "radroots_geonames", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_nostrdb", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_sync", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_app_store", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade_bindings", "radroots_transport_nostr", "radroots_transport_nostr_native", "radroots_transport_reticulum", "xtask"] [[platform]] id = "wasm32" diff --git a/contracts/crates/generated/release_inventory.v2.toml b/contracts/crates/generated/release_inventory.v2.toml @@ -1,7 +1,7 @@ schema = "radroots.workspace.release-inventory.v2" -catalog_sha256 = "39ff80bd34966be30ef54f5591d9ca149b869864ac3bcf1c7b97d91041759caa" +catalog_sha256 = "ab9b926b02a729d897246902ac2bed7aa98c61ec002d5be959ecd1f624d14488" architecture = "radroots.crates.release.v2" version = "0.1.0-alpha" public_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_sdk", "radroots_secrets", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade", "radroots_transport", "radroots_transport_nostr"] -private_packages = ["radroots_core_bindings", "radroots_event_bindings", "radroots_event_codec_wasm", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_storage_indexeddb", "radroots_test_fixtures", "radroots_trade_bindings", "radroots_transport_reticulum", "xtask"] +private_packages = ["radroots_core_bindings", "radroots_event_bindings", "radroots_event_codec_wasm", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_storage_indexeddb", "radroots_test_fixtures", "radroots_trade_bindings", "radroots_transport_nostr_native", "radroots_transport_reticulum", "xtask"] reserved_packages = [] diff --git a/contracts/releases/publish_policy.toml b/contracts/releases/publish_policy.toml @@ -64,6 +64,7 @@ private = [ "radroots_service_sqlite", "radroots_sql_core", "radroots_storage_indexeddb", + "radroots_transport_nostr_native", ] build_codegen = [ "radroots_core_bindings", diff --git a/crates/transport/README.md b/crates/transport/README.md @@ -1,5 +1,12 @@ # radroots_transport +The `std` host boundary `host::websocket` exchanges owned frames, revocable +admission and bounded errors with concrete native or browser socket providers. +It owns no protocol session, reconnect policy, executor or concrete socket. +Browser providers keep DOM objects local and exchange safe channel handles; +application futures retain their target-specific host bounds. The data model +and source/sink SPIs remain available without `std`. + `radroots_transport` is the transport-neutral host SPI for moving verified Radroots events between explicit targets. It owns extensible transport and target identities, separate source and sink capabilities, bounded fetch and diff --git a/crates/transport/src/host.rs b/crates/transport/src/host.rs @@ -1,5 +1,9 @@ //! Target-aware host bounds and shared handles for transport composition. +/// Concrete WebSocket I/O supplied by native or browser hosts. +#[cfg(feature = "std")] +pub mod websocket; + /// Native host implementations are thread safe; browser hosts may be local. #[cfg(not(target_arch = "wasm32"))] pub trait HostBound: Send + Sync {} diff --git a/crates/transport/src/host/websocket.rs b/crates/transport/src/host/websocket.rs @@ -0,0 +1,178 @@ +//! Byte I/O for a shared protocol session. Hosts own sockets; protocol adapters +//! own sessions, destination authority, ingress budgets and exact publication. + +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::{fmt, future::Future, net::IpAddr, pin::Pin, task::Context, time::Duration}; + +/// Owned channel futures may cross threads. Browser implementations keep DOM +/// objects in their origin-thread actor and return only safe message handles. +/// This bound does not apply to application or browser session futures. +pub type IoFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; + +/// Bounded failures retain no provider errors, destinations or wire content. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum Error { + /// Explicit destination or ingress authority refused the effect. + Policy, + /// DNS, TCP, TLS or the WebSocket handshake could not complete. + Unavailable, + /// The original connection deadline elapsed. + Timeout, + /// The connection no longer admits I/O. + Closed, + /// The peer or caller supplied an invalid or oversized frame. + Protocol, + /// This host cannot perform the requested operation. + Unsupported, +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Policy => "socket authority denied", + Self::Unavailable => "socket connection unavailable", + Self::Timeout => "socket connection deadline elapsed", + Self::Closed => "socket connection closed", + Self::Protocol => "socket frame refused", + Self::Unsupported => "socket operation unsupported", + }) + } +} + +impl std::error::Error for Error {} + +/// Original close code and reason. Debug formatting omits peer text. +#[derive(Clone, Eq, PartialEq)] +pub struct CloseFrame { + /// WebSocket close code. + pub code: u16, + /// Uninterpreted peer close reason. + pub reason: String, +} + +impl fmt::Debug for CloseFrame { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("CloseFrame") + .field("code", &self.code) + .finish_non_exhaustive() + } +} + +/// Original message bytes; the host never parses or reserializes protocol data. +#[derive(Clone, Eq, PartialEq)] +#[non_exhaustive] +pub enum Frame { + /// UTF-8 message bytes, including original whitespace and member order. + Text(String), + /// Original binary message bytes. + Binary(Vec<u8>), + /// Native control frame; browsers do not expose this operation. + Ping(Vec<u8>), + /// Native control frame; browsers do not expose this operation. + Pong(Vec<u8>), + /// Peer close information, when available. + Close(Option<CloseFrame>), +} + +impl fmt::Debug for Frame { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Text(_) => "Frame::Text([redacted])", + Self::Binary(_) => "Frame::Binary([redacted])", + Self::Ping(_) => "Frame::Ping([redacted])", + Self::Pong(_) => "Frame::Pong([redacted])", + Self::Close(_) => "Frame::Close([redacted])", + }) + } +} + +/// One connection's original destination and revocable ingress authority. +/// Implementations must not create fresh grants or reset a shared budget. +pub trait Admission: Send + Sync { + /// Checks each DNS result before any address is connected. + fn permits_address(&self, address: IpAddr) -> bool; + /// Checks read authority and registers the current reader for revocation. + fn admitted_read(&self, context: &Context<'_>) -> bool; + /// Checks write authority and registers the writer for revocation. + fn admitted_write(&self, context: &Context<'_>) -> bool; + /// Charges actual bytes, frame starts and data-message starts before decode. + /// A refusal is sticky within this connection's original shared budget. + fn charge(&self, bytes: usize, frames: usize, data_messages: usize) -> bool; +} + +/// A concrete host connection. The shared protocol adapter owns serialization, +/// session membership, reconnect policy and acknowledgement correlation. +pub trait Socket: Send + Sync { + /// Sends the original frame under the connection's frozen limits. + fn send(&self, frame: Frame) -> IoFuture<'_, Result<(), Error>>; + /// Receives one frame, or confirms the end of this connection's stream. + fn receive(&self) -> IoFuture<'_, Result<Option<Frame>, Error>>; + /// Closes this original connection; it never switches to a replacement. + fn close(&self) -> IoFuture<'_, Result<(), Error>>; +} + +/// Supplies concrete I/O to one existing protocol-session owner. Construction +/// and unpolled connection futures must be inert. A failed or cancelled attempt +/// must dispose its own socket and callbacks without authorizing a retry. +pub trait Connector: fmt::Debug + Send + Sync { + /// Whether the host exposes native ping/pong control frames. + fn supports_ping(&self) -> bool; + /// Revalidates the endpoint and every resolved address before I/O. Native + /// hosts meter plaintext before framing; browser hosts must describe their + /// actual platform admission boundary rather than claiming native controls. + fn connect<'a>( + &'a self, + endpoint: &'a str, + timeout: Duration, + max_message_bytes: core::num::NonZeroUsize, + admission: Arc<dyn Admission>, + ) -> IoFuture<'a, Result<Arc<dyn Socket>, Error>>; +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::format; + + #[test] + fn frame_diagnostics_never_retain_or_print_wire_credentials_or_peer_text() { + let secret = "private_wire_value_that_must_not_appear"; + let close = CloseFrame { + code: 1000, + reason: secret.into(), + }; + assert!(!format!("{close:?}").contains(secret)); + for frame in [ + Frame::Text(secret.into()), + Frame::Binary(secret.as_bytes().into()), + Frame::Ping(secret.as_bytes().into()), + Frame::Pong(secret.as_bytes().into()), + Frame::Close(Some(close)), + Frame::Close(None), + ] { + let debug = format!("{frame:?}"); + assert!(!debug.contains(secret)); + assert!(debug.contains("[redacted]")); + assert!(debug.len() < 64); + } + } + + #[test] + fn io_failures_have_bounded_diagnostics_and_no_provider_error_chain() { + use std::error::Error as _; + for error in [ + Error::Policy, + Error::Unavailable, + Error::Timeout, + Error::Closed, + Error::Protocol, + Error::Unsupported, + ] { + assert!(error.source().is_none()); + let text = format!("{error}"); + assert!(!text.is_empty() && text.len() < 64); + } + } +} diff --git a/crates/transport_nostr_native/Cargo.toml b/crates/transport_nostr_native/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "radroots_transport_nostr_native" +publish = false +version = "0.1.0-alpha" +edition.workspace = true +rust-version.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +description = "Native socket ownership for the shared Radroots Nostr session" +readme = "README.md" + +[dependencies] +radroots_transport = { workspace = true, features = ["std"] } +radroots_transport_nostr = { workspace = true } +futures = { workspace = true } +rustls = { workspace = true } +tokio = { workspace = true, features = ["net", "time"] } +tokio-rustls = { workspace = true } +tokio-tungstenite = { workspace = true } +url = { workspace = true } +webpki-roots = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] } + +[lints] +workspace = true diff --git a/crates/transport_nostr_native/LICENSE-APACHE b/crates/transport_nostr_native/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2025 Tyson Lupul + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/crates/transport_nostr_native/LICENSE-MIT b/crates/transport_nostr_native/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2025 Tyson Lupul + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/crates/transport_nostr_native/README.md b/crates/transport_nostr_native/README.md @@ -0,0 +1,9 @@ +# radroots_transport_nostr_native + +Native DNS, TCP, original-host TLS, WebSocket framing and plaintext ingress +metering for the shared Radroots Nostr session. The host exchanges owned frames +through `radroots_transport::host::websocket`; it owns no protocol relay pool, +signer, storage, outbox, retries or application executor. + +This package begins private while its concrete I/O boundary is verified. The +shared session's ordinary client has not switched to this provider yet. diff --git a/crates/transport_nostr_native/src/connector.rs b/crates/transport_nostr_native/src/connector.rs @@ -0,0 +1,117 @@ +use crate::{socket::NativeSocket, wire::MeteredIo}; +use core::{future::Future, pin::pin, task::Poll}; +use futures::StreamExt; +use radroots_transport::host::websocket::{Admission, Connector, Error, IoFuture, Socket}; +use std::{net::SocketAddr, num::NonZeroUsize, sync::Arc, time::Duration}; +use tokio::net::TcpStream; +use tokio_tungstenite::MaybeTlsStream; +use url::Url; + +const MAX_RESOLVED_ADDRESSES: usize = 32; + +/// Inert native I/O provider. The shared session supplies its original +/// destination authority, ingress generation, limits and connection deadline. +#[derive(Clone, Copy, Debug, Default)] +pub struct NativeConnector; + +impl Connector for NativeConnector { + fn supports_ping(&self) -> bool { + true + } + + fn connect<'a>( + &'a self, + endpoint: &'a str, + timeout: Duration, + max_message_bytes: NonZeroUsize, + admission: Arc<dyn Admission>, + ) -> IoFuture<'a, Result<Arc<dyn Socket>, Error>> { + Box::pin(async move { + let parsed = Url::parse(endpoint).map_err(|_| Error::Policy)?; + if !matches!(parsed.scheme(), "ws" | "wss") + || !parsed.username().is_empty() + || parsed.password().is_some() + || parsed.fragment().is_some() + { + return Err(Error::Policy); + } + let host = parsed + .host_str() + .ok_or(Error::Policy)? + .trim_matches(['[', ']']); + let port = parsed.port_or_known_default().ok_or(Error::Policy)?; + let metering = Arc::clone(&admission); + let connect = async { + let addresses = resolve_bounded(host, port).await?; + if addresses + .iter() + .any(|address| !admission.permits_address(address.ip())) + { + return Err(Error::Policy); + } + let tcp = connect_pinned(&addresses).await?; + let plaintext = if parsed.scheme() == "wss" { + let mut roots = rustls::RootCertStore::empty(); + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + let config = rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(); + let server_name = rustls::pki_types::ServerName::try_from(host.to_owned()) + .map_err(|_| Error::Policy)?; + let tls = tokio_rustls::TlsConnector::from(Arc::new(config)) + .connect(server_name, tcp) + .await + .map_err(|_| Error::Unavailable)?; + MaybeTlsStream::Rustls(tls) + } else { + MaybeTlsStream::Plain(tcp) + }; + let metered = MeteredIo::new(plaintext, metering, max_message_bytes.get()); + let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default() + .max_message_size(Some(max_message_bytes.get())) + .max_frame_size(Some(max_message_bytes.get())); + let (stream, _) = + tokio_tungstenite::client_async_with_config(endpoint, metered, Some(config)) + .await + .map_err(|_| Error::Unavailable)?; + let (sink, stream) = stream.split(); + Ok( + Arc::new(NativeSocket::new(sink, stream, max_message_bytes.get())) + as Arc<dyn Socket>, + ) + }; + let mut connect = pin!(connect); + let admitted = futures::future::poll_fn(|context| { + if !admission.admitted_read(context) || !admission.admitted_write(context) { + return Poll::Ready(Err(Error::Policy)); + } + connect.as_mut().poll(context) + }); + tokio::time::timeout(timeout, admitted) + .await + .map_err(|_| Error::Timeout)? + }) + } +} + +async fn resolve_bounded(host: &str, port: u16) -> Result<Vec<SocketAddr>, Error> { + let addresses = tokio::net::lookup_host((host, port)) + .await + .map_err(|_| Error::Unavailable)?; + let bounded = addresses + .take(MAX_RESOLVED_ADDRESSES + 1) + .collect::<Vec<_>>(); + if bounded.is_empty() || bounded.len() > MAX_RESOLVED_ADDRESSES { + return Err(Error::Policy); + } + Ok(bounded) +} + +async fn connect_pinned(addresses: &[SocketAddr]) -> Result<TcpStream, Error> { + for address in addresses { + if let Ok(stream) = TcpStream::connect(address).await { + return Ok(stream); + } + } + Err(Error::Unavailable) +} diff --git a/crates/transport_nostr_native/src/lib.rs b/crates/transport_nostr_native/src/lib.rs @@ -0,0 +1,9 @@ +#![doc = include_str!("../README.md")] +#![forbid(unsafe_code)] +#![cfg_attr(coverage_nightly, feature(coverage_attribute))] + +mod connector; +mod socket; +mod wire; + +pub use connector::NativeConnector; diff --git a/crates/transport_nostr_native/src/socket.rs b/crates/transport_nostr_native/src/socket.rs @@ -0,0 +1,163 @@ +use crate::wire::MeteredIo; +use futures::{ + SinkExt, StreamExt, + lock::Mutex, + stream::{SplitSink, SplitStream}, +}; +use radroots_transport::host::websocket::{CloseFrame, Error, Frame, IoFuture, Socket}; +use tokio::net::TcpStream; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, tungstenite::Message}; + +type NativeStream = WebSocketStream<MeteredIo<MaybeTlsStream<TcpStream>>>; + +pub(crate) struct NativeSocket { + sink: Mutex<SplitSink<NativeStream, Message>>, + stream: Mutex<SplitStream<NativeStream>>, + max_message_bytes: usize, +} + +impl NativeSocket { + pub(crate) fn new( + sink: SplitSink<NativeStream, Message>, + stream: SplitStream<NativeStream>, + max_message_bytes: usize, + ) -> Self { + Self { + sink: Mutex::new(sink), + stream: Mutex::new(stream), + max_message_bytes, + } + } +} + +impl Socket for NativeSocket { + fn send(&self, frame: Frame) -> IoFuture<'_, Result<(), Error>> { + Box::pin(async move { + let message = to_wire(frame, self.max_message_bytes)?; + self.sink + .lock() + .await + .send(message) + .await + .map_err(|_| Error::Unavailable) + }) + } + + fn receive(&self) -> IoFuture<'_, Result<Option<Frame>, Error>> { + Box::pin(async move { + self.stream + .lock() + .await + .next() + .await + .transpose() + .map_err(|_| Error::Unavailable)? + .map(from_wire) + .transpose() + }) + } + + fn close(&self) -> IoFuture<'_, Result<(), Error>> { + Box::pin(async move { + self.sink + .lock() + .await + .close() + .await + .map_err(|_| Error::Unavailable) + }) + } +} + +fn to_wire(frame: Frame, limit: usize) -> Result<Message, Error> { + Ok(match frame { + Frame::Text(value) if value.len() <= limit => Message::Text(value.into()), + Frame::Binary(value) if value.len() <= limit => Message::Binary(value.into()), + Frame::Ping(value) if value.len() <= 125 => Message::Ping(value.into()), + Frame::Pong(value) if value.len() <= 125 => Message::Pong(value.into()), + Frame::Close(None) => Message::Close(None), + Frame::Close(Some(value)) if value.reason.len() <= 123 => { + Message::Close(Some(tokio_tungstenite::tungstenite::protocol::CloseFrame { + code: value.code.into(), + reason: value.reason.into(), + })) + } + _ => return Err(Error::Protocol), + }) +} + +fn from_wire(message: Message) -> Result<Frame, Error> { + Ok(match message { + Message::Text(value) => Frame::Text(value.to_string()), + Message::Binary(value) => Frame::Binary(value.to_vec()), + Message::Ping(value) => Frame::Ping(value.to_vec()), + Message::Pong(value) => Frame::Pong(value.to_vec()), + Message::Close(value) => Frame::Close(value.map(|value| CloseFrame { + code: value.code.into(), + reason: value.reason.to_string(), + })), + Message::Frame(_) => return Err(Error::Protocol), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn data_control_and_original_close_information_round_trip_without_reencoding() { + for frame in [ + Frame::Text(" \n{ \"z\":1, \"a\":2 } \t".into()), + Frame::Binary(vec![0, 255]), + Frame::Ping(vec![1]), + Frame::Pong(vec![2]), + Frame::Close(None), + Frame::Close(Some(CloseFrame { + code: 1000, + reason: "complete".into(), + })), + ] { + assert_eq!( + from_wire(to_wire(frame.clone(), 1024).unwrap()).unwrap(), + frame + ); + } + } + + #[test] + fn every_outgoing_data_and_control_bound_is_checked_before_socket_io() { + for frame in [Frame::Text("x".repeat(64)), Frame::Binary(vec![1; 64])] { + assert!(to_wire(frame, 64).is_ok()); + } + for frame in [ + Frame::Text("x".repeat(65)), + Frame::Binary(vec![1; 65]), + Frame::Ping(vec![1; 126]), + Frame::Pong(vec![1; 126]), + Frame::Close(Some(CloseFrame { + code: 1000, + reason: "x".repeat(124), + })), + ] { + assert_eq!(to_wire(frame, 64).err(), Some(Error::Protocol)); + } + for frame in [ + Frame::Ping(vec![1; 125]), + Frame::Pong(vec![1; 125]), + Frame::Close(Some(CloseFrame { + code: 1000, + reason: "x".repeat(123), + })), + ] { + assert!(to_wire(frame, 64).is_ok()); + } + let raw = tokio_tungstenite::tungstenite::protocol::frame::Frame::message( + vec![1], + tokio_tungstenite::tungstenite::protocol::frame::coding::OpCode::Data( + tokio_tungstenite::tungstenite::protocol::frame::coding::Data::Binary, + ), + true, + ); + assert_eq!(from_wire(Message::Frame(raw)).err(), Some(Error::Protocol)); + } +} diff --git a/crates/transport_nostr_native/src/wire.rs b/crates/transport_nostr_native/src/wire.rs @@ -0,0 +1,240 @@ +//! Fixed-memory admission of decrypted ingress before WebSocket decoding. + +use radroots_transport::host::websocket::Admission; +use std::io; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; + +const MAX_UPGRADE_BYTES: usize = 16 * 1024; +const READ_CHUNK_BYTES: usize = 4096; + +/// Counts HTTP response and frame overhead conservatively in the same raw-byte +/// allowance as payloads. No message or payload is retained by this layer. +pub(crate) struct MeteredIo<S> { + inner: S, + ingress: Arc<dyn Admission>, + parser: WireParser, + failed: bool, +} + +impl<S> MeteredIo<S> { + pub(crate) fn new(inner: S, ingress: Arc<dyn Admission>, max_message_bytes: usize) -> Self { + Self { + inner, + ingress, + parser: WireParser::new(max_message_bytes), + failed: false, + } + } + + fn admitted(&self, context: &Context<'_>) -> io::Result<()> { + if self.failed || !self.ingress.admitted_read(context) { + Err(denied()) + } else { + Ok(()) + } + } +} + +impl<S: AsyncRead + Unpin> AsyncRead for MeteredIo<S> { + fn poll_read( + self: Pin<&mut Self>, + context: &mut Context<'_>, + output: &mut ReadBuf<'_>, + ) -> Poll<io::Result<()>> { + let this = self.get_mut(); + if let Err(error) = this.admitted(context) { + return Poll::Ready(Err(error)); + } + if output.remaining() == 0 { + return Poll::Ready(Ok(())); + } + let mut scratch = [0; READ_CHUNK_BYTES]; + let length = output.remaining().min(scratch.len()); + let mut input = ReadBuf::new(&mut scratch[..length]); + match Pin::new(&mut this.inner).poll_read(context, &mut input) { + Poll::Pending => Poll::Pending, + Poll::Ready(Err(error)) => { + this.failed = true; + Poll::Ready(Err(error)) + } + Poll::Ready(Ok(())) => { + let bytes = input.filled(); + let result = if !this.ingress.charge(bytes.len(), 0, 0) { + Err(denied()) + } else if bytes.is_empty() { + this.parser.eof() + } else { + this.parser + .consume(bytes, |data| this.ingress.charge(0, 1, usize::from(data))) + }; + if let Err(error) = result { + this.failed = true; + return Poll::Ready(Err(error)); + } + // Cancellation may race a ready read. Revalidate before any + // plaintext becomes visible to the WebSocket implementation. + if let Err(error) = this.admitted(context) { + this.failed = true; + return Poll::Ready(Err(error)); + } + output.put_slice(bytes); + Poll::Ready(Ok(())) + } + } + } +} + +impl<S: AsyncWrite + Unpin> AsyncWrite for MeteredIo<S> { + fn poll_write( + self: Pin<&mut Self>, + context: &mut Context<'_>, + bytes: &[u8], + ) -> Poll<io::Result<usize>> { + let this = self.get_mut(); + if this.failed || !this.ingress.admitted_write(context) { + return Poll::Ready(Err(denied())); + } + Pin::new(&mut this.inner).poll_write(context, bytes) + } + + fn poll_flush(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> { + let this = self.get_mut(); + if this.failed || !this.ingress.admitted_write(context) { + return Poll::Ready(Err(denied())); + } + Pin::new(&mut this.inner).poll_flush(context) + } + + fn poll_shutdown(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> { + // Closing the underlying transport remains possible after revocation. + Pin::new(&mut self.get_mut().inner).poll_shutdown(context) + } +} + +#[derive(Default)] +struct WireParser { + max_message_bytes: usize, + upgrade_bytes: usize, + delimiter: u32, + upgraded: bool, + header: [u8; 10], + header_len: usize, + header_needed: usize, + payload_remaining: usize, +} + +impl WireParser { + fn new(max_message_bytes: usize) -> Self { + Self { + max_message_bytes, + ..Self::default() + } + } + + fn consume( + &mut self, + mut bytes: &[u8], + mut admit_frame: impl FnMut(bool) -> bool, + ) -> io::Result<()> { + while let Some((&byte, rest)) = bytes.split_first() { + if !self.upgraded { + self.upgrade_bytes += 1; + if self.upgrade_bytes > MAX_UPGRADE_BYTES { + return Err(invalid("WebSocket upgrade response exceeds its limit")); + } + self.delimiter = (self.delimiter << 8) | u32::from(byte); + self.upgraded = self.delimiter == u32::from_be_bytes(*b"\r\n\r\n"); + bytes = rest; + } else if self.payload_remaining != 0 { + let consumed = self.payload_remaining.min(bytes.len()); + self.payload_remaining -= consumed; + bytes = &bytes[consumed..]; + } else { + if self.header_len == 0 { + let opcode = byte & 0x0f; + if !admit_frame(matches!(opcode, 1 | 2)) { + return Err(denied()); + } + if byte & 0x70 != 0 || !matches!(opcode, 0 | 1 | 2 | 8 | 9 | 10) { + return Err(invalid("unsupported WebSocket frame flags or opcode")); + } + if opcode >= 8 && byte & 0x80 == 0 { + return Err(invalid("fragmented WebSocket control frame")); + } + self.header_needed = 2; + } + self.header[self.header_len] = byte; + self.header_len += 1; + bytes = rest; + if self.header_len == 2 { + if byte & 0x80 != 0 { + return Err(invalid("masked server WebSocket frame")); + } + self.header_needed = match byte { + 126 => 4, + 127 => 10, + _ => 2, + }; + } + if self.header_len == self.header_needed { + self.payload_remaining = self.payload_length()?; + self.header_len = 0; + } + } + } + Ok(()) + } + + fn payload_length(&self) -> io::Result<usize> { + let (length, minimum) = match self.header[1] { + 126 => ( + u64::from(u16::from_be_bytes([self.header[2], self.header[3]])), + 126, + ), + 127 => { + let mut extended = [0; 8]; + extended.copy_from_slice(&self.header[2..10]); + (u64::from_be_bytes(extended), 65536) + } + length => (u64::from(length), 0), + }; + if length < minimum || length > self.max_message_bytes as u64 { + return Err(invalid( + "WebSocket frame length is noncanonical or exceeds its limit", + )); + } + if self.header[0] & 0x0f >= 8 && length > 125 { + return Err(invalid("WebSocket control frame exceeds its limit")); + } + usize::try_from(length).map_err(|_| invalid("WebSocket frame length cannot be represented")) + } + + fn eof(&self) -> io::Result<()> { + if !self.upgraded || self.header_len != 0 || self.payload_remaining != 0 { + Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "truncated WebSocket ingress", + )) + } else { + Ok(()) + } + } +} + +fn invalid(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +fn denied() -> io::Error { + io::Error::new( + io::ErrorKind::ConnectionAborted, + "relay ingress budget or generation revoked", + ) +} + +#[cfg(test)] +#[path = "wire_tests.rs"] +mod tests; diff --git a/crates/transport_nostr_native/src/wire_tests.rs b/crates/transport_nostr_native/src/wire_tests.rs @@ -0,0 +1,336 @@ +use super::*; +use std::sync::atomic::{AtomicBool, Ordering}; + +const UPGRADE: &[u8] = b"HTTP/1.1 101 Switching Protocols\r\n\r\n"; +const MAX_MESSAGE_BYTES: usize = 512 * 1024; + +fn upgraded() -> WireParser { + let mut parser = WireParser::new(MAX_MESSAGE_BYTES); + parser + .consume(UPGRADE, |_| panic!("HTTP is not a frame")) + .expect("upgrade"); + parser +} + +fn header(length: u64) -> Vec<u8> { + let mut bytes = vec![0x82, 127]; + bytes.extend(length.to_be_bytes()); + bytes +} + +#[test] +fn maximum_frame_length_is_admitted_and_next_byte_or_overflow_is_denied() { + let maximum = MAX_MESSAGE_BYTES as u64; + let mut parser = upgraded(); + parser + .consume(&header(maximum), |_| true) + .expect("exact limit"); + assert_eq!(parser.payload_remaining, maximum as usize); + for length in [maximum + 1, 1 << 63, u64::MAX] { + assert!(upgraded().consume(&header(length), |_| true).is_err()); + } +} + +#[test] +fn headers_payloads_and_upgrade_can_arrive_one_byte_at_a_time() { + let mut parser = WireParser::new(MAX_MESSAGE_BYTES); + let mut bytes = UPGRADE.to_vec(); + bytes.extend([0x01, 126, 0, 126]); + bytes.extend([b'x'; 126]); + bytes.extend([0x89, 0, 0x80, 2, b'y', b'z', 0x82, 0]); + let mut frames = 0; + let mut data = 0; + for byte in bytes { + parser + .consume(&[byte], |is_data| { + frames += 1; + data += usize::from(is_data); + true + }) + .expect("chopped ingress"); + } + assert_eq!((frames, data), (4, 2)); + parser.eof().expect("complete frames"); +} + +#[test] +fn zero_length_continuations_and_controls_each_require_admission() { + let mut parser = upgraded(); + let mut admissions = 0; + let error = parser + .consume(&[0x01, 0, 0x00, 0, 0x89, 0, 0x80, 0], |is_data| { + admissions += 1; + assert_eq!(is_data, admissions == 1); + admissions <= 3 + }) + .expect_err("fourth frame is denied"); + assert_eq!(error.kind(), io::ErrorKind::ConnectionAborted); + assert_eq!(admissions, 4); +} + +#[test] +fn invalid_flags_masks_lengths_and_controls_fail_closed() { + for bytes in [ + vec![0xc1, 0], + vec![0x83, 0], + vec![0x09, 0], + vec![0x81, 0x80], + vec![0x82, 126, 0, 125], + header(65535), + vec![0x89, 126, 0, 126], + ] { + assert!( + upgraded().consume(&bytes, |_| true).is_err(), + "accepted {bytes:?}" + ); + } +} + +#[test] +fn upgrade_prefix_has_an_exact_fixed_bound() { + let mut exact = vec![b'x'; MAX_UPGRADE_BYTES - 4]; + exact.extend(b"\r\n\r\n"); + let mut parser = WireParser::new(MAX_MESSAGE_BYTES); + parser.consume(&exact, |_| true).expect("exact maximum"); + parser.eof().expect("upgrade boundary"); + let mut excessive = vec![b'x']; + excessive.extend(exact); + assert!( + WireParser::new(MAX_MESSAGE_BYTES) + .consume(&excessive, |_| true) + .is_err() + ); +} + +#[test] +fn eof_rejects_partial_upgrade_header_and_payload() { + assert!(WireParser::new(MAX_MESSAGE_BYTES).eof().is_err()); + for bytes in [vec![0x81], vec![0x82, 126, 0], vec![0x81, 2, b'x']] { + let mut parser = upgraded(); + parser.consume(&bytes, |_| true).expect("partial input"); + assert_eq!( + parser.eof().expect_err("truncation").kind(), + io::ErrorKind::UnexpectedEof + ); + } + upgraded().eof().expect("frame boundary"); +} + +struct Authority { + open: AtomicBool, + charge: AtomicBool, +} + +impl Admission for Authority { + fn permits_address(&self, _: std::net::IpAddr) -> bool { + true + } + fn admitted_read(&self, _: &Context<'_>) -> bool { + self.open.load(Ordering::SeqCst) + } + fn admitted_write(&self, _: &Context<'_>) -> bool { + self.open.load(Ordering::SeqCst) + } + fn charge(&self, _: usize, _: usize, _: usize) -> bool { + self.charge.load(Ordering::SeqCst) + } +} + +struct ControlledIo { + bytes: Vec<u8>, + offset: usize, + reads: usize, + writes: usize, + shutdowns: usize, + read_error: bool, + revoke_after_read: bool, + authority: Arc<Authority>, +} + +impl AsyncRead for ControlledIo { + fn poll_read( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + output: &mut ReadBuf<'_>, + ) -> Poll<io::Result<()>> { + self.reads += 1; + if self.read_error { + return Poll::Ready(Err(io::Error::other("controlled read failure"))); + } + let length = (self.bytes.len() - self.offset).min(output.remaining()); + output.put_slice(&self.bytes[self.offset..self.offset + length]); + self.offset += length; + if self.revoke_after_read { + self.authority.open.store(false, Ordering::SeqCst); + } + Poll::Ready(Ok(())) + } +} + +impl AsyncWrite for ControlledIo { + fn poll_write( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bytes: &[u8], + ) -> Poll<io::Result<usize>> { + self.writes += 1; + Poll::Ready(Ok(bytes.len())) + } + fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { + self.writes += 1; + Poll::Ready(Ok(())) + } + fn poll_shutdown(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { + self.shutdowns += 1; + Poll::Ready(Ok(())) + } +} + +fn metered(bytes: Vec<u8>) -> (MeteredIo<ControlledIo>, Arc<Authority>) { + let authority = Arc::new(Authority { + open: AtomicBool::new(true), + charge: AtomicBool::new(true), + }); + let inner = ControlledIo { + bytes, + offset: 0, + reads: 0, + writes: 0, + shutdowns: 0, + read_error: false, + revoke_after_read: false, + authority: authority.clone(), + }; + ( + MeteredIo::new(inner, authority.clone(), MAX_MESSAGE_BYTES), + authority, + ) +} + +fn read_meter( + meter: &mut MeteredIo<ControlledIo>, + capacity: usize, +) -> (Poll<io::Result<()>>, usize) { + let waker = futures::task::noop_waker(); + let mut context = Context::from_waker(&waker); + let mut bytes = vec![0; capacity]; + let mut output = ReadBuf::new(&mut bytes); + let result = Pin::new(meter).poll_read(&mut context, &mut output); + (result, output.filled().len()) +} + +#[test] +fn empty_output_never_reads_and_large_outputs_still_use_fixed_scratch_chunks() { + let mut bytes = UPGRADE.to_vec(); + bytes.extend([0x82, 126, 0x13, 0x88]); + bytes.extend([1; 5000]); + let length = bytes.len(); + let (mut meter, _) = metered(bytes); + assert!(matches!( + read_meter(&mut meter, 0), + (Poll::Ready(Ok(())), 0) + )); + assert_eq!(meter.inner.reads, 0); + assert!(matches!( + read_meter(&mut meter, 8192), + (Poll::Ready(Ok(())), READ_CHUNK_BYTES) + )); + assert!( + matches!(read_meter(&mut meter,8192),(Poll::Ready(Ok(())),n) if n==length-READ_CHUNK_BYTES) + ); + assert!(matches!( + read_meter(&mut meter, 8192), + (Poll::Ready(Ok(())), 0) + )); +} + +#[test] +fn read_errors_and_raw_admission_refusal_are_sticky_before_any_later_io() { + for underlying_error in [false, true] { + let (mut meter, authority) = metered(UPGRADE.to_vec()); + meter.inner.read_error = underlying_error; + authority.charge.store(underlying_error, Ordering::SeqCst); + assert!(matches!( + read_meter(&mut meter, 4096), + (Poll::Ready(Err(_)), 0) + )); + assert!(matches!( + read_meter(&mut meter, 4096), + (Poll::Ready(Err(_)), 0) + )); + assert_eq!(meter.inner.reads, 1); + let waker = futures::task::noop_waker(); + let mut context = Context::from_waker(&waker); + assert!(matches!( + Pin::new(&mut meter).poll_write(&mut context, b"denied"), + Poll::Ready(Err(_)) + )); + assert!(matches!( + Pin::new(&mut meter).poll_flush(&mut context), + Poll::Ready(Err(_)) + )); + assert_eq!(meter.inner.writes, 0); + assert!(matches!( + Pin::new(&mut meter).poll_shutdown(&mut context), + Poll::Ready(Ok(())) + )); + assert_eq!(meter.inner.shutdowns, 1); + } +} + +#[test] +fn revocation_during_a_ready_read_never_exposes_the_obtained_plaintext() { + let (mut meter, _) = metered(UPGRADE.to_vec()); + meter.inner.revoke_after_read = true; + assert!(matches!( + read_meter(&mut meter, 4096), + (Poll::Ready(Err(_)), 0) + )); + assert!(matches!( + read_meter(&mut meter, 4096), + (Poll::Ready(Err(_)), 0) + )); + assert_eq!(meter.inner.reads, 1); +} + +#[test] +fn revoked_write_and_flush_refuse_without_requiring_a_prior_failed_read() { + let (mut meter, authority) = metered(UPGRADE.to_vec()); + authority.open.store(false, Ordering::SeqCst); + let waker = futures::task::noop_waker(); + let mut context = Context::from_waker(&waker); + assert!(matches!( + Pin::new(&mut meter).poll_write(&mut context, b"denied"), + Poll::Ready(Err(_)) + )); + assert!(matches!( + Pin::new(&mut meter).poll_flush(&mut context), + Poll::Ready(Err(_)) + )); + assert_eq!(meter.inner.writes, 0); + assert!(matches!( + read_meter(&mut meter, 4096), + (Poll::Ready(Err(_)), 0) + )); + assert_eq!(meter.inner.reads, 0); + assert!(matches!( + Pin::new(&mut meter).poll_shutdown(&mut context), + Poll::Ready(Ok(())) + )); +} + +#[test] +fn truncated_payload_eof_is_terminal_at_the_meter_boundary() { + let mut bytes = UPGRADE.to_vec(); + bytes.extend([0x81, 3, b'x']); + let (mut meter, _) = metered(bytes); + assert!(matches!(read_meter(&mut meter,4096),(Poll::Ready(Ok(())),n) if n>0)); + assert!( + matches!(read_meter(&mut meter,4096),(Poll::Ready(Err(error)),0) if error.kind()==io::ErrorKind::UnexpectedEof) + ); + assert!(matches!( + read_meter(&mut meter, 4096), + (Poll::Ready(Err(_)), 0) + )); + assert_eq!(meter.inner.reads, 2); +} diff --git a/crates/transport_nostr_native/tests/io.rs b/crates/transport_nostr_native/tests/io.rs @@ -0,0 +1,348 @@ +use futures::{FutureExt, SinkExt, StreamExt, task::AtomicWaker}; +use radroots_transport::host::websocket::{Admission, Connector, Error, Frame, Socket}; +use radroots_transport_nostr_native::NativeConnector; +use std::{ + net::IpAddr, + num::NonZeroUsize, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + task::Context, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, + sync::oneshot, +}; +use tokio_tungstenite::{accept_async, tungstenite::Message}; + +const WATCHDOG: Duration = Duration::from_secs(5); + +struct Permit { + open: AtomicBool, + addresses: bool, + bytes: AtomicUsize, + limit: AtomicUsize, + frames: AtomicUsize, + reads: AtomicUsize, + reader_seen: tokio::sync::Notify, + reader: AtomicWaker, + writer: AtomicWaker, +} + +impl Permit { + fn new(addresses: bool) -> Arc<Self> { + Arc::new(Self { + open: AtomicBool::new(true), + addresses, + bytes: AtomicUsize::new(0), + limit: AtomicUsize::new(usize::MAX), + frames: AtomicUsize::new(0), + reads: AtomicUsize::new(0), + reader_seen: tokio::sync::Notify::new(), + reader: AtomicWaker::new(), + writer: AtomicWaker::new(), + }) + } + fn revoke(&self) { + self.open.store(false, Ordering::SeqCst); + self.reader.wake(); + self.writer.wake(); + } +} + +impl Admission for Permit { + fn permits_address(&self, address: IpAddr) -> bool { + self.addresses && address.is_loopback() + } + fn admitted_read(&self, context: &Context<'_>) -> bool { + self.reader.register(context.waker()); + self.reads.fetch_add(1, Ordering::SeqCst); + self.reader_seen.notify_waiters(); + self.open.load(Ordering::SeqCst) + } + fn admitted_write(&self, context: &Context<'_>) -> bool { + self.writer.register(context.waker()); + self.open.load(Ordering::SeqCst) + } + fn charge(&self, bytes: usize, frames: usize, _: usize) -> bool { + let prior = self.bytes.fetch_add(bytes, Ordering::SeqCst); + self.frames.fetch_add(frames, Ordering::SeqCst); + prior + .checked_add(bytes) + .is_some_and(|total| total <= self.limit.load(Ordering::SeqCst)) + } +} + +async fn connect(url: &str, permit: Arc<Permit>, limit: usize) -> Arc<dyn Socket> { + NativeConnector + .connect( + url, + Duration::from_secs(1), + NonZeroUsize::new(limit).unwrap(), + permit, + ) + .await + .unwrap() +} + +#[tokio::test] +async fn construction_unpolled_connection_and_denied_authority_open_no_socket() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let permit = Permit::new(true); + let future = NativeConnector.connect( + &url, + Duration::from_secs(1), + NonZeroUsize::new(1024).unwrap(), + permit.clone(), + ); + drop(future); + assert!(listener.accept().now_or_never().is_none()); + permit.revoke(); + assert_eq!( + NativeConnector + .connect( + &url, + Duration::from_secs(1), + NonZeroUsize::new(1024).unwrap(), + permit + ) + .await + .err(), + Some(Error::Policy) + ); + assert_eq!( + NativeConnector + .connect( + &url, + Duration::from_secs(1), + NonZeroUsize::new(1024).unwrap(), + Permit::new(false) + ) + .await + .err(), + Some(Error::Policy) + ); + assert!(listener.accept().now_or_never().is_none()); + for url in [ + "https://127.0.0.1", + "ws://user:secret@127.0.0.1", + "ws://127.0.0.1/#fragment", + "invalid", + ] { + assert_eq!( + NativeConnector + .connect( + url, + Duration::from_secs(1), + NonZeroUsize::new(1024).unwrap(), + Permit::new(true) + ) + .await + .err(), + Some(Error::Policy) + ); + } +} + +#[tokio::test] +async fn original_text_binary_and_control_frames_share_one_socket_then_close() { + tokio::time::timeout(WATCHDOG, async { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let original = " \n[\"EVENT\", { \"z\":1, \"a\":2 }] \t"; + let server = tokio::spawn(async move { + let (tcp, _) = listener.accept().await.unwrap(); + let mut socket = accept_async(tcp).await.unwrap(); + assert_eq!( + socket.next().await.unwrap().unwrap(), + Message::Text(original.into()) + ); + socket.send(Message::Text(original.into())).await.unwrap(); + let binary = vec![0, 255, 1]; + assert_eq!( + socket.next().await.unwrap().unwrap(), + Message::Binary(binary.clone().into()) + ); + socket.send(Message::Binary(binary.into())).await.unwrap(); + assert_eq!( + socket.next().await.unwrap().unwrap(), + Message::Ping(vec![7].into()) + ); + socket.flush().await.unwrap(); + assert_eq!( + socket.next().await.unwrap().unwrap(), + Message::Pong(vec![9].into()) + ); + assert!(matches!( + socket.next().await.unwrap().unwrap(), + Message::Close(_) + )); + socket.flush().await.unwrap(); + }); + let permit = Permit::new(true); + let socket = connect(&url, permit.clone(), 1024).await; + assert!(NativeConnector.supports_ping()); + socket.send(Frame::Text(original.to_owned())).await.unwrap(); + assert_eq!( + socket.receive().await.unwrap(), + Some(Frame::Text(original.to_owned())) + ); + socket.send(Frame::Binary(vec![0, 255, 1])).await.unwrap(); + assert_eq!( + socket.receive().await.unwrap(), + Some(Frame::Binary(vec![0, 255, 1])) + ); + socket.send(Frame::Ping(vec![7])).await.unwrap(); + assert_eq!(socket.receive().await.unwrap(), Some(Frame::Pong(vec![7]))); + socket.send(Frame::Pong(vec![9])).await.unwrap(); + assert!(permit.frames.load(Ordering::SeqCst) >= 3); + socket.close().await.unwrap(); + server.await.unwrap(); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn secure_endpoint_sends_tls_and_refuses_a_plaintext_upgrade() { + tokio::time::timeout(WATCHDOG, async { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("wss://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut prefix = [0; 5]; + socket.read_exact(&mut prefix).await.unwrap(); + socket + .write_all(b"HTTP/1.1 101 Switching Protocols\r\n\r\n") + .await + .unwrap(); + prefix + }); + assert_eq!( + NativeConnector + .connect( + &url, + Duration::from_secs(1), + NonZeroUsize::new(1024).unwrap(), + Permit::new(true) + ) + .await + .err(), + Some(Error::Unavailable) + ); + let prefix = server.await.unwrap(); + assert_eq!(&prefix[..2], &[0x16, 0x03]); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn handshake_deadline_disposes_the_original_tcp_connection() { + tokio::time::timeout(WATCHDOG, async { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut bytes = [0; 4096]; + loop { + if socket.read(&mut bytes).await.unwrap() == 0 { + break; + } + } + }); + assert_eq!( + NativeConnector + .connect( + &url, + Duration::from_millis(50), + NonZeroUsize::new(1024).unwrap(), + Permit::new(true) + ) + .await + .err(), + Some(Error::Timeout) + ); + server.await.unwrap(); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn revocation_wakes_a_pending_read_and_prevents_later_writes() { + tokio::time::timeout(WATCHDOG, async { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (tcp, _) = listener.accept().await.unwrap(); + let mut socket = accept_async(tcp).await.unwrap(); + while let Some(message) = socket.next().await { + if message.is_err() { + break; + } + } + }); + let permit = Permit::new(true); + let socket = connect(&url, permit.clone(), 1024).await; + let before = permit.reads.load(Ordering::SeqCst); + let reader = socket.clone(); + let receive = tokio::spawn(async move { reader.receive().await }); + loop { + let observed = permit.reader_seen.notified(); + tokio::pin!(observed); + observed.as_mut().enable(); + if permit.reads.load(Ordering::SeqCst) > before { + break; + } + observed.await; + } + permit.revoke(); + assert_eq!(receive.await.unwrap(), Err(Error::Unavailable)); + assert_eq!( + socket.send(Frame::Text("denied".to_owned())).await, + Err(Error::Unavailable) + ); + drop(socket); + server.await.unwrap(); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn oversized_frames_and_refused_raw_bytes_never_reach_the_message_reader() { + for raw_budget in [false, true] { + tokio::time::timeout(WATCHDOG, async { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let (ready, wait) = oneshot::channel(); + let server = tokio::spawn(async move { + let (tcp, _) = listener.accept().await.unwrap(); + let mut socket = accept_async(tcp).await.unwrap(); + wait.await.unwrap(); + socket + .send(Message::Binary(vec![1; 128].into())) + .await + .unwrap(); + }); + let permit = Permit::new(true); + let socket = connect(&url, permit.clone(), if raw_budget { 1024 } else { 64 }).await; + if raw_budget { + permit + .limit + .store(permit.bytes.load(Ordering::SeqCst), Ordering::SeqCst); + } + ready.send(()).unwrap(); + assert_eq!(socket.receive().await, Err(Error::Unavailable)); + drop(socket); + server.await.unwrap(); + }) + .await + .unwrap(); + } +}