Security Guarantees
🔒 Cryptographic Protections
- Modern Encryption: ChaCha20-Poly1305 AEAD or TLS 1.2+/1.3 (no legacy ciphers)
- Key Exchange: X25519 ECDH with per-session ephemeral keys
- Forward Secrecy: Session keys never persist, automatic key rotation
- Replay Protection: Nonce tracking (10,000 per session) + timestamp validation (±5s window)
- Authentication: Mutual TLS support, certificate pinning available
🛡️ DoS/Memory Protections
- Decompression Bombs: Pre-validation prevents LZ4/Zstd expansion attacks (16MB hard limit)
- Memory Exhaustion: Maximum packet size 16MB, backpressure prevents unbounded buffering
- Slowloris: Connection timeouts (configurable), automatic dead connection cleanup
- Resource Limits: Bounded channels, connection limits, compression thresholds
- Fuzzing: 3 fuzz targets continuously tested, OOM attacks caught pre-release
- Zeroize Audit: Explicit memory clearing for session keys and shared secrets
🔍 Implementation Safety
- Memory Safe: 100% safe Rust (zero
unsafein protocol core), fuzz-tested - No Panics: All
unwrap()/expect()confined to test code only - Validated Input: All network data validated before processing, fail-fast on invalid packets
- Audit Trail: Structured logging, comprehensive error context for forensics
- Supply Chain:
cargo-deny+cargo-auditin CI, vetted crypto dependencies (RustCrypto/Rustls)
📋 Standards Compliance
- TLS: Enforces TLS 1.2+ minimum (no SSLv3/TLS 1.0/1.1), strong cipher suites only
- Crypto: NIST-approved algorithms (ChaCha20-Poly1305, X25519, SHA-256)
- Best Practices: Certificate validation, no homebrew crypto, constant-time operations
Threat Model: See THREAT_MODEL.md for comprehensive security analysis and attack scenarios.
Features
Security
- Secure handshake + post-handshake encryption using Elliptic Curve Diffie-Hellman (
ECDH) key exchange - TLS transport with client/server implementations and mutual authentication (
mTLS) - Certificate pinning for enhanced security in TLS connections
- Self-signed certificate generation capability for development environments
- Protection against replay attacks using timestamps and nonce verification
Performance & Reliability
- Advanced backpressure mechanism to prevent server overload from slow clients
- Bounded channels with dynamic read pausing to maintain stable memory usage
- Configurable connection timeouts for all network operations with proper error handling
- Heartbeat mechanism with keep-alive ping/pong messages for connection health monitoring
- Automatic detection and cleanup of dead connections
- Client-side timeouts for connecting, sending and waiting for a response
- Connection pooling with health checks, LRU reuse, and circuit breaker
- Request multiplexing with ID-tagged routing and timeout cleanup
- Optimized Release Builds: LTO + single codegen unit for maximum performance
Testing & Quality
- 214+ Test Suite: Unit, integration, edge cases, stress tests, doc tests
- Fuzzing Infrastructure: 3 targets (packet, handshake, compression) with CI smoke tests
- Benchmarking: Criterion-based micro-benchmarks for packet encode/decode, compression, messages
- CI Pipeline: Format, clippy, cross-platform builds (Linux/macOS/Windows), security audits
Core Architecture
- Custom binary packet format with optional compression (
LZ4,Zstd) - Plugin-friendly dispatcher for message routing with zero-copy serialization
- Graceful shutdown support for all server implementations with configurable timeouts
- Modular transport:
TCP,Unix socket,TLS,cluster sync - Comprehensive configuration system with
TOMLfiles and environment variable overrides - Configuration validation with detailed error reporting
- Structured logging with flexible log level control via configuration
Compatibility
- Cross-platform support for local transport (Windows, Linux, macOS)
- Windows-compatible alternative for Unix Domain Sockets
- Ready for microservices, databases, daemons, and system protocols
Installation
Add the library to your Cargo.toml:
[]
= "1.3"
Quick Start
TCP Server with Backpressure and Structured Logging
use ServerConfig;
use Dispatcher;
use Message;
use daemon;
use Arc;
use Duration;
use info;
async
start_daemon_no_signals() does not install a Ctrl+C handler, so the example waits for Ctrl+C itself. If the built-in PING and ECHO handlers are all you need, daemon::start_with_config(config).await? runs the server in the current task until Ctrl+C.
daemon::new_with_config(), Daemon::run() and Daemon::shutdown_with_timeout() are deprecated in 1.3.0: the first never started a server, run() returns at once, and the timeout argument was ignored. Use start_daemon_no_signals() and Daemon::shutdown(), and set the wait with ServerConfig::shutdown_timeout.
TLS Server
use tls_daemon;
use TlsServerConfig;
async
To accept clients with or without a certificate, add .require_client_auth(false) after with_client_auth(..). A certificate that is presented must still be signed by the client CA. Calling require_client_auth(true) without with_client_auth(..) is a configuration error from 1.3.0, because there is no CA to check certificates against. Clients have 10 seconds to finish the TLS handshake.
Use tls_daemon::start_with_shutdown(addr, config, shutdown_rx) with a tokio::sync::mpsc::Receiver<()> to stop the server from your own code: it shuts down when () is sent.
Client with Timeout Handling
use ClientConfig;
use Message;
use Client;
use Duration;
use info;
async
Client does not reconnect on its own. ClientConfig::auto_reconnect, max_reconnect_attempts and reconnect_delay are deprecated in 1.3.0 because they never had any effect; to reconnect, call Client::connect_with_config() again.
TLS Client
use Message;
use TlsClient;
use TlsClientConfig;
use info;
async
Without with_root_ca(..) the client trusts the system root store. TlsClient also has send() and receive() for one-way messages, and TlsClient::connect_with_session(addr, config, Some(cache)) resumes TLS sessions across connections that share the same Arc<SessionCache>.
Certificate Pinning
A pin is the SHA-256 fingerprint of the server's DER certificate, as 32 raw bytes (not hex). This example reads the certificate with rustls::pki_types, so it needs rustls = "0.23" in your own Cargo.toml:
use TlsClient;
use ;
use ;
async
From 1.3.0 the pin is checked on top of normal validation: the server certificate must chain to a trusted CA, match the server name, and have the pinned fingerprint. With insecure() the pin replaces CA validation instead, which is meant for development servers with a self-signed certificate. A pin that is not 32 bytes long makes load_client_config() (and so connect) return a TlsError.
Message Types
Built-in messages include:
SecureHandshakeInit/SecureHandshakeResponse/SecureHandshakeConfirmPing/PongEcho(String)Custom { command, payload }DisconnectUnknown
Use Message::Custom with your own command names for application messages, and register a handler for each name.
Benchmarks
Run microbenchmarks (Criterion):
Performance Highlights (v1.2.1 baseline):
- Packet encode: 1.64 GiB/s @ 1MB
- Packet decode: 4.90 GiB/s @ 1MB
- LZ4 compress: 8.33 GiB/s @ 1MB
- LZ4 decompress: 4.67 GiB/s @ 1MB
- Zstd compress: 3.05 GiB/s @ 1MB
- Zstd decompress: 4.44 GiB/s @ 1MB
- Adaptive compression: 10-15% CPU savings on mixed workloads
- Buffer pooling: 3-5% latency reduction under high load
- Pooling + multiplexing: lower connection churn and improved throughput under concurrency
Benchmarks collected on Windows (MSVC) with cargo bench.
See detailed results and recommendations in docs/PERFORMANCE.md.
Testing
Full test suite:
Fuzz smoke tests (nightly):
Stress tests:
Production build profile (already configured): LTO, codegen-units=1, opt-level=3, stripped symbols. Run with cargo build --release.
Custom Message Handlers
Register your own handlers with the dispatcher to process different message types:
use Dispatcher;
use Message;
use Result;
use Arc;
use info;
The dispatcher routes each message by its opcode: PING, PONG, ECHO and DISCONNECT for the built-in variants, and the command string for Message::Custom. A message with no registered handler fails with ProtocolError::UnexpectedMessage. Pass the dispatcher to daemon::start_daemon_no_signals(); the TLS daemon uses its own fixed PING and ECHO handlers.
Running Tests
Runs full unit + integration tests.
Benchmarking
# Run all benchmarks with output
# Run specific benchmark
Performance Metrics
| Metric | Result | Environment |
|---|---|---|
| Roundtrip Latency | <1ms avg | Local transport |
| Throughput | ~5,000 msg/sec | Standard payload |
| TLS Overhead | +2-5ms | With certificate validation |
The library includes comprehensive benchmarking tools that measure:
- Message roundtrip latency (client → server → client)
- Maximum throughput under various conditions
- Backpressure effectiveness during high load
- Connection recovery after network failures
For detailed benchmarking documentation, see the API Reference.
Documentation
- ARCHITECTURE.md - System design, data flow, component details
- THREAT_MODEL.md - Security analysis, attack scenarios, mitigations
- SECURITY.md - Vulnerability disclosure policy
- API Reference - Detailed API documentation
- Performance Guide - Optimization strategies and benchmarks
Project Structure
src/
├── config.rs # Configuration structures and loading
├── core/ # Codec, packet structure
├── protocol/ # Handshake, heartbeat, message types
├── transport/ # TCP, Unix socket, TLS, Cluster
├── service/ # Daemon + client APIs
├── utils/ # Compression, crypto, timers
benches/ # Criterion benchmarks
fuzz/ # Fuzzing targets (cargo-fuzz)
tests/ # Integration and stress tests
Contributing
Contributions welcome! Please:
- Run
cargo fmt && cargo clippy --workspace -- -D warningsbefore committing - Add tests for new features
- Update documentation as needed
- Follow existing code style and patterns
For security issues, see SECURITY.md.