Skip to content

feat(security): Implement transport-level rate limiting and spam protection - #79

Open
Samuel1505 wants to merge 2 commits into
StellarConduit:mainfrom
Samuel1505:transport-level
Open

feat(security): Implement transport-level rate limiting and spam protection#79
Samuel1505 wants to merge 2 commits into
StellarConduit:mainfrom
Samuel1505:transport-level

Conversation

@Samuel1505

Copy link
Copy Markdown
Contributor

Summary

Implements a token-bucket rate limiter to prevent malicious nodes from flooding neighbors with excessive messages, protecting against Resource Exhaustion / DOS attacks in the permissionless mesh network.

Problem

In a permissionless mesh network, anyone can join and start broadcasting. A malicious actor could spoof a node and constantly push thousands of 500-byte envelopes per second over WiFi-Direct, which would:

  • Drain the battery of all devices in the immediate vicinity
  • Clog the network layout
  • Cause resource exhaustion on receiving nodes

We need strict ingress rate limits per connected peer to mitigate these attacks.

Solution

Implemented a token-bucket rate limiter using the governor crate that:

  • Enforces per-peer rate limits with separate buckets for BLE and WiFi-Direct transports
  • Tracks violations and automatically triggers peer disconnection when thresholds are exceeded
  • Emits security events (PeerViolation) for external monitoring and ban handling
  • Automatically cleans up rate limiter state when peers disconnect

Rate Limits

  • BLE: Maximum 10 messages per second per peer
  • WiFi-Direct: Maximum 100 messages per second per peer
  • Violation Threshold: 10 consecutive violations trigger a ban (configurable)

Changes

New Files

  • src/security/mod.rs - Security module declaration
  • src/security/events.rs - Security event definitions (PeerViolation, ViolationReason)
  • src/security/rate_limit.rs - Token bucket rate limiter implementation
  • tests/integration/rate_limit_test.rs - Integration tests for rate limiting

Modified Files

  • src/lib.rs - Added security module
  • src/transport/unified.rs - Integrated rate limiter into TransportManager::recv_any()
  • Cargo.toml - Added governor and nonzero_ext dependencies

Implementation Details

  1. RateLimiter: Per-peer token bucket rate limiter with separate limiters for BLE and WiFi-Direct

    • Uses governor crate's RateLimiter with Quota::per_second()
    • Tracks violation counts per peer
    • Resets violation count on successful rate limit checks (good behavior)
  2. TransportManager Integration:

    • Rate limiting applied in recv_any() before processing messages
    • Messages exceeding rate limits are silently dropped
    • When violation threshold is reached:
      • PeerViolation event is emitted (if event sender is configured)
      • Peer connection is automatically disconnected
      • Rate limiter state is cleaned up
  3. Event System:

    • New SecurityEvent::PeerViolation event for external handling
    • TransportManager accepts optional broadcast::Sender<SecurityEvent> for event emission

Testing

Unit Tests (7 tests)

  • ✅ Token bucket correctly throttles rapid message bursts
  • ✅ Rate limiter blocks messages exceeding limits
  • ✅ Violation tracking and ban threshold enforcement
  • ✅ Separate rate limits per transport type (BLE vs WiFi-Direct)
  • ✅ Independent rate limits per peer
  • ✅ Violation count reset on good behavior
  • ✅ Peer state cleanup

Integration Tests (8 tests)

  • ✅ Rate limiter throttles rapid bursts with token refill
  • ✅ Violation tracking and ban triggering
  • ✅ Different limits per transport type
  • ✅ TransportManager integration
  • ✅ Security event emission on violations
  • ✅ Separate state per peer
  • ✅ Peer state removal
  • ✅ Violation reset on good behavior

All tests pass: 119 unit tests + 8 integration tests

Dependencies Added

  • governor = "0.6" - Token bucket rate limiting implementation
  • nonzero_ext = "0.3" - NonZeroU32 constant helpers

CI Status

cargo fmt --all - Code formatted
cargo clippy --all-targets --all-features -- -D warnings - No warnings
cargo test --workspace - All tests pass

Acceptance Criteria Met

  • ✅ Unit tests verify the token bucket correctly throttles rapid message bursts
  • ✅ Integration tests verify the connection terminates if the violation limit is reached
  • ✅ Adds the governor crate
  • ✅ All CI workflow commands pass

Usage Example

use stellarconduit_core::transport::unified::{TransportManager, TransportPreference};
use stellarconduit_core::security::events::SecurityEvent;
use tokio::sync::broadcast;

// Create TransportManager with security event channel
let (tx, mut rx) = broadcast::channel(128);
let mut mgr = TransportManager::with_security_events(TransportPreference::Auto, tx);

// Listen for security events
tokio::spawn(async move {
    while let Ok(event) = rx.recv().await {
        match event {
            SecurityEvent::PeerViolation { peer, reason } => {
                log::warn!("Peer {} violated rate limits: {:?}", peer, reason);
                // Handle ban logic here
            }
        }
    }
});

// Rate limiting is automatically applied in recv_any()
if let Some((peer, msg)) = mgr.recv_any().await {
    // Message passed rate limit check
    // Process message...
}

Breaking Changes

None - This is a purely additive feature. Existing code continues to work without changes.

Future Improvements

  • Configurable rate limits per peer (e.g., based on reputation)
  • Rate limit metrics/exporter for monitoring
  • Adaptive rate limiting based on network conditions
  • Rate limit bypass for trusted/relay nodes

closes #64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(security): Implement transport-level rate limiting and spam protection

1 participant