The network-protocol library is a Rust-based secure networking protocol designed for high-performance, low-latency communication. It provides layered security, configurable transport options, and comprehensive error handling.
- Security First: All communications encrypted by default, defense in depth
- Zero-Copy Where Possible: Minimize allocations and copies in hot paths
- Async by Default: Built on Tokio for scalable concurrent connections
- Type Safety: Leverage Rust's type system to prevent bugs at compile time
- Fail-Fast: Validate early, reject invalid input before expensive operations
- Observable: Structured logging for debugging and monitoring
┌─────────────────────────────────────────────────────────┐
│ Application Layer │
│ (User Code / Business Logic) │
└─────────────────────────────────────────────────────────┘
▲
│
┌─────────────────────────────────────────────────────────┐
│ Protocol Layer │
│ ┌──────────┐ ┌───────────┐ ┌────────────────────┐ │
│ │ Handshake│ │ Dispatcher│ │ Message Routing │ │
│ └──────────┘ └───────────┘ └────────────────────┘ │
│ ┌──────────┐ ┌───────────┐ ┌────────────────────┐ │
│ │Heartbeat │ │ Keepalive │ │ Session Management │ │
│ └──────────┘ └───────────┘ └────────────────────┘ │
└─────────────────────────────────────────────────────────┘
▲
│
┌─────────────────────────────────────────────────────────┐
│ Core Layer │
│ ┌──────────────┐ ┌─────────────┐ ┌──────────────┐ │
│ │Packet Codec │ │ Framing │ │ Serialization│ │
│ └──────────────┘ └─────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────┘
▲
│
┌─────────────────────────────────────────────────────────┐
│ Transport Layer │
│ ┌───────────┐ ┌──────────┐ ┌───────────────────┐ │
│ │ TLS │ │ TCP │ │ Unix Sockets │ │
│ └───────────┘ └──────────┘ └───────────────────┘ │
└─────────────────────────────────────────────────────────┘
▲
│
┌─────────────────────────────────────────────────────────┐
│ Utilities Layer │
│ ┌──────────┐ ┌────────────┐ ┌─────────────────┐ │
│ │ Crypto │ │Compression │ │ Logging │ │
│ └──────────┘ └────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────┘
- Purpose: Secure communication over untrusted networks
- Features:
- TLS 1.2/1.3 support via rustls
- Mutual TLS (mTLS) for client authentication
- Certificate pinning for high-security deployments
- Self-signed certificate generation for testing
- Security: System root CAs, modern cipher suites only
- Use Case: Internet-facing services, untrusted networks
- Purpose: High-performance IPC on same machine
- Features:
- Unix domain sockets (UDS)
- Lower overhead than TCP
- OS-level security via filesystem permissions
- Use Case: Microservices, local daemons, same-machine communication
- Purpose: TCP without TLS (trusted networks only)
- Features:
- Direct TCP connections
- Lower latency than TLS
- Must be combined with application-level encryption
- Use Case: Internal data centers, VPNs, localhost
- Purpose: Manage multi-peer topologies
- Features:
- Peer discovery and management
- Gossip protocol support
- Fault tolerance
- Use Case: Distributed systems, service meshes
- Purpose: Binary wire format with framing
- Format:
[Magic: 0xDEADBEEF (4 bytes)] [Version: 1 (1 byte)] [Flags: compression/encryption (1 byte)] [Length: payload size (4 bytes BE)] [Payload: N bytes] - Limits:
- Min: 10 bytes (header only)
- Max: 16 MB (prevents DoS)
- Validation: Magic bytes, version check, length bounds
- Purpose: Tokio codec for async framing
- Features:
- Incremental parsing (no buffering entire packets)
- Zero-copy where possible
- Backpressure support
- Implementation:
tokio_util::codec::{Encoder, Decoder}
- Purpose: Establish secure session with key exchange
- Flow:
- Client → Server:
SecureHandshakeInit(pubkey, timestamp, nonce) - Server validates timestamp, generates shared secret
- Server → Client:
SecureHandshakeResponse(encrypted challenge) - Client → Server:
SecureHandshakeConfirm(encrypted nonce verification)
- Client → Server:
- Security:
- X25519 ECDH key exchange
- Per-session keys
- Timestamp validation (±5 seconds)
- Nonce tracking (10,000 per session)
- Purpose: Application-level message types
- Types:
Data: Arbitrary payloadEcho: Request-response testPing/Pong: KeepaliveSecureHandshake*: Session establishment
- Serialization: Bincode (efficient binary)
- Purpose: Route messages to registered handlers
- Features:
- Handler registration by message type
- Thread-safe via
Arc<RwLock<>> - Extensible for custom message types
- Use Case: Server-side message routing
- Purpose: Detect idle connections
- Mechanism:
- Track last send/receive time
- Configurable interval (default 30s)
- Triggers keepalive ping if idle
- Use Case: Prevent silent connection failures
- Purpose: Prevent connection timeouts
- Mechanism:
- Send
Pingif idle - Expect
Pongresponse - Configurable interval
- Send
- Use Case: Long-lived connections through NAT/firewalls
- Purpose: Client-side connection management
- Features:
- Automatic keepalive
- Request-response patterns
- Timeout handling
- Graceful shutdown
- Purpose: Server-side connection handling
- Features:
- Accept incoming connections
- Per-connection processing
- Backpressure (channel limits)
- Graceful shutdown with signal handling
- Purpose: TLS-wrapped versions of client/daemon
- Features: All base features + TLS encryption
- Purpose: Reuse connections with health checks and backpressure controls
- Features: LRU reuse, circuit breaker, connection warming, and TTL enforcement
- Purpose: Route concurrent requests over shared connections
- Features: ID-tagged frames, lockless response routing, timeout cleanup
- Algorithm: ChaCha20-Poly1305 AEAD
- Key Size: 256-bit
- Nonce Size: 192-bit (unique per message)
- Features:
- Authenticated encryption
- Key derivation
- Secure RNG (getrandom)
- Algorithms: LZ4 (fast), Zstd (high ratio)
- Threshold: 512 bytes (configurable)
- Limits: 16 MB output (DoS protection)
- Features:
- Conditional compression based on size
- Pre-decompression size validation
- OOM attack prevention
- Framework: Tracing
- Formats: JSON, pretty-print
- Outputs: Stdout, file rotation
- Levels: Trace, Debug, Info, Warn, Error
- Time: Timestamp utilities (seconds, milliseconds)
- Timeout: Async wrappers for operations
- Use Case: Connection timeouts, handshake deadlines
Application
│
├─ Serialize message (bincode)
│
├─ Optionally compress (if > threshold)
│
├─ Optionally encrypt (if session keys present)
│
├─ Create Packet (magic, version, flags, length, payload)
│
├─ Encode to bytes (PacketCodec)
│
└─ Write to transport (TLS/TCP/UDS)
Transport (TLS/TCP/UDS)
│
├─ Read bytes from socket
│
├─ Decode Packet (PacketCodec validates magic/length)
│
├─ Extract payload from Packet
│
├─ Optionally decrypt (check flags)
│
├─ Optionally decompress (check flags)
│
├─ Deserialize message (bincode)
│
└─ Deliver to application
- Network: All network traffic is assumed hostile
- Peer: Peers may be malicious (validate all input)
- Resources: Assume DoS attempts (enforce limits)
- Encryption: ChaCha20-Poly1305 or TLS 1.2+
- Authentication: mTLS or session handshake
- Replay Protection: Nonce tracking + timestamps
- DoS Protection: Size limits, timeouts, backpressure
- Memory Safety: Rust ownership, no unsafe in core
- System Libraries: Trust OS RNG, TLS stack
- Dependencies: Audit via cargo-deny/audit
- Crypto Primitives: RustCrypto (community vetted)
See THREAT_MODEL.md for comprehensive threat analysis.
- Timeouts: Connection, send, receive (prevent slowloris)
- Compression: Threshold, algorithm selection
- Backpressure: Channel capacity (prevent memory exhaustion)
- TLS: Certificate paths, cipher suites, client auth
- TOML files (
config.toml) - Environment variables (application-specific)
- Programmatic defaults
- Packet Encoding/Decoding: Minimize allocations
- Crypto Operations: Use hardware acceleration (AES-NI, etc.)
- Compression: Only for large payloads (threshold)
- Serialization: Bincode (zero-copy where possible)
- LTO: Link-time optimization in release builds
- Codegen Units: Single unit for better optimization
- Zero-Copy: Direct buffer access where safe
- Async: Non-blocking I/O for concurrency
- Criterion: Microbenchmarks for packet, compression, messages
- Integration Tests: End-to-end latency and throughput
- Stress Tests: Large payload series, concurrent operations
See PERFORMANCE.md for detailed metrics.
- Unit Tests: Individual functions and modules
- Integration Tests: Cross-module interactions
- Edge Cases: Invalid inputs, boundary conditions
- Stress Tests: High load, large payloads
- Fuzz Tests: Random input generation (cargo-fuzz)
- Property Tests: Invariants (encode/decode roundtrip)
- Core Protocol: 100% (critical path)
- Transport: >90% (platform-dependent)
- Utilities: >95% (heavily reused)
- Recoverable: Timeouts, temporary network failures
- Protocol Errors: Invalid packets, handshake failures
- Fatal: Crypto failures, out of memory
- Result: All fallible operations
- thiserror: Structured error types with context
- Logging: Error details for debugging
- Application-specific (library doesn't retry)
- Caller decides retry policy
- Edge Services: TLS with system root CAs
- Internal Services: mTLS or Unix sockets
- High-Throughput: TCP in VPC, compression disabled
- High-Security: mTLS + certificate pinning
- Log structured events (JSON)
- Metrics: connection count, latency, throughput
- Alerts: Handshake failures, crypto errors, timeouts
- Post-quantum cryptography (when standardized)
- HTTP/3 transport (QUIC)
- Multi-stream connections
- Connection pooling
- Protocol versioning and negotiation
- Compression algorithm negotiation
- Message priority/QoS
- Rate limiting primitives