it appears actix-web's scope behaviour has changed in the latest beta

release:

Routes 404'd when scope contained trailing slash like so:
let scope = "/api/v1/pow/";
web::scope(scope)//

So had to rm trailing slash in scope
This commit is contained in:
realaravinth 2021-11-29 17:33:08 +05:30
parent f2f8632679
commit b5af9ee259
No known key found for this signature in database
GPG Key ID: AD9F0F08E855ED88
9 changed files with 53 additions and 127 deletions

View File

@ -29,11 +29,11 @@ pub use routes::ROUTES;
pub fn services(cfg: &mut ServiceConfig) { pub fn services(cfg: &mut ServiceConfig) {
meta::services(cfg); meta::services(cfg);
pow::services(cfg);
auth::services(cfg); auth::services(cfg);
account::services(cfg); account::services(cfg);
mcaptcha::services(cfg); mcaptcha::services(cfg);
notifications::services(cfg); notifications::services(cfg);
pow::services(cfg);
} }
#[cfg(test)] #[cfg(test)]

View File

@ -30,12 +30,6 @@ use crate::stats::record::record_fetch;
use crate::AppData; use crate::AppData;
use crate::V1_API_ROUTES; use crate::V1_API_ROUTES;
//#[derive(Clone, Debug, Deserialize, Serialize)]
//pub struct PoWConfig {
// pub name: String,
// pub domain: String,
//}
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetConfigPayload { pub struct GetConfigPayload {
pub key: String, pub key: String,
@ -44,9 +38,7 @@ pub struct GetConfigPayload {
// API keys are mcaptcha actor names // API keys are mcaptcha actor names
/// get PoW configuration for an mcaptcha key /// get PoW configuration for an mcaptcha key
#[my_codegen::post( #[my_codegen::post(path = "V1_API_ROUTES.pow.get_config()")]
path = "V1_API_ROUTES.pow.get_config.strip_prefix(V1_API_ROUTES.pow.scope).unwrap()"
)]
pub async fn get_config( pub async fn get_config(
payload: web::Json<GetConfigPayload>, payload: web::Json<GetConfigPayload>,
data: AppData, data: AppData,
@ -153,20 +145,15 @@ async fn init_mcaptcha(data: &AppData, key: &str) -> ServiceResult<()> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_web::http::StatusCode;
use actix_web::test;
use libmcaptcha::pow::PoWConfig; use libmcaptcha::pow::PoWConfig;
#[actix_rt::test]
async fn get_pow_config_works() {
use super::*; use super::*;
use crate::tests::*; use crate::tests::*;
use crate::*; use crate::*;
use actix_web::test;
#[test]
fn feature() {
actix_rt::System::new().block_on(async move { get_pow_config_works().await });
}
async fn get_pow_config_works() {
const NAME: &str = "powusrworks"; const NAME: &str = "powusrworks";
const PASSWORD: &str = "testingpas"; const PASSWORD: &str = "testingpas";
const EMAIL: &str = "randomuser@a.com"; const EMAIL: &str = "randomuser@a.com";
@ -177,8 +164,7 @@ mod tests {
} }
register_and_signin(NAME, EMAIL, PASSWORD).await; register_and_signin(NAME, EMAIL, PASSWORD).await;
let (data, _, signin_resp, token_key) = add_levels_util(NAME, 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 app = get_app!(data).await;
let get_config_payload = GetConfigPayload { let get_config_payload = GetConfigPayload {
@ -187,10 +173,11 @@ mod tests {
// update and check changes // update and check changes
let url = V1_API_ROUTES.pow.get_config;
println!("{}", &url);
let get_config_resp = test::call_service( let get_config_resp = test::call_service(
&app, &app,
post_request!(&get_config_payload, V1_API_ROUTES.pow.get_config) post_request!(&get_config_payload, V1_API_ROUTES.pow.get_config)
.cookie(cookies.clone())
.to_request(), .to_request(),
) )
.await; .await;

View File

@ -16,7 +16,6 @@
*/ */
use actix_web::web; use actix_web::web;
use actix_web::*;
pub mod get_config; pub mod get_config;
pub mod verify_pow; pub mod verify_pow;
@ -28,13 +27,14 @@ pub use super::mcaptcha::levels::I32Levels;
pub fn services(cfg: &mut web::ServiceConfig) { pub fn services(cfg: &mut web::ServiceConfig) {
let cors = actix_cors::Cors::default() let cors = actix_cors::Cors::default()
.allow_any_origin() .allow_any_origin()
.allowed_methods(vec!["POST"]) .allowed_methods(vec!["POST", "GET"])
.allow_any_header() .allow_any_header()
.max_age(3600) .max_age(3600)
.send_wildcard(); .send_wildcard();
let routes = crate::V1_API_ROUTES.pow;
cfg.service( cfg.service(
Scope::new(crate::V1_API_ROUTES.pow.scope) web::scope(routes.scope)
.wrap(cors) .wrap(cors)
.service(verify_pow::verify_pow) .service(verify_pow::verify_pow)
.service(get_config::get_config) .service(get_config::get_config)
@ -50,9 +50,25 @@ pub mod routes {
pub scope: &'static str, pub scope: &'static str,
} }
macro_rules! rm_scope {
($name:ident) => {
/// remove scope for $name route
pub fn $name(&self) -> &str {
self.$name
//.strip_prefix(&self.scope[..self.scope.len() - 1])
.strip_prefix(self.scope)
.unwrap()
}
};
}
impl PoW { impl PoW {
pub const fn new() -> Self { pub const fn new() -> Self {
let scope = "/api/v1/pow/"; // date: 2021-11-29 16:31
// commit: 6eb75d7
// route 404s when scope contained trailing slash
//let scope = "/api/v1/pow/";
let scope = "/api/v1/pow";
PoW { PoW {
get_config: "/api/v1/pow/config", get_config: "/api/v1/pow/config",
verify_pow: "/api/v1/pow/verify", verify_pow: "/api/v1/pow/verify",
@ -60,35 +76,22 @@ pub mod routes {
scope, scope,
} }
} }
rm_scope!(get_config);
rm_scope!(verify_pow);
rm_scope!(validate_captcha_token);
} }
} }
//#[allow(non_camel_case_types, missing_docs)]
//pub struct post;
//impl actix_web::dev::HttpServiceFactory for post {
// fn register(self, __config: &mut actix_web::dev::AppService) {
// async fn post() -> impl Responder {
// HttpResponse::Ok()
// }
// let __resource = actix_web::Resource::new("/test/post")
// .guard(actix_web::guard::Post())
// .to(post);
// actix_web::dev::HttpServiceFactory::register(__resource, __config)
// }
//}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::routes::PoW;
#[test] #[test]
fn scope_pow_works() { fn scope_pow_works() {
let pow = routes::PoW::new(); let pow = PoW::new();
assert_eq!(pow.get_config.strip_prefix(pow.scope).unwrap(), "config"); assert_eq!(pow.get_config(), "/config");
assert_eq!(pow.verify_pow.strip_prefix(pow.scope).unwrap(), "verify"); assert_eq!(pow.verify_pow(), "/verify");
assert_eq!( assert_eq!(pow.validate_captcha_token(), "/siteverify");
pow.validate_captcha_token.strip_prefix(pow.scope).unwrap(),
"siteverify"
);
} }
} }

View File

@ -36,9 +36,7 @@ pub struct ValidationToken {
/// route handler that verifies PoW and issues a solution token /// route handler that verifies PoW and issues a solution token
/// if verification is successful /// if verification is successful
#[my_codegen::post( #[my_codegen::post(path = "V1_API_ROUTES.pow.verify_pow()")]
path = "V1_API_ROUTES.pow.verify_pow.strip_prefix(V1_API_ROUTES.pow.scope).unwrap()"
)]
pub async fn verify_pow( pub async fn verify_pow(
payload: web::Json<Work>, payload: web::Json<Work>,
data: AppData, data: AppData,

View File

@ -33,9 +33,7 @@ pub struct CaptchaValidateResp {
// API keys are mcaptcha actor names // API keys are mcaptcha actor names
/// route hander that validates a PoW solution token /// route hander that validates a PoW solution token
#[my_codegen::post( #[my_codegen::post(path = "V1_API_ROUTES.pow.validate_captcha_token()")]
path = "V1_API_ROUTES.pow.validate_captcha_token.strip_prefix(V1_API_ROUTES.pow.scope).unwrap()"
)]
pub async fn validate_captcha_token( pub async fn validate_captcha_token(
payload: web::Json<VerifyCaptchaResult>, payload: web::Json<VerifyCaptchaResult>,
data: AppData, data: AppData,

View File

@ -19,10 +19,9 @@ use std::convert::From;
use actix::MailboxError; use actix::MailboxError;
use actix_web::{ use actix_web::{
dev::BaseHttpResponseBuilder as HttpResponseBuilder,
error::ResponseError, error::ResponseError,
http::{header, StatusCode}, http::{header, StatusCode},
HttpResponse, HttpResponse, HttpResponseBuilder,
}; };
use argon2_creds::errors::CredsError; use argon2_creds::errors::CredsError;
use derive_more::{Display, Error}; use derive_more::{Display, Error};

View File

@ -102,8 +102,6 @@ pub type AppData = actix_web::web::Data<Arc<crate::data::Data>>;
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
use std::time::Duration; use std::time::Duration;
use api::v1;
env::set_var("RUST_LOG", "info"); env::set_var("RUST_LOG", "info");
pretty_env_logger::init(); pretty_env_logger::init();
@ -137,11 +135,7 @@ async fn main() -> std::io::Result<()> {
.wrap(actix_middleware::NormalizePath::new( .wrap(actix_middleware::NormalizePath::new(
actix_middleware::TrailingSlash::Trim, actix_middleware::TrailingSlash::Trim,
)) ))
.configure(v1::services) .configure(routes::services)
.configure(docs::services)
.configure(widget::services)
.configure(pages::services)
.configure(static_assets::services)
.app_data(get_json_err()) .app_data(get_json_err())
}) })
.bind(SETTINGS.server.get_ip()) .bind(SETTINGS.server.get_ip())

View File

@ -15,52 +15,10 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#[allow(dead_code)] pub fn services(cfg: &mut actix_web::web::ServiceConfig) {
pub enum Methods { crate::api::v1::services(cfg);
/// GET hander crate::docs::services(cfg);
Get, crate::widget::services(cfg);
/// POST handler crate::pages::services(cfg);
Post, crate::static_assets::services(cfg);
/// Protected GET handler
ProtectGet,
/// Protected POST handler
ProtectPost,
}
/// Defines resoures for [Methods]
#[macro_export]
macro_rules! define_resource {
($cfg:expr, $path:expr, Methods::Get, $to:expr) => {
$cfg.service(
actix_web::web::resource($path)
.guard(actix_web::guard::Get())
.to($to),
);
};
($cfg:expr, $path:expr, Methods::Post, $to:expr) => {
$cfg.service(
actix_web::Resource::new($path)
.guard(actix_web::guard::Post())
.to($to),
);
};
($cfg:expr, $path:expr, Methods::ProtectPost, $to:expr) => {
$cfg.service(
actix_web::web::resource($path)
.wrap(crate::CheckLogin)
.guard(actix_web::guard::Post())
.to($to),
);
};
($cfg:expr, $path:expr, Methods::ProtectGet, $to:expr) => {
$cfg.service(
actix_web::web::resource($path)
.wrap(crate::CheckLogin)
.guard(actix_web::guard::Get())
.to($to),
);
};
} }

View File

@ -40,10 +40,7 @@ macro_rules! post_request {
}; };
($serializable:expr, $uri:expr) => { ($serializable:expr, $uri:expr) => {
test::TestRequest::post() test::TestRequest::post().uri($uri).set_json($serializable)
.uri($uri)
.insert_header((actix_web::http::header::CONTENT_TYPE, "application/json"))
.set_payload(serde_json::to_string($serializable).unwrap())
}; };
} }
@ -66,11 +63,7 @@ macro_rules! get_app {
.wrap(actix_middleware::NormalizePath::new( .wrap(actix_middleware::NormalizePath::new(
actix_middleware::TrailingSlash::Trim, actix_middleware::TrailingSlash::Trim,
)) ))
.configure(crate::api::v1::services) .configure(crate::routes::services),
.configure(crate::widget::services)
.configure(crate::docs::services)
.configure(crate::pages::services)
.configure(crate::static_assets::services),
) )
}; };
($data:expr) => { ($data:expr) => {
@ -80,11 +73,7 @@ macro_rules! get_app {
.wrap(actix_middleware::NormalizePath::new( .wrap(actix_middleware::NormalizePath::new(
actix_middleware::TrailingSlash::Trim, actix_middleware::TrailingSlash::Trim,
)) ))
.configure(crate::api::v1::services) .configure(crate::routes::services)
.configure(crate::widget::services)
.configure(crate::docs::services)
.configure(crate::pages::services)
.configure(crate::static_assets::services)
//.data(std::sync::Arc::new(crate::data::Data::new().await)) //.data(std::sync::Arc::new(crate::data::Data::new().await))
.app_data(actix_web::web::Data::new($data.clone())), .app_data(actix_web::web::Data::new($data.clone())),
) )