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
use libmcaptcha::dev::{AddVisitorResult, CreateMCaptcha, DefenseBuilder, MCaptchaBuilder};
use redis_module::key::RedisKey;
use redis_module::key::RedisKeyWritable;
use redis_module::native_types::RedisType;
use redis_module::raw::KeyType;
use redis_module::RedisError;
use redis_module::RedisString;
use redis_module::RedisValue;
use redis_module::{Context, RedisResult};
use redis_module::{NextArg, REDIS_OK};
use redis_module::raw;
use serde::{Deserialize, Serialize};
use crate::bucket::Format;
use crate::errors::*;
use crate::safety::MCaptchaSafety;
use crate::utils::*;
const REDIS_MCPATCHA_MCAPTCHA_TYPE_VERSION: i32 = 0;
#[derive(Serialize, Deserialize)]
pub struct MCaptcha {
m: libmcaptcha::dev::MCaptcha,
}
impl MCaptcha {
#[inline]
pub fn get_add_visitor_result(&self) -> AddVisitorResult {
AddVisitorResult::new(&self.m)
}
#[inline]
fn new(mut m: CreateMCaptcha) -> CacheResult<Self> {
let mut defense_builder = DefenseBuilder::default();
let mut defense_builder = &mut defense_builder;
for l in m.levels.drain(0..) {
defense_builder = defense_builder.add_level(l)?;
}
let defense = defense_builder.build()?;
let m = MCaptchaBuilder::default()
.defense(defense)
.duration(m.duration)
.build()?;
Ok(MCaptcha { m })
}
#[inline]
pub fn add_visitor(&mut self) {
self.m.add_visitor()
}
#[inline]
#[allow(dead_code)]
pub fn decrement_visitor(&mut self) {
self.m.decrement_visitor()
}
#[inline]
#[allow(dead_code)]
pub fn get_difficulty(&self) -> u32 {
self.m.get_difficulty()
}
#[inline]
#[allow(dead_code)]
pub fn get_duration(&self) -> u64 {
self.m.get_duration()
}
#[inline]
#[allow(dead_code)]
pub fn get_visitors(&self) -> u32 {
self.m.get_visitors()
}
#[inline]
pub fn decrement_visitor_by(&mut self, count: u32) {
self.m.decrement_visitor_by(count)
}
#[inline]
pub fn get_mut_mcaptcha(key: &RedisKeyWritable) -> CacheResult<Option<&mut Self>> {
Ok(key.get_value::<Self>(&MCAPTCHA_MCAPTCHA_TYPE)?)
}
#[inline]
pub fn get_mcaptcha(key: &RedisKey) -> CacheResult<Option<&Self>> {
Ok(key.get_value::<Self>(&MCAPTCHA_MCAPTCHA_TYPE)?)
}
pub fn get_count(ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key_name = args.next_string()?;
let key_name = get_captcha_key(&key_name);
let stored_captcha = ctx.open_key(&RedisString::create(ctx.ctx, &key_name));
if stored_captcha.key_type() == KeyType::Empty {
return CacheError::new(format!("key {} not found", key_name)).into();
}
match stored_captcha.get_value::<Self>(&MCAPTCHA_MCAPTCHA_TYPE)? {
Some(val) => Ok(RedisValue::Integer(val.get_visitors().into())),
None => Err(CacheError::CaptchaNotFound.into()),
}
}
pub fn add_captcha(ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key_name = get_captcha_key(&args.next_string()?);
let json = args.next_string()?;
let mcaptcha: CreateMCaptcha = Format::Json.from_str(&json)?;
let mcaptcha = Self::new(mcaptcha)?;
Self::add_captcha_runner(ctx, &key_name, mcaptcha)
}
#[inline]
fn add_captcha_runner(ctx: &Context, key_name: &str, mcaptcha: MCaptcha) -> RedisResult {
let duration = mcaptcha.get_duration();
let key = ctx.open_key_writable(&RedisString::create(ctx.ctx, key_name));
if key.key_type() == KeyType::Empty {
key.set_value(&MCAPTCHA_MCAPTCHA_TYPE, mcaptcha)?;
ctx.log_debug(&format!("mcaptcha {} created", key_name));
MCaptchaSafety::new(ctx, duration, key_name)?;
REDIS_OK
} else {
let msg = format!("mcaptcha {} exists", key_name);
ctx.log_debug(&msg);
Err(CacheError::new(msg).into())
}
}
pub fn captcha_exists(ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key_name = get_captcha_key(&args.next_string()?);
let key = ctx.open_key(&RedisString::create(ctx.ctx, &key_name));
if Self::captcha_exists_runner(&key) {
Ok(RedisValue::Integer(0))
} else {
Ok(RedisValue::Integer(1))
}
}
#[inline]
fn captcha_exists_runner(key: &RedisKey) -> bool {
!(key.key_type() == KeyType::Empty)
}
pub fn rename(ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key_name = get_captcha_key(&args.next_string()?);
let new_name = get_captcha_key(&args.next_string()?);
let key = ctx.open_key(&RedisString::create(ctx.ctx, &key_name));
if Self::captcha_exists_runner(&key) {
if let Some(mcaptcha) = Self::get_mcaptcha(&key)? {
let mcaptcha = MCaptcha {
m: MCaptchaBuilder::default()
.defense(mcaptcha.m.get_defense())
.duration(mcaptcha.get_duration())
.build()?,
};
Self::add_captcha_runner(ctx, &new_name, mcaptcha)?;
Self::delete_captcha_runner(ctx, &key_name)?;
}
};
REDIS_OK
}
pub fn delete_captcha(ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key_name = get_captcha_key(&args.next_string()?);
Self::delete_captcha_runner(ctx, &key_name)
}
#[inline]
fn delete_captcha_runner(ctx: &Context, key_name: &str) -> RedisResult {
let key = ctx.open_key_writable(&RedisString::create(ctx.ctx, key_name));
if key.key_type() == KeyType::Empty {
Err(RedisError::nonexistent_key())
} else {
key.delete()?;
REDIS_OK
}
}
}
pub static MCAPTCHA_MCAPTCHA_TYPE: RedisType = RedisType::new(
"mcaptmcap",
REDIS_MCPATCHA_MCAPTCHA_TYPE_VERSION,
raw::RedisModuleTypeMethods {
version: raw::REDISMODULE_TYPE_METHOD_VERSION as u64,
rdb_load: Some(type_methods::rdb_load),
rdb_save: Some(type_methods::rdb_save),
aof_rewrite: None,
free: Some(type_methods::free),
mem_usage: None,
digest: None,
aux_load: None,
aux_save: None,
aux_save_triggers: 0,
free_effort: None,
unlink: None,
copy: None,
defrag: None,
},
);
pub mod type_methods {
use std::os::raw::c_void;
use libc::c_int;
use super::*;
#[allow(non_snake_case, unused)]
pub extern "C" fn rdb_load(rdb: *mut raw::RedisModuleIO, encver: c_int) -> *mut c_void {
let mcaptcha = match encver {
0 => {
let data = raw::load_string(rdb).unwrap().to_string();
let mcaptcha: Result<MCaptcha, CacheError> = Format::Json.from_str(&data);
if mcaptcha.is_err() {
panic!(
"Can't load mCaptcha from old redis RDB, error while serde {}, data received: {}",
mcaptcha.err().unwrap(),
data
);
}
mcaptcha.unwrap()
}
_ => panic!("Can't load mCaptcha from old redis RDB, encver {}", encver),
};
Box::into_raw(Box::new(mcaptcha)) as *mut c_void
}
pub unsafe extern "C" fn free(value: *mut c_void) {
let val = value as *mut MCaptcha;
Box::from_raw(val);
}
#[allow(non_snake_case, unused)]
pub unsafe extern "C" fn rdb_save(rdb: *mut raw::RedisModuleIO, value: *mut c_void) {
let mcaptcha = &*(value as *mut MCaptcha);
match &serde_json::to_string(mcaptcha) {
Ok(string) => raw::save_string(rdb, string),
Err(e) => panic!("error while rdb_save: {}", e),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use libmcaptcha::defense::Level;
use libmcaptcha::defense::LevelBuilder;
fn get_levels() -> Vec<Level> {
let mut levels = Vec::default();
levels.push(
LevelBuilder::default()
.visitor_threshold(50)
.difficulty_factor(50)
.unwrap()
.build()
.unwrap(),
);
levels.push(
LevelBuilder::default()
.visitor_threshold(500)
.difficulty_factor(5000)
.unwrap()
.build()
.unwrap(),
);
levels.push(
LevelBuilder::default()
.visitor_threshold(5000)
.difficulty_factor(50000)
.unwrap()
.build()
.unwrap(),
);
levels.push(
LevelBuilder::default()
.visitor_threshold(50000)
.difficulty_factor(500000)
.unwrap()
.build()
.unwrap(),
);
levels.push(
LevelBuilder::default()
.visitor_threshold(500000)
.difficulty_factor(5000000)
.unwrap()
.build()
.unwrap(),
);
levels
}
#[test]
fn create_mcaptcha_works() {
let levels = get_levels();
let payload = CreateMCaptcha {
levels,
duration: 30,
};
let mcaptcha = MCaptcha::new(payload);
assert!(mcaptcha.is_ok());
let mut mcaptcha = mcaptcha.unwrap();
for _ in 0..50 {
mcaptcha.add_visitor();
}
assert_eq!(mcaptcha.get_visitors(), 50);
assert_eq!(mcaptcha.get_difficulty(), 50);
for _ in 0..451 {
mcaptcha.add_visitor();
}
assert_eq!(mcaptcha.get_visitors(), 501);
assert_eq!(mcaptcha.get_difficulty(), 5000);
mcaptcha.decrement_visitor_by(501);
for _ in 0..5002 {
mcaptcha.add_visitor();
}
assert_eq!(mcaptcha.get_visitors(), 5002);
assert_eq!(mcaptcha.get_difficulty(), 50000);
}
}