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};
const FAIL_LIMIT: u32 = 5;
const LOCK_FOR: Duration = Duration::from_secs(60);
pub const FAIL_DELAY: Duration = Duration::from_millis(250);
pub struct TokenStore {
path: PathBuf,
token: String,
}
impl TokenStore {
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,
})
}
#[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
}
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;
}
}
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;
}
}
}
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(),
}
}
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));
}
}