domain verification

This commit is contained in:
realaravinth
2021-03-26 22:18:01 +05:30
parent ee548588a8
commit 51764817f9
17 changed files with 623 additions and 108 deletions

View File

@@ -107,11 +107,8 @@ pub async fn signout(id: Identity) -> impl Responder {
// TODO use middleware
pub fn is_authenticated(id: &Identity) -> ServiceResult<()> {
// access request identity
if let Some(_) = id.identity() {
Ok(())
} else {
Err(ServiceError::AuthorizationRequired)
}
id.identity().ok_or(ServiceError::AuthorizationRequired)?;
Ok(())
}
#[post("/api/v1/account/delete")]

View File

@@ -17,10 +17,11 @@
use actix_identity::Identity;
use actix_web::{post, web, HttpResponse, Responder};
use awc::Client;
use serde::{Deserialize, Serialize};
use url::Url;
use super::is_authenticated;
use super::{get_random, is_authenticated};
use crate::errors::*;
use crate::Data;
@@ -37,25 +38,115 @@ pub async fn add_domain(
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let url = Url::parse(&payload.name)?;
if let Some(host) = url.host_str() {
let user = id.identity().unwrap();
let res = sqlx::query!(
"INSERT INTO mcaptcha_domains (name, ID) VALUES
($1, (SELECT ID FROM mcaptcha_users WHERE name = ($2) ));",
host,
user
)
.execute(&data.db)
.await;
match res {
Err(e) => Err(dup_error(e, ServiceError::HostnameTaken)),
Ok(_) => Ok(HttpResponse::Ok()),
}
} else {
Err(ServiceError::NotAUrl)
let host = url.host_str().ok_or(ServiceError::NotAUrl)?;
let user = id.identity().unwrap();
let challenge = get_random(32);
let res = sqlx::query!(
"INSERT INTO mcaptcha_domains_unverified (name, owner_id, verification_challenge) VALUES
($1, (SELECT ID FROM mcaptcha_users WHERE name = ($2) ), $3);",
host,
user,
challenge
)
.execute(&data.db)
.await;
match res {
Err(e) => Err(dup_error(e, ServiceError::HostnameTaken)),
Ok(_) => Ok(HttpResponse::Ok()),
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Challenge {
verification_challenge: String,
}
#[post("/api/v1/mcaptcha/domain/verify/challenge/get")]
pub async fn get_challenge(
payload: web::Json<Domain>,
data: web::Data<Data>,
id: Identity,
client: web::Data<Client>,
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let url = Url::parse(&payload.name)?;
let host = url.host_str().ok_or(ServiceError::NotAUrl).unwrap();
let user = id.identity().unwrap();
let res = sqlx::query_as!(
Challenge,
"SELECT verification_challenge
FROM mcaptcha_domains_unverified where
name = $1 AND owner_id = (SELECT ID from mcaptcha_users where name = $2)",
host,
user,
)
.fetch_one(&data.db)
.await
.unwrap();
Ok(HttpResponse::Ok().json(res))
}
#[post("/api/v1/mcaptcha/domain/verify/challenge/prove")]
pub async fn verify(
payload: web::Json<Domain>,
data: web::Data<Data>,
client: web::Data<Client>,
id: Identity,
) -> ServiceResult<impl Responder> {
use futures::{future::TryFutureExt, try_join};
is_authenticated(&id).unwrap();
//let url = Url::parse(&payload.name).unwrap();
//let host = url.host_str().ok_or(ServiceError::NotAUrl).unwrap();
//let user = id.identity().unwrap();
//let challenge_fut = sqlx::query_as!(
// Challenge,
// "SELECT verification_challenge
// FROM mcaptcha_domains_unverified where
// name = $1 AND owner_id = (SELECT ID from mcaptcha_users where name = $2)",
// &host,
// &user,
//)
//.fetch_one(&data.db)
//.map_err(|e| {
// let r: ServiceError = e.into();
// r
//});
//let res_fut = client.get(host).send().map_err(|e| {
// let r: ServiceError = e.into();
// r
//});
//let (challenge, mut server_res) = try_join!(challenge_fut, res_fut).unwrap();
//let server_resp: Challenge = server_res
// .json()
// .await
// .map_err(|_| return ServiceError::ChallengeCourruption)
// .unwrap();
//if server_resp.verification_challenge == challenge.verification_challenge {
// sqlx::query!(
// "INSERT INTO mcaptcha_domains_verified (name, owner_id) VALUES
// ($1, (SELECT ID from mcaptcha_users WHERE name = $2))",
// &host,
// &user
// )
// .execute(&data.db)
// .await
// .unwrap();
// // TODO delete staging unverified
Ok(HttpResponse::Ok())
//} else {
// Err(ServiceError::ChallengeVerificationFailure)
//}
}
#[post("/api/v1/mcaptcha/domain/delete")]
pub async fn delete_domain(
payload: web::Json<Domain>,
@@ -64,14 +155,14 @@ pub async fn delete_domain(
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let url = Url::parse(&payload.name)?;
if let Some(host) = url.host_str() {
sqlx::query!("DELETE FROM mcaptcha_domains WHERE name = ($1)", host,)
.execute(&data.db)
.await?;
Ok(HttpResponse::Ok())
} else {
Err(ServiceError::NotAUrl)
}
let host = url.host_str().ok_or(ServiceError::NotAUrl)?;
sqlx::query!(
"DELETE FROM mcaptcha_domains_verified WHERE name = ($1)",
host,
)
.execute(&data.db)
.await?;
Ok(HttpResponse::Ok())
}
// Workflow:
@@ -150,4 +241,82 @@ mod tests {
)
.await;
}
#[actix_rt::test]
async fn domain_verification_works() {
use crate::api::v1::tests::*;
use awc::Client;
use std::sync::mpsc;
use std::thread;
const NAME: &str = "testdomainveri";
const PASSWORD: &str = "longpassworddomain";
const EMAIL: &str = "domainverification@a.com";
const DOMAIN: &str = "http://localhost:18001";
const IP: &str = "localhost:18001";
const CHALLENGE_GET: &str = "/api/v1/mcaptcha/domain/verify/challenge/get";
const CHALLENGE_VERIFY: &str = "/api/v1/mcaptcha/domain/verify/challenge/prove";
{
let data = Data::new().await;
delete_user(NAME, &data).await;
}
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
rt::System::new("").block_on(server(IP, tx));
});
let srv = rx.recv().unwrap();
let client = Client::new();
let (data, _, signin_resp) = register_and_signin(NAME, EMAIL, PASSWORD).await;
let cookies = get_cookie!(signin_resp);
let mut app = test::init_service(
App::new()
.wrap(get_identity_service())
.configure(v1_services)
.data(data.clone())
.data(client.clone()),
)
.await;
let domain = Domain {
name: DOMAIN.into(),
};
let add_domain_resp = test::call_service(
&mut app,
post_request!(&domain, "/api/v1/mcaptcha/domain/add")
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(add_domain_resp.status(), StatusCode::OK);
let get_challenge_resp = test::call_service(
&mut app,
post_request!(&domain, CHALLENGE_GET)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(get_challenge_resp.status(), StatusCode::OK);
let challenge: Challenge = test::read_body_json(get_challenge_resp).await;
client
.post(format!("{}/domain_verification_works/", DOMAIN))
.send_json(&challenge)
.await
.unwrap();
let verify_challenge_resp = test::call_service(
&mut app,
post_request!(&domain, CHALLENGE_VERIFY)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(verify_challenge_resp.status(), StatusCode::OK);
srv.stop(true).await;
}
}

View File

@@ -20,7 +20,7 @@ use actix_web::{post, web, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use url::Url;
use super::is_authenticated;
use super::{get_random, is_authenticated};
use crate::errors::*;
use crate::Data;
@@ -46,32 +46,30 @@ pub async fn add_mcaptcha(
let key = get_random(32);
let url = Url::parse(&payload.domain)?;
println!("got req");
if let Some(host) = url.host_str() {
let res = sqlx::query!(
"INSERT INTO mcaptcha_config
let host = url.host_str().ok_or(ServiceError::NotAUrl)?;
let res = sqlx::query!(
"INSERT INTO mcaptcha_config
(name, key, domain_name)
VALUES ($1, $2, (
SELECT name FROM mcaptcha_domains WHERE name = ($3)))",
&payload.name,
&key,
&host,
)
.execute(&data.db)
.await;
SELECT name FROM mcaptcha_domains_verified WHERE name = ($3)))",
&payload.name,
&key,
&host,
)
.execute(&data.db)
.await;
match res {
Err(e) => Err(dup_error(e, ServiceError::TokenNameTaken)),
Ok(_) => {
let resp = MCaptchaDetails {
key,
name: payload.into_inner().name,
};
match res {
Err(e) => Err(dup_error(e, ServiceError::TokenNameTaken)),
Ok(_) => {
let resp = MCaptchaDetails {
key,
name: payload.into_inner().name,
};
Ok(HttpResponse::Ok().json(resp))
}
Ok(HttpResponse::Ok().json(resp))
}
} else {
Err(ServiceError::NotAUrl)
}
}
@@ -91,20 +89,6 @@ pub async fn delete_mcaptcha(
Ok(HttpResponse::Ok())
}
fn get_random(len: usize) -> String {
use std::iter;
use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
let mut rng: ThreadRng = thread_rng();
iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.map(char::from)
.take(len)
.collect::<String>()
}
// Workflow:
// 1. Sign up
// 2. Sign in

View File

@@ -21,3 +21,17 @@ pub mod levels;
pub mod mcaptcha;
pub use super::auth::is_authenticated;
pub fn get_random(len: usize) -> String {
use std::iter;
use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
let mut rng: ThreadRng = thread_rng();
iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.map(char::from)
.take(len)
.collect::<String>()
}

View File

@@ -32,6 +32,8 @@ pub fn services(cfg: &mut ServiceConfig) {
// domain
cfg.service(mcaptcha::domains::add_domain);
cfg.service(mcaptcha::domains::delete_domain);
cfg.service(mcaptcha::domains::verify);
cfg.service(mcaptcha::domains::get_challenge);
// mcaptcha
cfg.service(mcaptcha::mcaptcha::add_mcaptcha);

View File

@@ -0,0 +1,94 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@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 <https://www.gnu.org/licenses/>.
*/
use log::info;
use std::collections::HashMap;
use std::env;
use std::sync::mpsc;
use std::sync::{Arc, RwLock};
use actix_web::{dev::Server, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
// from
// use crate::api::v1::mcaptcha::domains::Challenge;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Challenge {
verification_challenge: String,
}
#[cfg(not(tarpaulin_include))]
#[actix_web::main]
async fn main() {
pretty_env_logger::init();
let mut confif = env::args();
confif.next();
let port = confif.next().unwrap();
HttpServer::new(move || {
let store: UtilKVServer = Arc::new(RwLock::new(HashMap::new()));
App::new()
.data(store)
.route("/{key}/", web::post().to(util_server_add))
.route("/{key}/", web::get().to(util_server_retrive))
})
.bind(format!("localhost:{}", port))
.unwrap()
.run()
.await
.unwrap();
}
pub async fn server(ip: &str, tx: mpsc::Sender<Server>) {
pretty_env_logger::init();
let srv = HttpServer::new(move || {
let store: UtilKVServer = Arc::new(RwLock::new(HashMap::new()));
App::new()
.data(store)
.route("/{key}/", web::post().to(util_server_add))
.route("/{key}/", web::get().to(util_server_retrive))
})
.bind(ip)
.unwrap()
.run();
tx.send(srv.clone());
}
type UtilKVServer = Arc<RwLock<HashMap<String, Challenge>>>;
#[cfg(not(tarpaulin_include))]
async fn util_server_retrive(
key: web::Path<String>,
data: web::Data<UtilKVServer>,
) -> impl Responder {
let key = key.into_inner();
let store = data.read().unwrap();
let resp = store.get(&key).unwrap();
info!("key :{}, value: {:?}", key, resp);
HttpResponse::Ok().json(resp)
}
#[cfg(not(tarpaulin_include))]
async fn util_server_add(
key: web::Path<String>,
payload: web::Json<Challenge>,
data: web::Data<UtilKVServer>,
) -> impl Responder {
info!("key :{}, value: {:?}", key, payload);
let mut store = data.write().unwrap();
store.insert(key.into_inner(), payload.into_inner());
HttpResponse::Ok()
}

View File

@@ -16,3 +16,6 @@
*/
mod auth;
mod kvserver;
pub use kvserver::server;