ek-api 0.1.3

Headless API service for the ek ecosystem: NDJSON JSON-RPC over TCP, token auth, plugin management and event push.
//! token 认证、失败退避与限流(设计 §5.2)。

use std::collections::HashMap;
use std::collections::VecDeque;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};

/// 失败 N 次后锁定该 IP,锁 60s。
const FAIL_LIMIT: u32 = 5;
const LOCK_FOR: Duration = Duration::from_secs(60);
/// 失败后的固定延迟(防枚举)。
pub const FAIL_DELAY: Duration = Duration::from_millis(250);

/// token 文件:32 字节随机 → 64 位 hex;文件不存在则生成。
pub struct TokenStore {
    path: PathBuf,
    token: String,
}

impl TokenStore {
    /// 读取或生成 token(生成后尽力收紧 ACL)。
    pub fn load_or_create(path: &Path) -> Result<Self, String> {
        let existing = std::fs::read_to_string(path).ok();
        let token = match existing {
            Some(t) if !t.trim().is_empty() => t.trim().to_string(),
            _ => {
                let mut buf = [0u8; 32];
                getrandom::fill(&mut buf).map_err(|e| format!("生成 token 失败: {e}"))?;
                let token = hex(&buf);
                if let Some(parent) = path.parent()
                    && !parent.as_os_str().is_empty()
                {
                    std::fs::create_dir_all(parent)
                        .map_err(|e| format!("建 token 目录失败 {parent:?}: {e}"))?;
                }
                std::fs::write(path, &token)
                    .map_err(|e| format!("写 token 文件失败 {path:?}: {e}"))?;
                tighten_acl(path);
                token
            }
        };
        Ok(Self {
            path: path.to_path_buf(),
            token,
        })
    }

    /// 常数时间校验(长度不同直接 false)。
    #[must_use]
    pub fn verify(&self, given: &str) -> bool {
        constant_time_eq(self.token.as_bytes(), given.as_bytes())
    }

    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// 仅供本进程诊断/测试(绝不对外暴露)。
    #[must_use]
    pub fn token(&self) -> &str {
        &self.token
    }
}

/// 定长字节常数时间比较。
#[must_use]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

fn hex(buf: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut s = String::with_capacity(buf.len() * 2);
    for &b in buf {
        s.push(HEX[(b >> 4) as usize] as char);
        s.push(HEX[(b & 0xf) as usize] as char);
    }
    s
}

/// Windows:`icacls <path> /inheritance:r /grant:r <user>:F`(失败只影响日志,不影响启动)。
fn tighten_acl(path: &Path) {
    #[cfg(windows)]
    {
        let Ok(user) = std::env::var("USERNAME") else {
            return;
        };
        if user.is_empty() {
            return;
        }
        let _ = std::process::Command::new("icacls")
            .arg(path)
            .args(["/inheritance:r", "/grant:r"])
            .arg(format!("{user}:F"))
            .output();
    }
    #[cfg(not(windows))]
    {
        let _ = path;
    }
}

/// 每 IP 的失败计数与锁定。
pub struct FailGuard {
    inner: Mutex<HashMap<IpAddr, FailState>>,
}

#[derive(Default)]
struct FailState {
    fails: u32,
    locked_until: Option<Instant>,
}

impl Default for FailGuard {
    fn default() -> Self {
        Self::new()
    }
}

impl FailGuard {
    pub fn new() -> Self {
        Self {
            inner: Mutex::new(HashMap::new()),
        }
    }

    /// 是否处于锁定期(过期即清除)。
    pub fn is_locked(&self, ip: IpAddr) -> bool {
        let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
        let Some(st) = g.get_mut(&ip) else {
            return false;
        };
        match st.locked_until {
            Some(t) if Instant::now() < t => true,
            Some(_) => {
                st.locked_until = None;
                st.fails = 0;
                false
            }
            None => false,
        }
    }

    /// 记一次失败;到阈值即锁定。
    pub fn note_failure(&self, ip: IpAddr) {
        let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
        let st = g.entry(ip).or_default();
        st.fails = st.fails.saturating_add(1);
        if st.fails >= FAIL_LIMIT {
            st.locked_until = Some(Instant::now() + LOCK_FOR);
        }
    }

    /// 成功即清零。
    pub fn note_success(&self, ip: IpAddr) {
        let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
        if let Some(st) = g.get_mut(&ip) {
            st.fails = 0;
            st.locked_until = None;
        }
    }
}

/// 每连接、按 1s 滑动窗口的限流器。
pub struct RateLimiter {
    hits: VecDeque<Instant>,
}

impl Default for RateLimiter {
    fn default() -> Self {
        Self::new()
    }
}

impl RateLimiter {
    pub fn new() -> Self {
        Self {
            hits: VecDeque::new(),
        }
    }

    /// `limit_per_sec` 次/秒内放行。
    pub fn allow(&mut self, limit_per_sec: usize) -> bool {
        let now = Instant::now();
        while let Some(front) = self.hits.front() {
            if now.duration_since(*front) >= Duration::from_secs(1) {
                self.hits.pop_front();
            } else {
                break;
            }
        }
        if self.hits.len() >= limit_per_sec {
            return false;
        }
        self.hits.push_back(now);
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn token_roundtrip_and_verify() {
        let dir = std::env::temp_dir().join(format!("ek-api-auth-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("token");
        let ts = TokenStore::load_or_create(&path).expect("create");
        assert_eq!(ts.token().len(), 64);
        assert!(ts.verify(ts.token()));
        assert!(!ts.verify("deadbeef"));

        let again = TokenStore::load_or_create(&path).expect("reload");
        assert_eq!(again.token(), ts.token());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn constant_time_eq_basics() {
        assert!(constant_time_eq(b"abc", b"abc"));
        assert!(!constant_time_eq(b"abc", b"abd"));
        assert!(!constant_time_eq(b"abc", b"abcd"));
    }

    #[test]
    fn fail_guard_locks_after_five() {
        let g = FailGuard::new();
        let ip: IpAddr = "127.0.0.1".parse().unwrap();
        for _ in 0..4 {
            g.note_failure(ip);
        }
        assert!(!g.is_locked(ip));
        g.note_failure(ip);
        assert!(g.is_locked(ip));
        g.note_success(ip);
        assert!(!g.is_locked(ip));
    }

    #[test]
    fn rate_limiter_window() {
        let mut r = RateLimiter::new();
        assert!(r.allow(2));
        assert!(r.allow(2));
        assert!(!r.allow(2));
    }
}