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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use std::borrow::Cow;
use actix_identity::Identity;
use actix_web::{web, HttpResponse, Responder};
use libmcaptcha::master::messages::{RemoveCaptcha, RenameBuilder};
use libmcaptcha::{defense::Level, defense::LevelBuilder};
use serde::{Deserialize, Serialize};
use super::get_random;
use super::levels::{add_captcha_runner, AddLevels};
use crate::errors::*;
use crate::settings::DefaultDifficultyStrategy;
use crate::stats::fetch::{Stats, StatsUnixTimestamp};
use crate::AppData;
pub mod routes {
pub struct MCaptcha {
pub delete: &'static str,
pub update_key: &'static str,
pub stats: &'static str,
pub user_provided_traffic_pattern: &'static str,
}
impl MCaptcha {
pub const fn new() -> MCaptcha {
MCaptcha {
update_key: "/api/v1/mcaptcha/update/key",
delete: "/api/v1/mcaptcha/delete",
stats: "/api/v1/mcaptcha/stats",
user_provided_traffic_pattern:
"/api/v1/mcaptcha/add/user-provided-traffic-pattern",
}
}
}
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(update_token);
cfg.service(delete_mcaptcha);
cfg.service(get_stats);
cfg.service(from_user_provided_traffic_pattern);
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MCaptchaID {
pub name: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MCaptchaDetails {
pub name: String,
pub key: String,
}
#[my_codegen::post(
path = "crate::V1_API_ROUTES.mcaptcha.update_key",
wrap = "crate::CheckLogin"
)]
async fn update_token(
payload: web::Json<MCaptchaDetails>,
data: AppData,
id: Identity,
) -> ServiceResult<impl Responder> {
let username = id.identity().unwrap();
let mut key;
loop {
key = get_random(32);
let res = update_token_helper(&key, &payload.key, &username, &data).await;
if res.is_ok() {
break;
} else if let Err(sqlx::Error::Database(err)) = res {
if err.code() == Some(Cow::from("23505")) {
continue;
} else {
return Err(sqlx::Error::Database(err).into());
}
};
}
let payload = payload.into_inner();
let rename = RenameBuilder::default()
.name(payload.key)
.rename_to(key.clone())
.build()
.unwrap();
data.captcha.rename(rename).await?;
let resp = MCaptchaDetails {
key,
name: payload.name,
};
Ok(HttpResponse::Ok().json(resp))
}
async fn update_token_helper(
key: &str,
old_key: &str,
username: &str,
data: &AppData,
) -> Result<(), sqlx::Error> {
sqlx::query!(
"UPDATE mcaptcha_config SET key = $1
WHERE key = $2 AND user_id = (SELECT ID FROM mcaptcha_users WHERE name = $3)",
&key,
&old_key,
&username,
)
.execute(&data.db)
.await?;
Ok(())
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DeleteCaptcha {
pub key: String,
pub password: String,
}
#[my_codegen::post(
path = "crate::V1_API_ROUTES.mcaptcha.delete",
wrap = "crate::CheckLogin"
)]
async fn delete_mcaptcha(
payload: web::Json<DeleteCaptcha>,
data: AppData,
id: Identity,
) -> ServiceResult<impl Responder> {
use argon2_creds::Config;
use sqlx::Error::RowNotFound;
let username = id.identity().unwrap();
struct PasswordID {
password: String,
id: i32,
}
let rec = sqlx::query_as!(
PasswordID,
r#"SELECT ID, password FROM mcaptcha_users WHERE name = ($1)"#,
&username,
)
.fetch_one(&data.db)
.await;
match rec {
Ok(rec) => {
if Config::verify(&rec.password, &payload.password)? {
let payload = payload.into_inner();
sqlx::query!(
"DELETE FROM mcaptcha_levels
WHERE config_id = (
SELECT config_id FROM mcaptcha_config
WHERE key = $1 AND user_id = $2
);",
&payload.key,
&rec.id,
)
.execute(&data.db)
.await?;
sqlx::query!(
"DELETE FROM mcaptcha_config WHERE key = ($1) AND user_id = $2;",
&payload.key,
&rec.id,
)
.execute(&data.db)
.await?;
if let Err(err) = data.captcha.remove(RemoveCaptcha(payload.key)).await {
log::error!(
"Error while trying to remove captcha from cache {}",
err
);
}
Ok(HttpResponse::Ok())
} else {
Err(ServiceError::WrongPassword)
}
}
Err(RowNotFound) => Err(ServiceError::UsernameNotFound),
Err(_) => Err(ServiceError::InternalServerError),
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StatsPayload {
pub key: String,
}
#[my_codegen::post(
path = "crate::V1_API_ROUTES.mcaptcha.stats",
wrap = "crate::CheckLogin"
)]
async fn get_stats(
payload: web::Json<StatsPayload>,
data: AppData,
id: Identity,
) -> ServiceResult<impl Responder> {
let username = id.identity().unwrap();
let stats = Stats::new(&username, &payload.key, &data.db).await?;
let stats = StatsUnixTimestamp::from_stats(&stats);
Ok(HttpResponse::Ok().json(&stats))
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct UserProvidedTrafficPattern {
pub avg_traffic: u32,
pub peak_sustainable_traffic: u32,
pub broke_my_site_traffic: Option<u32>,
pub description: String,
}
impl UserProvidedTrafficPattern {
pub fn calculate(
&self,
strategy: &DefaultDifficultyStrategy,
) -> ServiceResult<Vec<Level>> {
let mut levels = vec![
LevelBuilder::default()
.difficulty_factor(strategy.avg_traffic_difficulty)?
.visitor_threshold(self.avg_traffic)
.build()?,
LevelBuilder::default()
.difficulty_factor(strategy.peak_sustainable_traffic_difficulty)?
.visitor_threshold(self.peak_sustainable_traffic)
.build()?,
];
let mut highest_level = LevelBuilder::default();
highest_level.difficulty_factor(strategy.broke_my_site_traffic_difficulty)?;
match self.broke_my_site_traffic {
Some(broke_my_site_traffic) => {
highest_level.visitor_threshold(broke_my_site_traffic)
}
None => match self
.peak_sustainable_traffic
.checked_add(self.peak_sustainable_traffic / 2)
{
Some(num) => highest_level.visitor_threshold(num),
None => highest_level.visitor_threshold(u32::MAX),
},
};
levels.push(highest_level.build()?);
Ok(levels)
}
}
#[my_codegen::post(
path = "crate::V1_API_ROUTES.mcaptcha.user_provided_traffic_pattern",
wrap = "crate::CheckLogin"
)]
async fn from_user_provided_traffic_pattern(
payload: web::Json<UserProvidedTrafficPattern>,
data: AppData,
id: Identity,
) -> ServiceResult<impl Responder> {
let username = id.identity().unwrap();
let payload = payload.into_inner();
let levels =
payload.calculate(&crate::SETTINGS.captcha.default_difficulty_strategy)?;
let msg = AddLevels {
levels,
duration: crate::SETTINGS.captcha.default_difficulty_strategy.duration,
description: payload.description,
};
let broke_my_site_traffic = match payload.broke_my_site_traffic {
Some(n) => Some(n as i32),
None => None,
};
let mcaptcha_config = add_captcha_runner(&msg, &data, &username).await?;
sqlx::query!(
"INSERT INTO mcaptcha_sitekey_user_provided_avg_traffic (
config_id,
avg_traffic,
peak_sustainable_traffic,
broke_my_site_traffic
) VALUES (
(SELECT config_id FROM mcaptcha_config
WHERE
key = ($1)
AND user_id = (SELECT ID FROM mcaptcha_users WHERE name = $2)
), $3, $4, $5)",
&mcaptcha_config.key,
&username,
payload.avg_traffic as i32,
payload.peak_sustainable_traffic as i32,
broke_my_site_traffic,
)
.execute(&data.db)
.await?;
Ok(HttpResponse::Ok().json(mcaptcha_config))
}
#[cfg(test)]
mod tests {
use actix_web::http::StatusCode;
use actix_web::test;
use super::*;
use crate::api::v1::ROUTES;
use crate::tests::*;
use crate::*;
#[actix_rt::test]
async fn update_and_get_mcaptcha_works() {
const NAME: &str = "updateusermcaptcha";
const PASSWORD: &str = "longpassworddomain";
const EMAIL: &str = "testupdateusermcaptcha@a.com";
{
let data = Data::new().await;
delete_user(NAME, &data).await;
}
register_and_signin(NAME, EMAIL, PASSWORD).await;
let (data, _, signin_resp, token_key) = add_levels_util(NAME, PASSWORD).await;
let cookies = get_cookie!(signin_resp);
let app = get_app!(data).await;
let update_token_resp = test::call_service(
&app,
post_request!(&token_key, ROUTES.mcaptcha.update_key)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(update_token_resp.status(), StatusCode::OK);
let updated_token: MCaptchaDetails =
test::read_body_json(update_token_resp).await;
let get_token_resp = test::call_service(
&app,
post_request!(&updated_token, ROUTES.levels.get)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(get_token_resp.status(), StatusCode::OK);
let paylod = StatsPayload { key: token_key.key };
let get_statis_resp = test::call_service(
&app,
post_request!(&paylod, ROUTES.mcaptcha.stats)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(get_statis_resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn user_provided_traffic_pattern_calculate_works() {
const NAME: &str = "defaultuserconfgworks";
let mut payload = UserProvidedTrafficPattern {
avg_traffic: 100_000,
peak_sustainable_traffic: 1_000_000,
broke_my_site_traffic: Some(10_000_000),
description: NAME.into(),
};
let strategy = &crate::SETTINGS.captcha.default_difficulty_strategy;
let l1 = LevelBuilder::default()
.difficulty_factor(strategy.avg_traffic_difficulty)
.unwrap()
.visitor_threshold(payload.avg_traffic)
.build()
.unwrap();
let l2 = LevelBuilder::default()
.difficulty_factor(strategy.peak_sustainable_traffic_difficulty)
.unwrap()
.visitor_threshold(payload.peak_sustainable_traffic)
.build()
.unwrap();
let l3 = LevelBuilder::default()
.difficulty_factor(strategy.broke_my_site_traffic_difficulty)
.unwrap()
.visitor_threshold(payload.broke_my_site_traffic.unwrap())
.build()
.unwrap();
let levels = vec![l1, l2, l3];
assert_eq!(payload.calculate(strategy).unwrap(), levels);
let estimated_lmax = LevelBuilder::default()
.difficulty_factor(strategy.broke_my_site_traffic_difficulty)
.unwrap()
.visitor_threshold(1500000)
.build()
.unwrap();
payload.broke_my_site_traffic = None;
assert_eq!(
payload.calculate(strategy).unwrap(),
vec![l1, l2, estimated_lmax]
);
let lmax = LevelBuilder::default()
.difficulty_factor(strategy.broke_my_site_traffic_difficulty)
.unwrap()
.visitor_threshold(u32::MAX)
.build()
.unwrap();
let very_large_l2_peak_traffic = u32::MAX - 1;
let very_large_l2 = LevelBuilder::default()
.difficulty_factor(strategy.peak_sustainable_traffic_difficulty)
.unwrap()
.visitor_threshold(very_large_l2_peak_traffic)
.build()
.unwrap();
payload.peak_sustainable_traffic = very_large_l2_peak_traffic;
assert_eq!(
payload.calculate(strategy).unwrap(),
vec![l1, very_large_l2, lmax]
);
}
#[actix_rt::test]
async fn from_user_provided_traffic_pattern_works() {
const NAME: &str = "defaultuserconfgworks";
const PASSWORD: &str = "longpassworddomain";
const EMAIL: &str = "defaultuserconfgworks@a.com";
{
let data = Data::new().await;
delete_user(NAME, &data).await;
}
let (data, _creds, signin_resp) =
register_and_signin(NAME, EMAIL, PASSWORD).await;
let cookies = get_cookie!(signin_resp);
let app = get_app!(data).await;
let payload = UserProvidedTrafficPattern {
avg_traffic: 100_000,
peak_sustainable_traffic: 1_000_000,
broke_my_site_traffic: Some(10_000_000),
description: NAME.into(),
};
let default_levels = payload
.calculate(&crate::SETTINGS.captcha.default_difficulty_strategy)
.unwrap();
let add_token_resp = test::call_service(
&app,
post_request!(&payload, ROUTES.mcaptcha.user_provided_traffic_pattern)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(add_token_resp.status(), StatusCode::OK);
let token_key: MCaptchaDetails = test::read_body_json(add_token_resp).await;
let get_level_resp = test::call_service(
&app,
post_request!(&token_key, ROUTES.levels.get)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(get_level_resp.status(), StatusCode::OK);
let res_levels: Vec<Level> = test::read_body_json(get_level_resp).await;
assert_eq!(res_levels, default_levels);
}
}