tmp22/src/cache/redis.rs

281 lines
8.1 KiB
Rust
Raw Permalink Normal View History

2021-06-09 20:09:54 +05:30
/*
* mCaptcha - A proof of work based DoS protection system
* Copyright © 2021 Aravinth Manivannan <realravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! Cache implementation that uses Redis
use actix::prelude::*;
2021-06-11 12:08:05 +05:30
use tokio::sync::oneshot;
2021-06-09 20:09:54 +05:30
use super::messages::*;
2021-06-09 21:00:29 +05:30
use super::AddChallenge;
2021-06-09 20:09:54 +05:30
use super::Save;
use crate::errors::*;
2021-06-11 12:08:05 +05:30
use crate::redis::mcaptcha_redis::MCaptchaRedis;
use crate::redis::RedisConfig;
2021-06-09 20:09:54 +05:30
2021-06-09 21:00:29 +05:30
pub struct RedisCache(MCaptchaRedis);
2021-06-09 20:09:54 +05:30
impl RedisCache {
2021-06-09 21:00:29 +05:30
pub async fn new(redis: RedisConfig) -> CaptchaResult<Self> {
2021-06-11 12:08:05 +05:30
let redis = MCaptchaRedis::new(redis).await?;
let master = Self(redis);
Ok(master)
2021-06-09 20:09:54 +05:30
}
}
2021-06-11 12:08:05 +05:30
impl Save for RedisCache {}
2021-06-09 20:09:54 +05:30
2021-06-11 12:08:05 +05:30
impl Actor for RedisCache {
2021-06-09 20:09:54 +05:30
type Context = Context<Self>;
}
/// cache a PoWConfig
2021-06-11 12:08:05 +05:30
impl Handler<CachePoW> for RedisCache {
2021-06-09 20:09:54 +05:30
type Result = MessageResult<CachePoW>;
fn handle(&mut self, msg: CachePoW, ctx: &mut Self::Context) -> Self::Result {
2021-06-11 12:08:05 +05:30
let (tx, rx) = oneshot::channel();
let con = self.0.get_client();
let fut = async move {
let payload: AddChallenge = AddChallenge {
challenge: msg.string,
difficulty: msg.difficulty_factor,
duration: msg.duration,
};
let res = con.add_challenge(&msg.key, &payload).await;
tx.send(res).unwrap();
2021-06-09 20:09:54 +05:30
}
.into_actor(self);
2021-06-11 12:08:05 +05:30
ctx.wait(fut);
2021-06-09 20:09:54 +05:30
2021-06-11 12:08:05 +05:30
MessageResult(rx)
2021-06-09 20:09:54 +05:30
}
}
/// Retrive PoW difficulty_factor for a PoW string
2021-06-11 12:08:05 +05:30
impl Handler<RetrivePoW> for RedisCache {
2021-06-09 20:09:54 +05:30
type Result = MessageResult<RetrivePoW>;
2021-06-11 12:08:05 +05:30
fn handle(&mut self, msg: RetrivePoW, ctx: &mut Self::Context) -> Self::Result {
let (tx, rx) = oneshot::channel();
let con = self.0.get_client();
let fut = async move {
let r = match con.get_challenge(&msg.0).await {
Err(e) => Err(e),
Ok(val) => {
let res = CachedPoWConfig {
duration: val.duration,
difficulty_factor: val.difficulty_factor,
key: msg.0.key,
};
Ok(Some(res))
}
};
tx.send(r).unwrap();
}
.into_actor(self);
ctx.wait(fut);
MessageResult(rx)
2021-06-09 20:09:54 +05:30
}
}
/// cache PoW result
2021-06-11 12:08:05 +05:30
impl Handler<CacheResult> for RedisCache {
2021-06-09 20:09:54 +05:30
type Result = MessageResult<CacheResult>;
fn handle(&mut self, msg: CacheResult, ctx: &mut Self::Context) -> Self::Result {
2021-06-11 12:08:05 +05:30
let (tx, rx) = oneshot::channel();
2021-06-09 20:09:54 +05:30
2021-06-11 12:08:05 +05:30
let con = self.0.get_client();
let fut = async move {
let r = con.add_token(&msg).await;
tx.send(r).unwrap();
}
.into_actor(self);
ctx.wait(fut);
MessageResult(rx)
}
}
2021-06-09 20:09:54 +05:30
2021-06-11 12:08:05 +05:30
/// Retrive PoW difficulty_factor for a PoW string
impl Handler<VerifyCaptchaResult> for RedisCache {
type Result = MessageResult<VerifyCaptchaResult>;
fn handle(&mut self, msg: VerifyCaptchaResult, ctx: &mut Self::Context) -> Self::Result {
let (tx, rx) = oneshot::channel();
let con = self.0.get_client();
let fut = async move {
let r = con.get_token(&msg).await;
tx.send(r).unwrap();
2021-06-09 20:09:54 +05:30
}
.into_actor(self);
2021-06-11 12:08:05 +05:30
ctx.wait(fut);
2021-06-09 20:09:54 +05:30
2021-06-11 12:08:05 +05:30
MessageResult(rx)
2021-06-09 20:09:54 +05:30
}
}
/// Delte a PoWConfig
2021-06-11 12:08:05 +05:30
impl Handler<DeleteCaptchaResult> for RedisCache {
2021-06-09 20:09:54 +05:30
type Result = MessageResult<DeleteCaptchaResult>;
2021-06-11 12:08:05 +05:30
fn handle(&mut self, _msg: DeleteCaptchaResult, _ctx: &mut Self::Context) -> Self::Result {
2021-06-09 20:09:54 +05:30
MessageResult(Ok(()))
}
}
2021-06-11 12:08:05 +05:30
/// Delte a PoWConfig
impl Handler<DeletePoW> for RedisCache {
type Result = MessageResult<DeletePoW>;
fn handle(&mut self, _msg: DeletePoW, _ctx: &mut Self::Context) -> Self::Result {
//self.remove_pow_config(&msg.0);
MessageResult(Ok(()))
2021-06-09 20:09:54 +05:30
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
use actix::clock::sleep;
2021-06-11 12:08:05 +05:30
//use crate::master::AddVisitorResult;
//use crate::pow::PoWConfig;
2021-06-09 20:09:54 +05:30
// async fn sleep(time: u64) {
// //use actix::clock::sleep;
// use actix::clock::delay_for;
// use std::time::Duration;
// let duration: Duration = Duration::new(time, 0);
// //sleep(duration).await;
// delay_for(duration).await;
// }
2021-06-11 12:08:05 +05:30
const REDIS_URL: &str = "redis://127.0.1.1/";
2021-06-09 20:09:54 +05:30
#[actix_rt::test]
2021-06-11 12:08:05 +05:30
async fn rediscache_pow_cache_works() {
2021-06-09 20:09:54 +05:30
const DIFFICULTY_FACTOR: u32 = 54;
const DURATION: u64 = 5;
const KEY: &str = "mcaptchakey";
2021-06-11 12:08:05 +05:30
const CHALLENGE: &str = "redischallenge1";
let addr = RedisCache::new(RedisConfig::Single(REDIS_URL.into()))
.await
.unwrap()
.start();
2021-06-09 20:09:54 +05:30
let msg = CachePoWBuilder::default()
2021-06-11 12:08:05 +05:30
.string(CHALLENGE.into())
2021-06-09 20:09:54 +05:30
.difficulty_factor(DIFFICULTY_FACTOR)
2021-06-11 12:08:05 +05:30
.duration(DURATION)
2021-06-09 20:09:54 +05:30
.key(KEY.into())
.build()
.unwrap();
2021-06-11 12:08:05 +05:30
addr.send(msg.clone())
.await
.unwrap()
.await
.unwrap()
.unwrap();
let msg = VerifyCaptchaResult {
token: CHALLENGE.into(),
key: KEY.into(),
};
2021-06-09 20:09:54 +05:30
let cache_difficulty_factor = addr
2021-06-11 12:08:05 +05:30
.send(RetrivePoW(msg.clone()))
.await
.unwrap()
2021-06-09 20:09:54 +05:30
.await
.unwrap()
.unwrap();
assert_eq!(
DIFFICULTY_FACTOR,
cache_difficulty_factor.unwrap().difficulty_factor
);
let duration: Duration = Duration::new(5, 0);
//delay_for(duration + duration).await;
sleep(duration + duration).await;
2021-06-09 20:09:54 +05:30
2021-06-11 12:08:05 +05:30
let expired_string = addr.send(RetrivePoW(msg)).await.unwrap().await.unwrap();
assert!(expired_string.is_err());
2021-06-09 20:09:54 +05:30
}
#[actix_rt::test]
2021-06-11 12:08:05 +05:30
async fn redishashcache_result_cache_works() {
use std::time::Duration;
//use actix::clock::delay_for;
2021-06-09 20:09:54 +05:30
const DURATION: u64 = 5;
const KEY: &str = "a";
const RES: &str = "b";
2021-06-11 12:08:05 +05:30
let addr = RedisCache::new(RedisConfig::Single(REDIS_URL.into()))
.await
.unwrap()
.start();
2021-06-09 20:09:54 +05:30
// send value to cache
// send another value to cache for auto delete
// verify_captcha_result
// delete
// wait for timeout and verify_captcha_result against second value
let add_cache = CacheResult {
key: KEY.into(),
token: RES.into(),
duration: DURATION,
};
2021-06-11 12:08:05 +05:30
addr.send(add_cache).await.unwrap().await.unwrap().unwrap();
2021-06-09 20:09:54 +05:30
let verify_msg = VerifyCaptchaResult {
key: KEY.into(),
token: RES.into(),
};
2021-06-11 12:08:05 +05:30
assert!(addr
.send(verify_msg.clone())
.await
.unwrap()
.await
.unwrap()
.unwrap());
2021-06-09 20:09:54 +05:30
// duplicate
2021-06-11 12:08:05 +05:30
assert!(!addr.send(verify_msg).await.unwrap().await.unwrap().unwrap());
2021-06-09 20:09:54 +05:30
let verify_msg = VerifyCaptchaResult {
key: "cz".into(),
token: RES.into(),
};
2021-06-11 12:08:05 +05:30
assert!(!addr.send(verify_msg).await.unwrap().await.unwrap().unwrap());
2021-06-09 20:09:54 +05:30
let duration: Duration = Duration::new(5, 0);
//delay_for(duration + duration).await;
sleep(duration + duration).await;
2021-06-09 20:09:54 +05:30
let verify_msg = VerifyCaptchaResult {
key: KEY.into(),
token: RES.into(),
};
2021-06-11 12:08:05 +05:30
assert!(!addr.send(verify_msg).await.unwrap().await.unwrap().unwrap());
2021-06-09 20:09:54 +05:30
}
}