server: refactor auth_service to use Results

This simplifies the flow, and gets rid of wrong clippy warnings about
missing awaits due to the instrumentation.
This commit is contained in:
Valentin Tolmer 2022-06-30 15:51:56 +02:00 committed by nitnelave
parent 23a4763914
commit 1a03346a38
5 changed files with 278 additions and 259 deletions

View File

@ -601,24 +601,6 @@ mod tests {
.collect::<Vec<_>>() .collect::<Vec<_>>()
} }
#[tokio::test]
async fn test_bind_admin() {
let sql_pool = get_in_memory_db().await;
let config = ConfigurationBuilder::default()
.ldap_user_dn(UserId::new("admin"))
.ldap_user_pass(secstr::SecUtf8::from("test"))
.build()
.unwrap();
let handler = SqlBackendHandler::new(config, sql_pool);
handler
.bind(BindRequest {
name: UserId::new("admin"),
password: "test".to_string(),
})
.await
.unwrap();
}
#[tokio::test] #[tokio::test]
async fn test_bind_user() { async fn test_bind_user() {
let sql_pool = get_initialized_db().await; let sql_pool = get_initialized_db().await;

View File

@ -90,17 +90,6 @@ impl SqlBackendHandler {
impl LoginHandler for SqlBackendHandler { impl LoginHandler for SqlBackendHandler {
#[instrument(skip_all, level = "debug", err)] #[instrument(skip_all, level = "debug", err)]
async fn bind(&self, request: BindRequest) -> Result<()> { async fn bind(&self, request: BindRequest) -> Result<()> {
if request.name == self.config.ldap_user_dn {
if SecUtf8::from(request.password) == self.config.ldap_user_pass {
return Ok(());
} else {
debug!(r#"Invalid password for LDAP bind user"#);
return Err(DomainError::AuthenticationError(format!(
" for user '{}'",
request.name
)));
}
}
let (query, values) = Query::select() let (query, values) = Query::select()
.column(Users::PasswordHash) .column(Users::PasswordHash)
.from(Users::Table) .from(Users::Table)

View File

@ -13,14 +13,14 @@ use actix_web_httpauth::extractors::bearer::BearerAuth;
use anyhow::Result; use anyhow::Result;
use chrono::prelude::*; use chrono::prelude::*;
use futures::future::{ok, Ready}; use futures::future::{ok, Ready};
use futures_util::{FutureExt, TryFutureExt}; use futures_util::FutureExt;
use hmac::Hmac; use hmac::Hmac;
use jwt::{SignWithKey, VerifyWithKey}; use jwt::{SignWithKey, VerifyWithKey};
use sha2::Sha512; use sha2::Sha512;
use time::ext::NumericalDuration; use time::ext::NumericalDuration;
use tracing::{debug, instrument, warn}; use tracing::{debug, instrument, warn};
use lldap_auth::{login, opaque, password_reset, registration, JWTClaims}; use lldap_auth::{login, password_reset, registration, JWTClaims};
use crate::{ use crate::{
domain::{ domain::{
@ -30,7 +30,7 @@ use crate::{
}, },
infra::{ infra::{
tcp_backend_handler::*, tcp_backend_handler::*,
tcp_server::{error_to_http_response, AppState}, tcp_server::{error_to_http_response, AppState, TcpError, TcpResult},
}, },
}; };
@ -51,9 +51,9 @@ fn create_jwt(key: &Hmac<Sha512>, user: String, groups: HashSet<GroupIdAndName>)
jwt::Token::new(header, claims).sign_with_key(key).unwrap() jwt::Token::new(header, claims).sign_with_key(key).unwrap()
} }
fn parse_refresh_token(token: &str) -> std::result::Result<(u64, UserId), HttpResponse> { fn parse_refresh_token(token: &str) -> TcpResult<(u64, UserId)> {
match token.split_once('+') { match token.split_once('+') {
None => Err(HttpResponse::Unauthorized().body("Invalid refresh token")), None => Err(DomainError::AuthenticationError("Invalid refresh token".to_string()).into()),
Some((token, u)) => { Some((token, u)) => {
let refresh_token_hash = { let refresh_token_hash = {
let mut s = DefaultHasher::new(); let mut s = DefaultHasher::new();
@ -65,14 +65,16 @@ fn parse_refresh_token(token: &str) -> std::result::Result<(u64, UserId), HttpRe
} }
} }
fn get_refresh_token(request: HttpRequest) -> std::result::Result<(u64, UserId), HttpResponse> { fn get_refresh_token(request: HttpRequest) -> TcpResult<(u64, UserId)> {
match ( match (
request.cookie("refresh_token"), request.cookie("refresh_token"),
request.headers().get("refresh-token"), request.headers().get("refresh-token"),
) { ) {
(Some(c), _) => parse_refresh_token(c.value()), (Some(c), _) => parse_refresh_token(c.value()),
(_, Some(t)) => parse_refresh_token(t.to_str().unwrap()), (_, Some(t)) => parse_refresh_token(t.to_str().unwrap()),
(None, None) => Err(HttpResponse::Unauthorized().body("Missing refresh token")), (None, None) => {
Err(DomainError::AuthenticationError("Missing refresh token".to_string()).into())
}
} }
} }
@ -80,68 +82,75 @@ fn get_refresh_token(request: HttpRequest) -> std::result::Result<(u64, UserId),
async fn get_refresh<Backend>( async fn get_refresh<Backend>(
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
request: HttpRequest, request: HttpRequest,
) -> HttpResponse ) -> TcpResult<HttpResponse>
where where
Backend: TcpBackendHandler + BackendHandler + 'static, Backend: TcpBackendHandler + BackendHandler + 'static,
{ {
let backend_handler = &data.backend_handler; let backend_handler = &data.backend_handler;
let jwt_key = &data.jwt_key; let jwt_key = &data.jwt_key;
let (refresh_token_hash, user) = match get_refresh_token(request) { let (refresh_token_hash, user) = get_refresh_token(request)?;
Ok(t) => t, let found = data
Err(http_response) => return http_response,
};
let res_found = data
.backend_handler .backend_handler
.check_token(refresh_token_hash, &user) .check_token(refresh_token_hash, &user)
.await; .await?;
// Async closures are not supported yet. if !found {
match res_found { return Err(TcpError::DomainError(DomainError::AuthenticationError(
Ok(true) => backend_handler.get_user_groups(&user).await,
Ok(false) => Err(DomainError::AuthenticationError(
"Invalid refresh token".to_string(), "Invalid refresh token".to_string(),
)), )));
Err(e) => Err(e),
} }
.map(|groups| create_jwt(jwt_key, user.to_string(), groups)) Ok(backend_handler
.map(|token| { .get_user_groups(&user)
HttpResponse::Ok() .await
.cookie( .map(|groups| create_jwt(jwt_key, user.to_string(), groups))
Cookie::build("token", token.as_str()) .map(|token| {
.max_age(1.days()) HttpResponse::Ok()
.path("/") .cookie(
.http_only(true) Cookie::build("token", token.as_str())
.same_site(SameSite::Strict) .max_age(1.days())
.finish(), .path("/")
) .http_only(true)
.json(&login::ServerLoginResponse { .same_site(SameSite::Strict)
token: token.as_str().to_owned(), .finish(),
refresh_token: None, )
}) .json(&login::ServerLoginResponse {
}) token: token.as_str().to_owned(),
.unwrap_or_else(error_to_http_response) refresh_token: None,
})
})?)
} }
#[instrument(skip_all, level = "debug")] async fn get_refresh_handler<Backend>(
async fn get_password_reset_step1<Backend>(
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
request: HttpRequest, request: HttpRequest,
) -> HttpResponse ) -> HttpResponse
where
Backend: TcpBackendHandler + BackendHandler + 'static,
{
get_refresh(data, request)
.await
.unwrap_or_else(error_to_http_response)
}
#[instrument(skip_all, level = "debug")]
async fn get_password_reset_step1<Backend>(
data: web::Data<AppState<Backend>>,
request: HttpRequest,
) -> TcpResult<()>
where where
Backend: TcpBackendHandler + BackendHandler + 'static, Backend: TcpBackendHandler + BackendHandler + 'static,
{ {
let user_id = match request.match_info().get("user_id") { let user_id = match request.match_info().get("user_id") {
None => return HttpResponse::BadRequest().body("Missing user ID"), None => return Err(TcpError::BadRequest("Missing user ID".to_string())),
Some(id) => UserId::new(id), Some(id) => UserId::new(id),
}; };
let token = match data.backend_handler.start_password_reset(&user_id).await { let token = match data.backend_handler.start_password_reset(&user_id).await? {
Err(e) => return HttpResponse::InternalServerError().body(e.to_string()), None => return Ok(()),
Ok(None) => return HttpResponse::Ok().finish(), Some(token) => token,
Ok(Some(token)) => token,
}; };
let user = match data.backend_handler.get_user_details(&user_id).await { let user = match data.backend_handler.get_user_details(&user_id).await {
Err(e) => { Err(e) => {
warn!("Error getting used details: {:#?}", e); warn!("Error getting used details: {:#?}", e);
return HttpResponse::Ok().finish(); return Ok(());
} }
Ok(u) => u, Ok(u) => u,
}; };
@ -153,38 +162,50 @@ where
&data.mail_options, &data.mail_options,
) { ) {
warn!("Error sending email: {:#?}", e); warn!("Error sending email: {:#?}", e);
return HttpResponse::InternalServerError().body(format!("Could not send email: {}", e)); return Err(TcpError::InternalServerError(format!(
"Could not send email: {}",
e
)));
} }
HttpResponse::Ok().finish() Ok(())
} }
#[instrument(skip_all, level = "debug")] async fn get_password_reset_step1_handler<Backend>(
async fn get_password_reset_step2<Backend>(
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
request: HttpRequest, request: HttpRequest,
) -> HttpResponse ) -> HttpResponse
where where
Backend: TcpBackendHandler + BackendHandler + 'static, Backend: TcpBackendHandler + BackendHandler + 'static,
{ {
let token = match request.match_info().get("token") { get_password_reset_step1(data, request)
None => return HttpResponse::BadRequest().body("Missing token"), .await
Some(token) => token, .map(|()| HttpResponse::Ok().finish())
}; .unwrap_or_else(error_to_http_response)
let user_id = match data }
#[instrument(skip_all, level = "debug")]
async fn get_password_reset_step2<Backend>(
data: web::Data<AppState<Backend>>,
request: HttpRequest,
) -> TcpResult<HttpResponse>
where
Backend: TcpBackendHandler + BackendHandler + 'static,
{
let token = request
.match_info()
.get("token")
.ok_or_else(|| TcpError::BadRequest("Missing reset token".to_string()))?;
let user_id = data
.backend_handler .backend_handler
.get_user_id_for_password_reset_token(token) .get_user_id_for_password_reset_token(token)
.await .await?;
{
Err(_) => return HttpResponse::Unauthorized().body("Invalid or expired token"),
Ok(user_id) => user_id,
};
let _ = data let _ = data
.backend_handler .backend_handler
.delete_password_reset_token(token) .delete_password_reset_token(token)
.await; .await;
let groups = HashSet::new(); let groups = HashSet::new();
let token = create_jwt(&data.jwt_key, user_id.to_string(), groups); let token = create_jwt(&data.jwt_key, user_id.to_string(), groups);
HttpResponse::Ok() Ok(HttpResponse::Ok()
.cookie( .cookie(
Cookie::build("token", token.as_str()) Cookie::build("token", token.as_str())
.max_age(5.minutes()) .max_age(5.minutes())
@ -197,44 +218,39 @@ where
.json(&password_reset::ServerPasswordResetResponse { .json(&password_reset::ServerPasswordResetResponse {
user_id: user_id.to_string(), user_id: user_id.to_string(),
token: token.as_str().to_owned(), token: token.as_str().to_owned(),
}) }))
} }
#[instrument(skip_all, level = "debug")] async fn get_password_reset_step2_handler<Backend>(
async fn get_logout<Backend>(
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
request: HttpRequest, request: HttpRequest,
) -> HttpResponse ) -> HttpResponse
where where
Backend: TcpBackendHandler + BackendHandler + 'static, Backend: TcpBackendHandler + BackendHandler + 'static,
{ {
let (refresh_token_hash, user) = match get_refresh_token(request) { get_password_reset_step2(data, request)
Ok(t) => t, .await
Err(http_response) => return http_response, .unwrap_or_else(error_to_http_response)
}; }
if let Err(response) = data
.backend_handler #[instrument(skip_all, level = "debug")]
async fn get_logout<Backend>(
data: web::Data<AppState<Backend>>,
request: HttpRequest,
) -> TcpResult<HttpResponse>
where
Backend: TcpBackendHandler + BackendHandler + 'static,
{
let (refresh_token_hash, user) = get_refresh_token(request)?;
data.backend_handler
.delete_refresh_token(refresh_token_hash) .delete_refresh_token(refresh_token_hash)
.map_err(error_to_http_response) .await?;
.await let new_blacklisted_jwts = data.backend_handler.blacklist_jwts(&user).await?;
{ let mut jwt_blacklist = data.jwt_blacklist.write().unwrap();
return response; for jwt in new_blacklisted_jwts {
}; jwt_blacklist.insert(jwt);
match data }
.backend_handler Ok(HttpResponse::Ok()
.blacklist_jwts(&user)
.map_err(error_to_http_response)
.await
{
Ok(new_blacklisted_jwts) => {
let mut jwt_blacklist = data.jwt_blacklist.write().unwrap();
for jwt in new_blacklisted_jwts {
jwt_blacklist.insert(jwt);
}
}
Err(response) => return response,
};
HttpResponse::Ok()
.cookie( .cookie(
Cookie::build("token", "") Cookie::build("token", "")
.max_age(0.days()) .max_age(0.days())
@ -251,11 +267,23 @@ where
.same_site(SameSite::Strict) .same_site(SameSite::Strict)
.finish(), .finish(),
) )
.finish() .finish())
} }
pub(crate) fn error_to_api_response<T>(error: DomainError) -> ApiResult<T> { async fn get_logout_handler<Backend>(
ApiResult::Right(error_to_http_response(error)) data: web::Data<AppState<Backend>>,
request: HttpRequest,
) -> HttpResponse
where
Backend: TcpBackendHandler + BackendHandler + 'static,
{
get_logout(data, request)
.await
.unwrap_or_else(error_to_http_response)
}
pub(crate) fn error_to_api_response<T, E: Into<TcpError>>(error: E) -> ApiResult<T> {
ApiResult::Right(error_to_http_response(error.into()))
} }
pub type ApiResult<M> = actix_web::Either<web::Json<M>, HttpResponse>; pub type ApiResult<M> = actix_web::Either<web::Json<M>, HttpResponse>;
@ -279,178 +307,168 @@ where
async fn get_login_successful_response<Backend>( async fn get_login_successful_response<Backend>(
data: &web::Data<AppState<Backend>>, data: &web::Data<AppState<Backend>>,
name: &UserId, name: &UserId,
) -> HttpResponse ) -> TcpResult<HttpResponse>
where where
Backend: TcpBackendHandler + BackendHandler, Backend: TcpBackendHandler + BackendHandler,
{ {
// The authentication was successful, we need to fetch the groups to create the JWT // The authentication was successful, we need to fetch the groups to create the JWT
// token. // token.
data.backend_handler let groups = data.backend_handler.get_user_groups(name).await?;
.get_user_groups(name) let (refresh_token, max_age) = data.backend_handler.create_refresh_token(name).await?;
.and_then(|g| async { Ok((g, data.backend_handler.create_refresh_token(name).await?)) }) let token = create_jwt(&data.jwt_key, name.to_string(), groups);
.await let refresh_token_plus_name = refresh_token + "+" + name.as_str();
.map(|(groups, (refresh_token, max_age))| {
let token = create_jwt(&data.jwt_key, name.to_string(), groups);
let refresh_token_plus_name = refresh_token + "+" + name.as_str();
HttpResponse::Ok() Ok(HttpResponse::Ok()
.cookie( .cookie(
Cookie::build("token", token.as_str()) Cookie::build("token", token.as_str())
.max_age(1.days()) .max_age(1.days())
.path("/") .path("/")
.http_only(true) .http_only(true)
.same_site(SameSite::Strict) .same_site(SameSite::Strict)
.finish(), .finish(),
) )
.cookie( .cookie(
Cookie::build("refresh_token", refresh_token_plus_name.clone()) Cookie::build("refresh_token", refresh_token_plus_name.clone())
.max_age(max_age.num_days().days()) .max_age(max_age.num_days().days())
.path("/auth") .path("/auth")
.http_only(true) .http_only(true)
.same_site(SameSite::Strict) .same_site(SameSite::Strict)
.finish(), .finish(),
) )
.json(&login::ServerLoginResponse { .json(&login::ServerLoginResponse {
token: token.as_str().to_owned(), token: token.as_str().to_owned(),
refresh_token: Some(refresh_token_plus_name), refresh_token: Some(refresh_token_plus_name),
}) }))
})
.unwrap_or_else(error_to_http_response)
} }
#[instrument(skip_all, level = "debug")] #[instrument(skip_all, level = "debug")]
async fn opaque_login_finish<Backend>( async fn opaque_login_finish<Backend>(
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
request: web::Json<login::ClientLoginFinishRequest>, request: web::Json<login::ClientLoginFinishRequest>,
) -> TcpResult<HttpResponse>
where
Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static,
{
let name = data
.backend_handler
.login_finish(request.into_inner())
.await?;
get_login_successful_response(&data, &name).await
}
async fn opaque_login_finish_handler<Backend>(
data: web::Data<AppState<Backend>>,
request: web::Json<login::ClientLoginFinishRequest>,
) -> HttpResponse ) -> HttpResponse
where where
Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static, Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static,
{ {
let name = match data opaque_login_finish(data, request)
.backend_handler
.login_finish(request.into_inner())
.await .await
{ .unwrap_or_else(error_to_http_response)
Ok(n) => n,
Err(e) => return error_to_http_response(e),
};
get_login_successful_response(&data, &name).await
} }
#[instrument(skip_all, level = "debug")] #[instrument(skip_all, level = "debug")]
async fn simple_login<Backend>( async fn simple_login<Backend>(
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
request: web::Json<login::ClientSimpleLoginRequest>, request: web::Json<login::ClientSimpleLoginRequest>,
) -> TcpResult<HttpResponse>
where
Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + LoginHandler + 'static,
{
let user_id = UserId::new(&request.username);
let bind_request = BindRequest {
name: user_id.clone(),
password: request.password.clone(),
};
data.backend_handler.bind(bind_request).await?;
get_login_successful_response(&data, &user_id).await
}
async fn simple_login_handler<Backend>(
data: web::Data<AppState<Backend>>,
request: web::Json<login::ClientSimpleLoginRequest>,
) -> HttpResponse ) -> HttpResponse
where where
Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static, Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + LoginHandler + 'static,
{ {
let password = &request.password; simple_login(data, request)
let mut rng = rand::rngs::OsRng; .await
let opaque::client::login::ClientLoginStartResult { state, message } = .unwrap_or_else(error_to_http_response)
match opaque::client::login::start_login(password, &mut rng) {
Ok(n) => n,
Err(e) => {
return HttpResponse::InternalServerError()
.body(format!("Internal Server Error: {:#?}", e))
}
};
let username = request.username.clone();
let start_request = login::ClientLoginStartRequest {
username: username.clone(),
login_start_request: message,
};
let start_response = match data.backend_handler.login_start(start_request).await {
Ok(n) => n,
Err(e) => return error_to_http_response(e),
};
let login_finish =
match opaque::client::login::finish_login(state, start_response.credential_response) {
Err(_) => {
return error_to_http_response(DomainError::AuthenticationError(String::from(
"Invalid username or password",
)))
}
Ok(l) => l,
};
let finish_request = login::ClientLoginFinishRequest {
server_data: start_response.server_data,
credential_finalization: login_finish.message,
};
let name = match data.backend_handler.login_finish(finish_request).await {
Ok(n) => n,
Err(e) => return error_to_http_response(e),
};
get_login_successful_response(&data, &name).await
} }
#[instrument(skip_all, level = "debug")] #[instrument(skip_all, level = "debug")]
async fn post_authorize<Backend>( async fn post_authorize<Backend>(
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
request: web::Json<BindRequest>, request: web::Json<BindRequest>,
) -> HttpResponse ) -> TcpResult<HttpResponse>
where where
Backend: TcpBackendHandler + BackendHandler + LoginHandler + 'static, Backend: TcpBackendHandler + BackendHandler + LoginHandler + 'static,
{ {
let name = request.name.clone(); let name = request.name.clone();
debug!(%name); debug!(%name);
if let Err(e) = data.backend_handler.bind(request.into_inner()).await { data.backend_handler.bind(request.into_inner()).await?;
return error_to_http_response(e);
}
get_login_successful_response(&data, &name).await get_login_successful_response(&data, &name).await
} }
async fn post_authorize_handler<Backend>(
data: web::Data<AppState<Backend>>,
request: web::Json<BindRequest>,
) -> HttpResponse
where
Backend: TcpBackendHandler + BackendHandler + LoginHandler + 'static,
{
post_authorize(data, request)
.await
.unwrap_or_else(error_to_http_response)
}
#[instrument(skip_all, level = "debug")] #[instrument(skip_all, level = "debug")]
async fn opaque_register_start<Backend>( async fn opaque_register_start<Backend>(
request: actix_web::HttpRequest, request: actix_web::HttpRequest,
mut payload: actix_web::web::Payload, mut payload: actix_web::web::Payload,
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
) -> ApiResult<registration::ServerRegistrationStartResponse> ) -> TcpResult<registration::ServerRegistrationStartResponse>
where where
Backend: OpaqueHandler + 'static, Backend: OpaqueHandler + 'static,
{ {
use actix_web::FromRequest; use actix_web::FromRequest;
let validation_result = match BearerAuth::from_request(&request, &mut payload.0) let validation_result = BearerAuth::from_request(&request, &mut payload.0)
.await .await
.ok() .ok()
.and_then(|bearer| check_if_token_is_valid(&data, bearer.token()).ok()) .and_then(|bearer| check_if_token_is_valid(&data, bearer.token()).ok())
{ .ok_or_else(|| {
Some(t) => t, TcpError::UnauthorizedError("Not authorized to change the user's password".to_string())
None => { })?;
return ApiResult::Right(
HttpResponse::Unauthorized().body("Not authorized to change the user's password"),
)
}
};
let registration_start_request = let registration_start_request =
match web::Json::<registration::ClientRegistrationStartRequest>::from_request( web::Json::<registration::ClientRegistrationStartRequest>::from_request(
&request, &request,
&mut payload.0, &mut payload.0,
) )
.await .await
{ .map_err(|e| TcpError::BadRequest(format!("{:#?}", e)))?
Ok(r) => r,
Err(e) => {
return ApiResult::Right(
HttpResponse::BadRequest().body(format!("Bad request: {:#?}", e)),
)
}
}
.into_inner(); .into_inner();
let user_id = &registration_start_request.username; let user_id = &registration_start_request.username;
if !validation_result.can_write(user_id) { if !validation_result.can_write(user_id) {
return ApiResult::Right( return Err(TcpError::UnauthorizedError(
HttpResponse::Unauthorized().body("Not authorized to change the user's password"), "Not authorized to change the user's password".to_string(),
); ));
} }
data.backend_handler Ok(data
.backend_handler
.registration_start(registration_start_request) .registration_start(registration_start_request)
.await?)
}
async fn opaque_register_start_handler<Backend>(
request: actix_web::HttpRequest,
payload: actix_web::web::Payload,
data: web::Data<AppState<Backend>>,
) -> ApiResult<registration::ServerRegistrationStartResponse>
where
Backend: OpaqueHandler + 'static,
{
opaque_register_start(request, payload, data)
.await .await
.map(|res| ApiResult::Left(web::Json(res))) .map(|res| ApiResult::Left(web::Json(res)))
.unwrap_or_else(error_to_api_response) .unwrap_or_else(error_to_api_response)
@ -460,18 +478,26 @@ where
async fn opaque_register_finish<Backend>( async fn opaque_register_finish<Backend>(
data: web::Data<AppState<Backend>>, data: web::Data<AppState<Backend>>,
request: web::Json<registration::ClientRegistrationFinishRequest>, request: web::Json<registration::ClientRegistrationFinishRequest>,
) -> TcpResult<HttpResponse>
where
Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static,
{
data.backend_handler
.registration_finish(request.into_inner())
.await?;
Ok(HttpResponse::Ok().finish())
}
async fn opaque_register_finish_handler<Backend>(
data: web::Data<AppState<Backend>>,
request: web::Json<registration::ClientRegistrationFinishRequest>,
) -> HttpResponse ) -> HttpResponse
where where
Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static, Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static,
{ {
if let Err(e) = data opaque_register_finish(data, request)
.backend_handler
.registration_finish(request.into_inner())
.await .await
{ .unwrap_or_else(error_to_http_response)
return error_to_http_response(e);
}
HttpResponse::Ok().finish()
} }
pub struct CookieToHeaderTranslatorFactory; pub struct CookieToHeaderTranslatorFactory;
@ -616,35 +642,38 @@ pub fn configure_server<Backend>(cfg: &mut web::ServiceConfig)
where where
Backend: TcpBackendHandler + LoginHandler + OpaqueHandler + BackendHandler + 'static, Backend: TcpBackendHandler + LoginHandler + OpaqueHandler + BackendHandler + 'static,
{ {
cfg.service(web::resource("").route(web::post().to(post_authorize::<Backend>))) cfg.service(web::resource("").route(web::post().to(post_authorize_handler::<Backend>)))
.service( .service(
web::resource("/opaque/login/start") web::resource("/opaque/login/start")
.route(web::post().to(opaque_login_start::<Backend>)), .route(web::post().to(opaque_login_start::<Backend>)),
) )
.service( .service(
web::resource("/opaque/login/finish") web::resource("/opaque/login/finish")
.route(web::post().to(opaque_login_finish::<Backend>)), .route(web::post().to(opaque_login_finish_handler::<Backend>)),
) )
.service(web::resource("/simple/login").route(web::post().to(simple_login::<Backend>))) .service(
.service(web::resource("/refresh").route(web::get().to(get_refresh::<Backend>))) web::resource("/simple/login").route(web::post().to(simple_login_handler::<Backend>)),
)
.service(web::resource("/refresh").route(web::get().to(get_refresh_handler::<Backend>)))
.service( .service(
web::resource("/reset/step1/{user_id}") web::resource("/reset/step1/{user_id}")
.route(web::get().to(get_password_reset_step1::<Backend>)), .route(web::get().to(get_password_reset_step1_handler::<Backend>)),
) )
.service( .service(
web::resource("/reset/step2/{token}") web::resource("/reset/step2/{token}")
.route(web::get().to(get_password_reset_step2::<Backend>)), .route(web::get().to(get_password_reset_step2_handler::<Backend>)),
) )
.service(web::resource("/logout").route(web::get().to(get_logout::<Backend>))) .service(web::resource("/logout").route(web::get().to(get_logout_handler::<Backend>)))
.service( .service(
web::scope("/opaque/register") web::scope("/opaque/register")
.wrap(CookieToHeaderTranslatorFactory) .wrap(CookieToHeaderTranslatorFactory)
.service( .service(
web::resource("/start").route(web::post().to(opaque_register_start::<Backend>)), web::resource("/start")
.route(web::post().to(opaque_register_start_handler::<Backend>)),
) )
.service( .service(
web::resource("/finish") web::resource("/finish")
.route(web::post().to(opaque_register_finish::<Backend>)), .route(web::post().to(opaque_register_finish_handler::<Backend>)),
), ),
); );
} }

View File

@ -894,7 +894,7 @@ impl<Backend: BackendHandler + LoginHandler + OpaqueHandler> LdapHandler<Backend
.collect::<Result<_>>()?, .collect::<Result<_>>()?,
)), )),
LdapFilter::Not(filter) => Ok(GroupRequestFilter::Not(Box::new( LdapFilter::Not(filter) => Ok(GroupRequestFilter::Not(Box::new(
self.convert_group_filter(&*filter)?, self.convert_group_filter(filter)?,
))), ))),
LdapFilter::Present(field) => { LdapFilter::Present(field) => {
if ALL_GROUP_ATTRIBUTE_KEYS.contains(&field.to_ascii_lowercase().as_str()) { if ALL_GROUP_ATTRIBUTE_KEYS.contains(&field.to_ascii_lowercase().as_str()) {
@ -924,7 +924,7 @@ impl<Backend: BackendHandler + LoginHandler + OpaqueHandler> LdapHandler<Backend
.collect::<Result<_>>()?, .collect::<Result<_>>()?,
)), )),
LdapFilter::Not(filter) => Ok(UserRequestFilter::Not(Box::new( LdapFilter::Not(filter) => Ok(UserRequestFilter::Not(Box::new(
self.convert_user_filter(&*filter)?, self.convert_user_filter(filter)?,
))), ))),
LdapFilter::Equality(field, value) => { LdapFilter::Equality(field, value) => {
let field = &field.to_ascii_lowercase(); let field = &field.to_ascii_lowercase();

View File

@ -31,17 +31,36 @@ async fn index() -> actix_web::Result<NamedFile> {
Ok(NamedFile::open(path)?) Ok(NamedFile::open(path)?)
} }
pub(crate) fn error_to_http_response(error: DomainError) -> HttpResponse { #[derive(thiserror::Error, Debug)]
pub enum TcpError {
#[error("`{0}`")]
DomainError(#[from] DomainError),
#[error("Bad request: `{0}`")]
BadRequest(String),
#[error("Internal server error: `{0}`")]
InternalServerError(String),
#[error("Unauthorized: `{0}`")]
UnauthorizedError(String),
}
pub type TcpResult<T> = std::result::Result<T, TcpError>;
pub(crate) fn error_to_http_response(error: TcpError) -> HttpResponse {
match error { match error {
DomainError::AuthenticationError(_) | DomainError::AuthenticationProtocolError(_) => { TcpError::DomainError(ref de) => match de {
HttpResponse::Unauthorized() DomainError::AuthenticationError(_) | DomainError::AuthenticationProtocolError(_) => {
} HttpResponse::Unauthorized()
DomainError::DatabaseError(_) }
| DomainError::InternalError(_) DomainError::DatabaseError(_)
| DomainError::UnknownCryptoError(_) => HttpResponse::InternalServerError(), | DomainError::InternalError(_)
DomainError::Base64DecodeError(_) | DomainError::BinarySerializationError(_) => { | DomainError::UnknownCryptoError(_) => HttpResponse::InternalServerError(),
HttpResponse::BadRequest() DomainError::Base64DecodeError(_) | DomainError::BinarySerializationError(_) => {
} HttpResponse::BadRequest()
}
},
TcpError::BadRequest(_) => HttpResponse::BadRequest(),
TcpError::InternalServerError(_) => HttpResponse::InternalServerError(),
TcpError::UnauthorizedError(_) => HttpResponse::Unauthorized(),
} }
.body(error.to_string()) .body(error.to_string())
} }