guard/src/config/sections/edge.rs
loki5512344 918e561a61
feat(xdp): IPv6 UDP rate limit, working loader; English JavaDoc comments
XDP behaviour:
- udp_rate_limit6 (LRU, 128-bit source key) + throttle_hit6, so
  udp_policy = "rate-limit" now applies to native IPv6 as well.
- scripts/xdp_ipv6_smoke.sh: phase 4 patches .rodata before load and
  verifies policy=2 on a real kernel (3 pass / 3 rate-limited).

XDP loader (was completely broken, never reached the verifier):
- .rodata is now one struct rampart_config with frozen offsets enforced by
  _Static_assert; XdpGlobals is #[repr(C)] and the image is built with
  offset_of!. Previously a 96-byte image was written into a 76-byte map at
  offsets clang had reordered, so load() failed with EINVAL.
- patch_rodata fails loudly when the map size and the image size diverge.
- build.rs tracks xdp/core and xdp/hooks, not just universal_filter.c.
- build_ringbuf looked for "events_map"; the map is "events_ringbuf".
- tests/xdp_object_maps.rs: verifies map names and .rodata size without root;
  the real binary was confirmed to attach in a netns.

Docs and style:
- Code comments are English, JavaDoc/Rustdoc style, without emoji or
  decorative banners (new project rule, TODO §0.8).
- README rewritten bilingual: Russian first, English below, TOC and
  copy-paste quick start.
- docs/README.md: documentation index and maintenance rules;
  configuration.md documents the whole [xdp] section and IPv4/IPv6 coverage;
  testing.md describes the real-kernel smoke; stale research links removed.
2026-11-15 23:44:07 +01:00

240 lines
5.8 KiB
Rust

//! Edge sections: bind, backend, workers, limits, ban, PoW and PROXY protocol.
use serde::{Deserialize, Deserializer};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
/// `[bind]` section: listen address and port of the edge node.
#[derive(Debug, Clone, Deserialize)]
pub struct BindConfig {
#[serde(default = "default_bind_address")]
pub address: String,
#[serde(default = "default_bind_port")]
pub port: u16,
}
impl Default for BindConfig {
fn default() -> Self {
Self {
address: default_bind_address(),
port: default_bind_port(),
}
}
}
fn default_bind_address() -> String {
"0.0.0.0".to_string()
}
fn default_bind_port() -> u16 {
25565
}
/// `[backend]` section: upstream backends (`addr:port`) behind the edge node.
#[derive(Debug, Clone, Deserialize)]
pub struct BackendConfig {
#[serde(default = "default_upstreams")]
pub upstreams: Vec<String>,
}
impl Default for BackendConfig {
fn default() -> Self {
Self {
upstreams: default_upstreams(),
}
}
}
fn default_upstreams() -> Vec<String> {
vec!["127.0.0.1:25566".to_string()]
}
/// `[workers]` section: number of accept loops sharing the listen address.
#[derive(Debug, Clone, Deserialize)]
pub struct WorkerConfig {
#[serde(default = "default_worker_count")]
pub count: usize,
}
impl Default for WorkerConfig {
fn default() -> Self {
Self { count: 4 }
}
}
fn default_worker_count() -> usize {
4
}
/// `[limits]` section: per-IP connection and rate limits.
#[derive(Debug, Clone, Deserialize)]
pub struct LimitsConfig {
#[serde(default = "default_handshake_timeout")]
pub handshake_timeout_secs: u64,
#[serde(default = "default_max_connections_per_ip")]
pub max_connections_per_ip: u32,
#[serde(default = "default_rate_limit_pps")]
pub rate_limit_pps: f64,
#[serde(default = "default_rate_limit_burst")]
pub rate_limit_burst: f64,
}
impl Default for LimitsConfig {
fn default() -> Self {
Self {
handshake_timeout_secs: default_handshake_timeout(),
max_connections_per_ip: default_max_connections_per_ip(),
rate_limit_pps: default_rate_limit_pps(),
rate_limit_burst: default_rate_limit_burst(),
}
}
}
fn default_handshake_timeout() -> u64 {
5
}
fn default_max_connections_per_ip() -> u32 {
10
}
fn default_rate_limit_pps() -> f64 {
5.0
}
fn default_rate_limit_burst() -> f64 {
10.0
}
/// `[ban]` section: default ban duration.
#[derive(Debug, Clone, Deserialize)]
pub struct BanConfig {
#[serde(default = "default_ban_duration")]
pub ban_duration_secs: u64,
}
impl Default for BanConfig {
fn default() -> Self {
Self {
ban_duration_secs: default_ban_duration(),
}
}
}
fn default_ban_duration() -> u64 {
3600
}
/// `[pow]` section: proof-of-work gate.
#[derive(Debug, Clone, Deserialize)]
pub struct PowConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default = "default_pow_difficulty")]
pub difficulty: u8,
}
impl Default for PowConfig {
fn default() -> Self {
Self {
enabled: false,
difficulty: default_pow_difficulty(),
}
}
}
fn default_pow_difficulty() -> u8 {
4
}
/// CIDR network allowed to send inbound PROXY protocol headers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TrustedProxyCidr {
network: IpAddr,
prefix_len: u8,
}
impl TrustedProxyCidr {
/// Returns whether `ip` belongs to this network.
#[must_use]
pub fn contains(&self, ip: IpAddr) -> bool {
let mask4 = mask_v4(self.prefix_len);
let mask6 = mask_v6(self.prefix_len);
match (self.network, ip) {
(IpAddr::V4(network), IpAddr::V4(ip)) => u32::from(network) & mask4 == u32::from(ip) & mask4,
(IpAddr::V6(network), IpAddr::V6(ip)) => u128::from(network) & mask6 == u128::from(ip) & mask6,
_ => false,
}
}
}
impl FromStr for TrustedProxyCidr {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let (address, prefix) = match value.split_once('/') {
Some((address, prefix)) => (address, Some(prefix)),
None => (value, None),
};
let network = IpAddr::from_str(address).map_err(|_| format!("invalid trusted proxy CIDR: {value}"))?;
let max_prefix = if network.is_ipv4() { 32 } else { 128 };
let prefix_len = match prefix {
Some(prefix) => prefix
.parse::<u8>()
.map_err(|_| format!("invalid trusted proxy CIDR prefix: {value}"))?,
None => max_prefix,
};
if prefix_len > max_prefix {
return Err(format!("trusted proxy CIDR prefix is too large: {value}"));
}
let network = match network {
IpAddr::V4(ip) => IpAddr::V4(Ipv4Addr::from(u32::from(ip) & mask_v4(prefix_len))),
IpAddr::V6(ip) => IpAddr::V6(Ipv6Addr::from(u128::from(ip) & mask_v6(prefix_len))),
};
Ok(Self { network, prefix_len })
}
}
impl<'de> Deserialize<'de> for TrustedProxyCidr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
value.parse().map_err(serde::de::Error::custom)
}
}
fn mask_v4(prefix: u8) -> u32 {
if prefix == 0 { 0 } else { u32::MAX << (32 - prefix) }
}
fn mask_v6(prefix: u8) -> u128 {
if prefix == 0 { 0 } else { u128::MAX << (128 - prefix) }
}
/// `[proxy_protocol]` section: inbound PROXY protocol ingestion.
#[derive(Debug, Clone, Deserialize)]
pub struct ProxyProtocolConfig {
#[serde(default)]
pub ingress_enabled: bool,
#[serde(default)]
pub trusted_cidrs: Vec<TrustedProxyCidr>,
#[serde(default = "default_proxy_protocol_timeout_ms")]
pub ingress_timeout_ms: u64,
#[serde(default = "default_proxy_protocol_max_header_bytes")]
pub max_header_bytes: usize,
}
impl Default for ProxyProtocolConfig {
fn default() -> Self {
Self {
ingress_enabled: false,
trusted_cidrs: Vec::new(),
ingress_timeout_ms: default_proxy_protocol_timeout_ms(),
max_header_bytes: default_proxy_protocol_max_header_bytes(),
}
}
}
fn default_proxy_protocol_timeout_ms() -> u64 {
750
}
fn default_proxy_protocol_max_header_bytes() -> usize {
512
}