powchallenge_server 1.0.0

Server validation library for the POW Captcha ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use parking_lot::Mutex;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;

// ──────────────────────────────────────────────────────────────────────────────
// Storage-specific error type (replaces bare `String` errors)
// ──────────────────────────────────────────────────────────────────────────────

#[derive(Error, Debug)]
pub enum StorageError {
    #[error("Server busy")]
    Capacity,
    #[cfg(feature = "redis")]
    #[error("Redis error: {0}")]
    Redis(#[from] redis::RedisError),
    #[error("Serialisation error: {0}")]
    Serde(#[from] serde_json::Error),
}

// ──────────────────────────────────────────────────────────────────────────────
// Serialised challenge state (stored in both Memory and Redis)
// ──────────────────────────────────────────────────────────────────────────────

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct CaptchaRequestState {
    pub challenge: String, // hex-encoded raw bytes
    pub ip: String,
    pub timestamp: String, // RFC-3339
    pub difficulty: u32,
}

// ──────────────────────────────────────────────────────────────────────────────
// StorageBackend — enum dispatch (avoids dynamic dispatch overhead)
// ──────────────────────────────────────────────────────────────────────────────

pub enum StorageBackend {
    Memory(MemoryStorage),
    #[cfg(feature = "redis")]
    Redis(RedisStorage),
}

impl StorageBackend {
    pub async fn count_challenges(&self) -> usize {
        match self {
            StorageBackend::Memory(s) => s.count_challenges(),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.count_challenges().await,
        }
    }

    pub async fn add_challenge(
        &self,
        req_id: &str,
        challenge_bytes: &[u8],
        ip: &str,
        difficulty: u32,
        timestamp: DateTime<Utc>,
        validity_seconds: i64,
    ) -> Result<(), StorageError> {
        match self {
            StorageBackend::Memory(s) => s.add_challenge(req_id, challenge_bytes, ip, difficulty, timestamp, validity_seconds),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.add_challenge(req_id, challenge_bytes, ip, difficulty, timestamp, validity_seconds).await,
        }
    }

    pub async fn get_and_delete_challenge(&self, req_id: &str) -> Option<CaptchaRequestState> {
        match self {
            StorageBackend::Memory(s) => s.get_and_delete_challenge(req_id),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.get_and_delete_challenge(req_id).await,
        }
    }

    pub async fn is_ip_active(&self, ip: &str) -> bool {
        match self {
            StorageBackend::Memory(s) => s.is_ip_active(ip),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.is_ip_active(ip).await,
        }
    }

    pub async fn increment_subnet_history(&self, subnet: &str) {
        match self {
            StorageBackend::Memory(s) => s.increment_subnet_history(subnet),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.increment_subnet_history(subnet).await,
        }
    }

    pub async fn get_subnet_history(&self, subnet: &str) -> u32 {
        match self {
            StorageBackend::Memory(s) => s.get_subnet_history(subnet),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.get_subnet_history(subnet).await,
        }
    }

    pub async fn increment_fingerprint_history(&self, fingerprint: &str) {
        match self {
            StorageBackend::Memory(s) => s.increment_fingerprint_history(fingerprint),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.increment_fingerprint_history(fingerprint).await,
        }
    }

    pub async fn get_fingerprint_history(&self, fingerprint: &str) -> u32 {
        match self {
            StorageBackend::Memory(s) => s.get_fingerprint_history(fingerprint),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.get_fingerprint_history(fingerprint).await,
        }
    }

    pub async fn add_global_solve(&self, timestamp: DateTime<Utc>) {
        match self {
            StorageBackend::Memory(s) => s.add_global_solve(timestamp),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.add_global_solve(timestamp).await,
        }
    }

    pub async fn get_recent_global_solves_count(&self, window_seconds: i64) -> usize {
        match self {
            StorageBackend::Memory(s) => s.get_recent_global_solves_count(window_seconds),
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.get_recent_global_solves_count(window_seconds).await,
        }
    }

    /// Propagate a new capacity limit to the inner storage (SEC-6).
    pub async fn set_max_challenges(&mut self, max: usize) {
        match self {
            StorageBackend::Memory(s) => s.max_challenges = max,
            #[cfg(feature = "redis")]
            StorageBackend::Redis(s) => s.max_challenges = max,
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// In-memory implementation
// ──────────────────────────────────────────────────────────────────────────────

pub struct MemoryStorage {
    active_challenges: Arc<Mutex<HashMap<String, CaptchaRequestState>>>,
    active_ips: Arc<Mutex<HashSet<String>>>,
    fingerprint_history: Arc<Mutex<HashMap<String, u32>>>,
    subnet_history: Arc<Mutex<HashMap<String, u32>>>,
    global_solve_history: Arc<Mutex<VecDeque<DateTime<Utc>>>>,
    pub max_challenges: usize,
}

impl MemoryStorage {
    pub fn new(max_challenges: usize) -> Self {
        Self {
            active_challenges: Arc::new(Mutex::new(HashMap::new())),
            active_ips: Arc::new(Mutex::new(HashSet::new())),
            fingerprint_history: Arc::new(Mutex::new(HashMap::new())),
            subnet_history: Arc::new(Mutex::new(HashMap::new())),
            global_solve_history: Arc::new(Mutex::new(VecDeque::with_capacity(1000))),
            max_challenges,
        }
    }

    fn cleanup_expired(&self, validity_seconds: i64) {
        let now = Utc::now();
        let mut challenges = self.active_challenges.lock();
        let mut ips = self.active_ips.lock();

        let expired: Vec<String> = challenges
            .iter()
            .filter_map(|(id, state)| {
                state.timestamp.parse::<DateTime<Utc>>().ok().and_then(|ts| {
                    if (now - ts).num_seconds() > validity_seconds { Some(id.clone()) } else { None }
                })
            })
            .collect();

        for id in expired {
            if let Some(state) = challenges.remove(&id) {
                ips.remove(&state.ip);
            }
        }
    }

    pub fn count_challenges(&self) -> usize { self.active_challenges.lock().len() }

    pub fn add_challenge(
        &self,
        req_id: &str,
        challenge_bytes: &[u8],
        ip: &str,
        difficulty: u32,
        timestamp: DateTime<Utc>,
        validity_seconds: i64,
    ) -> Result<(), StorageError> {
        self.cleanup_expired(validity_seconds);
        let mut challenges = self.active_challenges.lock();
        if challenges.len() >= self.max_challenges {
            return Err(StorageError::Capacity);
        }
        challenges.insert(req_id.to_string(), CaptchaRequestState {
            challenge: hex::encode(challenge_bytes),
            ip: ip.to_string(),
            timestamp: timestamp.to_rfc3339(),
            difficulty,
        });
        self.active_ips.lock().insert(ip.to_string());
        Ok(())
    }

    pub fn get_and_delete_challenge(&self, req_id: &str) -> Option<CaptchaRequestState> {
        let state = self.active_challenges.lock().remove(req_id);
        if let Some(ref s) = state { self.active_ips.lock().remove(&s.ip); }
        state
    }

    pub fn is_ip_active(&self, ip: &str) -> bool { self.active_ips.lock().contains(ip) }

    fn evict_map(map: &mut HashMap<String, u32>) {
        if map.len() > 10000 {
            let mut entries: Vec<_> = map.iter().map(|(k, v)| (k.clone(), *v)).collect();
            entries.sort_by(|a, b| b.1.cmp(&a.1));
            map.clear();
            for (k, v) in entries.into_iter().take(5000) { map.insert(k, v); }
        }
    }

    pub fn increment_subnet_history(&self, subnet: &str) {
        let mut h = self.subnet_history.lock();
        *h.entry(subnet.to_string()).or_insert(0) += 1;
        Self::evict_map(&mut h);
    }

    pub fn get_subnet_history(&self, subnet: &str) -> u32 {
        *self.subnet_history.lock().get(subnet).unwrap_or(&0)
    }

    pub fn increment_fingerprint_history(&self, fingerprint: &str) {
        let mut h = self.fingerprint_history.lock();
        *h.entry(fingerprint.to_string()).or_insert(0) += 1;
        Self::evict_map(&mut h);
    }

    pub fn get_fingerprint_history(&self, fingerprint: &str) -> u32 {
        *self.fingerprint_history.lock().get(fingerprint).unwrap_or(&0)
    }

    pub fn add_global_solve(&self, timestamp: DateTime<Utc>) {
        self.global_solve_history.lock().push_back(timestamp);
    }

    pub fn get_recent_global_solves_count(&self, window_seconds: i64) -> usize {
        let mut hist = self.global_solve_history.lock();
        let now = Utc::now();
        while let Some(&front) = hist.front() {
            if (now - front).num_seconds() > window_seconds { hist.pop_front(); } else { break; }
        }
        hist.len()
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Redis implementation (requires feature "redis")
// ──────────────────────────────────────────────────────────────────────────────

#[cfg(feature = "redis")]
/// Lua script: atomically GET then DEL a key.
/// Prevents the TOCTOU replay-attack race that a plain pipeline has (SEC-1).
const LUA_GET_AND_DELETE: &str = r#"
local v = redis.call('GET', KEYS[1])
if v then
    redis.call('DEL', KEYS[1])
    return v
end
return false
"#;

#[cfg(feature = "redis")]
pub struct RedisStorage {
    con: redis::aio::MultiplexedConnection,
    pub max_challenges: usize,
    prefix: String,
}

#[cfg(feature = "redis")]
impl RedisStorage {
    pub async fn new(redis_url: &str, max_challenges: usize) -> Result<Self, StorageError> {
        let client = redis::Client::open(redis_url)?;
        let con = client.get_multiplexed_async_connection().await?;
        Ok(Self {
            con,
            max_challenges,
            prefix: "pow_captcha:".to_string(),
        })
    }

    pub async fn count_challenges(&self) -> usize {
        let mut con = self.con.clone();
        let now = Utc::now().timestamp();
        let key = format!("{}active_challenges_zset", self.prefix);
        let _: () = redis::cmd("ZREMRANGEBYSCORE")
            .arg(&key).arg("-inf").arg(now - 300)
            .query_async(&mut con).await.unwrap_or(());
        redis::cmd("ZCARD").arg(&key).query_async(&mut con).await.unwrap_or(0)
    }

    pub async fn add_challenge(
        &self,
        req_id: &str,
        challenge_bytes: &[u8],
        ip: &str,
        difficulty: u32,
        timestamp: DateTime<Utc>,
        validity_seconds: i64,
    ) -> Result<(), StorageError> {
        let mut con = self.con.clone();
        let state = CaptchaRequestState {
            challenge: hex::encode(challenge_bytes),
            ip: ip.to_string(),
            timestamp: timestamp.to_rfc3339(),
            difficulty,
        };
        let state_json = serde_json::to_string(&state)?;

        let mut pipe = redis::pipe();
        pipe.cmd("SETEX").arg(format!("{}req:{}", self.prefix, req_id)).arg(validity_seconds).arg(&state_json);
        pipe.cmd("SETEX").arg(format!("{}ip:{}", self.prefix, ip)).arg(validity_seconds).arg("1");
        pipe.cmd("ZADD").arg(format!("{}active_challenges_zset", self.prefix)).arg(timestamp.timestamp()).arg(req_id);
        let _: () = pipe.query_async(&mut con).await?;
        Ok(())
    }

    /// Atomic get-and-delete via Lua script — eliminates replay-attack race (SEC-1).
    pub async fn get_and_delete_challenge(&self, req_id: &str) -> Option<CaptchaRequestState> {
        let mut con = self.con.clone();
        let req_key = format!("{}req:{}", self.prefix, req_id);

        let raw: Option<String> = redis::Script::new(LUA_GET_AND_DELETE)
            .key(&req_key)
            .invoke_async(&mut con)
            .await
            .unwrap_or(None);

        let raw = raw?;
        let state: CaptchaRequestState = serde_json::from_str(&raw).ok()?;

        // Best-effort cleanup of ancillary keys (non-critical)
        let mut pipe = redis::pipe();
        pipe.cmd("DEL").arg(format!("{}ip:{}", self.prefix, state.ip));
        pipe.cmd("ZREM").arg(format!("{}active_challenges_zset", self.prefix)).arg(req_id);
        let _: () = pipe.query_async(&mut con).await.unwrap_or(());

        Some(state)
    }

    pub async fn is_ip_active(&self, ip: &str) -> bool {
        let mut con = self.con.clone();
        redis::cmd("EXISTS")
            .arg(format!("{}ip:{}", self.prefix, ip))
            .query_async(&mut con).await.unwrap_or(false)
    }

    pub async fn increment_subnet_history(&self, subnet: &str) {
        let mut con = self.con.clone();
        let key = format!("{}subnet:{}", self.prefix, subnet);
        let _: () = redis::cmd("INCR").arg(&key).query_async(&mut con).await.unwrap_or(());
        let _: () = redis::cmd("EXPIRE").arg(&key).arg(86400).query_async(&mut con).await.unwrap_or(());
    }

    pub async fn get_subnet_history(&self, subnet: &str) -> u32 {
        let mut con = self.con.clone();
        redis::cmd("GET")
            .arg(format!("{}subnet:{}", self.prefix, subnet))
            .query_async(&mut con).await.unwrap_or(0)
    }

    pub async fn increment_fingerprint_history(&self, fingerprint: &str) {
        let mut con = self.con.clone();
        let key = format!("{}fingerprint:{}", self.prefix, fingerprint);
        let _: () = redis::cmd("INCR").arg(&key).query_async(&mut con).await.unwrap_or(());
        let _: () = redis::cmd("EXPIRE").arg(&key).arg(86400).query_async(&mut con).await.unwrap_or(());
    }

    pub async fn get_fingerprint_history(&self, fingerprint: &str) -> u32 {
        let mut con = self.con.clone();
        redis::cmd("GET")
            .arg(format!("{}fingerprint:{}", self.prefix, fingerprint))
            .query_async(&mut con).await.unwrap_or(0)
    }

    pub async fn add_global_solve(&self, timestamp: DateTime<Utc>) {
        let mut con = self.con.clone();
        let key = format!("{}global_solves", self.prefix);
        let score = timestamp.timestamp();
        let member = format!("{}-{}", score, rand::random::<u32>());
        let _: () = redis::cmd("ZADD").arg(&key).arg(score).arg(&member).query_async(&mut con).await.unwrap_or(());
        let _: () = redis::cmd("ZREMRANGEBYSCORE").arg(&key).arg("-inf").arg(score - 60).query_async(&mut con).await.unwrap_or(());
    }

    pub async fn get_recent_global_solves_count(&self, window_seconds: i64) -> usize {
        let mut con = self.con.clone();
        let key = format!("{}global_solves", self.prefix);
        let now = Utc::now().timestamp();
        redis::cmd("ZCOUNT").arg(&key).arg(now - window_seconds).arg("+inf").query_async(&mut con).await.unwrap_or(0)
    }
}