fix(core): close auth bypass, hangs and memory leaks found by review

Security:
- An empty API_PASSWORD passed validation (only the literal "changeme" was
  rejected) and verify_password("", "") returned true, so a login with an
  empty password minted an admin token. Require >= 16 characters and >= 32
  non-whitespace bytes for JWT_SECRET; verify rejects an empty stored secret.
- syn_challenge_enabled required a real challenge_secret_hex: the public
  placeholder from config.h is now rejected in every spelling.
- docker-compose: Redis/ClickHouse/Grafana are loopback-only and every
  password uses ${VAR:?} instead of a default. An exposed Redis was a way to
  lift bans and publish unbans to the whole fleet with one redis-cli.
- Empty CORS_ORIGIN no longer means "allow any origin".
- ban_cidr / userspace blacklist validate and mask prefixes; CIDR bans are
  stored as ranges, so a /24 or /64 ban actually covers the subnet (before,
  only the network address was blocked).

Availability:
- ClickHouse client has connect/request timeouts and no mutex held across
  await: a hung analytics backend can no longer freeze the ban path. Events
  go through a bounded buffer with a drop counter.
- Redis uses a ConnectionManager with per-command timeouts; pubsub and
  reconcile reset the backoff after success; publish cannot block shutdown.
- Ban durations from pubsub are clamped and use checked_add; the sync task
  survives panics instead of silently dying.
- Blacklist TOCTOU (remove_if) and replace_redis no longer empties the table
  during a Redis reconnect.
- RateLimiter and reputation have hard caps with incremental eviction instead
  of an unbounded DashMap and a stop-the-world retain.
- The attack detector scores before updating its baseline and needs several
  quiet windows to leave UnderAttack, so a sustained flood keeps banning new
  offenders instead of ending after one tick.
- accept() backs off on EMFILE/ENFILE, shutdown Err is treated as shutdown,
  a global semaphore bounds in-flight connections, rate limiting runs before
  PoW, whitelisted IPs are never banned, and connect/handshake/relay have
  timeouts with an idle budget.
- PoW uses the configured difficulty as a floor, the clamp is enforced, and
  nonce framing survives split segments and coalesced handshake bytes.
- Subnet tracker memory is capped (prefixes and per-prefix sources) and the
  monitor bans with the configured TTL.

CI and docs:
- CI runs the test suite with --no-default-features --features protocol-http;
  make ebpf fails on errors; the secrets gate catches weak compose defaults.
- doctor skips protected endpoints without a token and exits non-zero on
  failure; a drain timeout returns exit code 1.
- TODO §2b records the review findings, what is fixed and what is deferred;
  configuration/testing docs describe the new XDP and secret semantics.
This commit is contained in:
Loki 2026-11-16 12:06:23 +01:00
parent 14dcaccdbf
commit c1a076a4a3
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
57 changed files with 4193 additions and 1171 deletions

View file

@ -0,0 +1,75 @@
//! Idle-aware bidirectional relay between the accepted client and the backend.
use super::Gateway;
use std::io;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
const RELAY_BUFFER_BYTES: usize = 16 * 1024;
/// Idle budget of the client/backend relay.
///
/// Minecraft keeps one connection alive for a whole session and a legitimately
/// silent gap (menus, chunk loading, AFK timeouts) can last minutes, so 300s is
/// the safe default: it never cuts a real session and still reaps dead peers.
/// The value is a constant because `[limits]` is owned by a parallel change; it
/// is plumbed as a parameter through [`Gateway::relay_with_idle`] so a config
/// field can be wired in without touching the relay itself.
pub const RELAY_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
impl Gateway {
/// Relays bytes in both directions until either side closes, an I/O error
/// occurs or a direction stays silent for `idle`.
///
/// The idle budget restarts on every successful read/write, so a long-lived
/// session with steady traffic is never cut, while a dead or half-open peer
/// is reaped instead of pinning two descriptors forever. Both directions run
/// under one `select!`: when one pump finishes the other is dropped and both
/// sockets close, preserving the cancellation semantics of
/// `copy_bidirectional`.
///
/// `idle` is a parameter rather than a constant so tests can exercise the
/// timeout with a short budget and per-upstream tuning can override it.
///
/// # Errors
/// Fails on the first I/O error and on an idle timeout; a clean half-close is
/// `Ok`.
pub async fn relay_with_idle(&self, client: TcpStream, backend: TcpStream, idle: Duration) -> anyhow::Result<()> {
let (client_read, mut client_write) = client.into_split();
let (backend_read, mut backend_write) = backend.into_split();
tokio::select! {
result = pump(client_read, &mut backend_write, idle) => result?,
result = pump(backend_read, &mut client_write, idle) => result?,
}
Ok(())
}
}
/// Copies one direction, bounded by `idle` between chunks.
///
/// # Errors
/// Fails on a read/write error and when a direction makes no progress within
/// `idle`.
async fn pump<R, W>(mut source: R, mut sink: W, idle: Duration) -> io::Result<()>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
let mut buffer = vec![0u8; RELAY_BUFFER_BYTES];
loop {
let read = tokio::time::timeout(idle, source.read(&mut buffer))
.await
.map_err(|_| idle_error())??;
if read == 0 {
return Ok(());
}
tokio::time::timeout(idle, sink.write_all(&buffer[..read]))
.await
.map_err(|_| idle_error())??;
}
}
fn idle_error() -> io::Error {
io::Error::new(io::ErrorKind::TimedOut, "relay idle timeout")
}