lldap/src/infra/auth_service.rs

392 lines
12 KiB
Rust
Raw Normal View History

2021-05-23 14:20:26 +00:00
use crate::{
2021-06-16 20:04:11 +00:00
domain::{
handler::{BackendHandler, LoginHandler},
opaque_handler::OpaqueHandler,
},
2021-05-23 14:20:26 +00:00
infra::{
2021-06-21 07:24:49 +00:00
tcp_api::{error_to_api_response, ApiResult},
2021-05-23 14:20:26 +00:00
tcp_backend_handler::*,
tcp_server::{error_to_http_response, AppState},
},
};
2021-05-20 17:18:15 +00:00
use actix_web::{
cookie::{Cookie, SameSite},
2021-05-23 14:20:26 +00:00
dev::{Service, ServiceRequest, ServiceResponse, Transform},
2021-05-20 17:18:15 +00:00
error::{ErrorBadRequest, ErrorUnauthorized},
2021-05-23 14:20:26 +00:00
web, HttpRequest, HttpResponse,
2021-05-20 17:18:15 +00:00
};
2021-05-23 14:20:26 +00:00
use actix_web_httpauth::extractors::bearer::BearerAuth;
use anyhow::Result;
2021-05-20 17:18:15 +00:00
use chrono::prelude::*;
2021-05-23 14:20:26 +00:00
use futures::future::{ok, Ready};
use futures_util::{FutureExt, TryFutureExt};
use hmac::Hmac;
use jwt::{SignWithKey, VerifyWithKey};
2021-06-21 07:24:49 +00:00
use lldap_model::{login, registration, BindRequest, JWTClaims};
2021-05-23 14:20:26 +00:00
use log::*;
2021-05-20 17:18:15 +00:00
use sha2::Sha512;
2021-05-23 14:20:26 +00:00
use std::collections::{hash_map::DefaultHasher, HashSet};
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::task::{Context, Poll};
use time::ext::NumericalDuration;
2021-05-20 17:18:15 +00:00
type Token<S> = jwt::Token<jwt::Header, JWTClaims, S>;
type SignedToken = Token<jwt::token::Signed>;
fn create_jwt(key: &Hmac<Sha512>, user: String, groups: HashSet<String>) -> SignedToken {
let claims = JWTClaims {
exp: Utc::now() + chrono::Duration::days(1),
iat: Utc::now(),
user,
groups,
};
let header = jwt::Header {
algorithm: jwt::AlgorithmType::Hs512,
..Default::default()
};
jwt::Token::new(header, claims).sign_with_key(key).unwrap()
}
2021-05-23 14:20:26 +00:00
fn get_refresh_token_from_cookie(
request: HttpRequest,
2021-05-23 14:26:24 +00:00
) -> std::result::Result<(u64, String), HttpResponse> {
2021-05-23 14:20:26 +00:00
match request.cookie("refresh_token") {
None => Err(HttpResponse::Unauthorized().body("Missing refresh token")),
Some(t) => match t.value().split_once("+") {
None => Err(HttpResponse::Unauthorized().body("Invalid refresh token")),
2021-05-23 14:26:24 +00:00
Some((token, u)) => {
let refresh_token_hash = {
let mut s = DefaultHasher::new();
token.hash(&mut s);
s.finish()
};
Ok((refresh_token_hash, u.to_string()))
}
2021-05-23 14:20:26 +00:00
},
}
}
2021-05-20 17:18:15 +00:00
async fn get_refresh<Backend>(
data: web::Data<AppState<Backend>>,
request: HttpRequest,
) -> HttpResponse
where
Backend: TcpBackendHandler + BackendHandler + 'static,
{
let backend_handler = &data.backend_handler;
let jwt_key = &data.jwt_key;
2021-05-23 14:26:24 +00:00
let (refresh_token_hash, user) = match get_refresh_token_from_cookie(request) {
2021-05-23 14:20:26 +00:00
Ok(t) => t,
Err(http_response) => return http_response,
2021-05-20 17:18:15 +00:00
};
2021-05-23 14:20:26 +00:00
let res_found = data
.backend_handler
2021-05-23 14:26:24 +00:00
.check_token(refresh_token_hash, &user)
2021-05-23 14:20:26 +00:00
.await;
2021-05-20 17:18:15 +00:00
// Async closures are not supported yet.
match res_found {
Ok(found) => {
if found {
backend_handler.get_user_groups(user.to_string()).await
} else {
Err(DomainError::AuthenticationError(
"Invalid refresh token".to_string(),
))
}
}
Err(e) => Err(e),
}
.map(|groups| create_jwt(jwt_key, user.to_string(), groups))
.map(|token| {
2021-05-23 14:20:26 +00:00
HttpResponse::Ok()
.cookie(
Cookie::build("token", token.as_str())
.max_age(1.days())
.path("/api")
.http_only(true)
.same_site(SameSite::Strict)
.finish(),
)
.body(token.as_str().to_owned())
2021-05-20 17:18:15 +00:00
})
.unwrap_or_else(error_to_http_response)
}
async fn post_logout<Backend>(
2021-05-23 14:20:26 +00:00
data: web::Data<AppState<Backend>>,
request: HttpRequest,
) -> HttpResponse
where
Backend: TcpBackendHandler + BackendHandler + 'static,
{
2021-05-23 14:26:24 +00:00
let (refresh_token_hash, user) = match get_refresh_token_from_cookie(request) {
2021-05-23 14:20:26 +00:00
Ok(t) => t,
Err(http_response) => return http_response,
};
if let Err(response) = data
.backend_handler
2021-05-23 14:26:24 +00:00
.delete_refresh_token(refresh_token_hash)
2021-05-23 14:20:26 +00:00
.map_err(error_to_http_response)
.await
{
return response;
};
match data
.backend_handler
.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);
2021-05-23 14:26:24 +00:00
}
2021-05-23 14:20:26 +00:00
}
Err(response) => return response,
};
HttpResponse::Ok()
.cookie(
Cookie::build("token", "")
.max_age(0.days())
.path("/api")
.http_only(true)
.same_site(SameSite::Strict)
.finish(),
)
.cookie(
Cookie::build("refresh_token", "")
.max_age(0.days())
.path("/auth")
2021-05-23 14:20:26 +00:00
.http_only(true)
.same_site(SameSite::Strict)
.finish(),
)
.finish()
}
2021-06-21 07:24:49 +00:00
async fn opaque_login_start<Backend>(
2021-05-20 17:18:15 +00:00
data: web::Data<AppState<Backend>>,
2021-06-21 07:24:49 +00:00
request: web::Json<login::ClientLoginStartRequest>,
) -> ApiResult<login::ServerLoginStartResponse>
where
Backend: OpaqueHandler + 'static,
{
data.backend_handler
.login_start(request.clone())
.await
.map(|res| ApiResult::Left(web::Json(res)))
.unwrap_or_else(error_to_api_response)
}
async fn get_login_successful_response<Backend>(
data: &web::Data<AppState<Backend>>,
name: &str,
2021-05-20 17:18:15 +00:00
) -> HttpResponse
where
2021-06-21 07:24:49 +00:00
Backend: TcpBackendHandler + BackendHandler,
2021-05-20 17:18:15 +00:00
{
2021-06-21 07:24:49 +00:00
// The authentication was successful, we need to fetch the groups to create the JWT
// token.
2021-05-20 17:18:15 +00:00
data.backend_handler
2021-06-21 07:24:49 +00:00
.get_user_groups(name.to_string())
.and_then(|g| async { Ok((g, data.backend_handler.create_refresh_token(&name).await?)) })
2021-05-20 17:18:15 +00:00
.await
.map(|(groups, (refresh_token, max_age))| {
2021-06-21 07:24:49 +00:00
let token = create_jwt(&data.jwt_key, name.to_string(), groups);
2021-05-23 14:20:26 +00:00
HttpResponse::Ok()
.cookie(
Cookie::build("token", token.as_str())
.max_age(1.days())
.path("/api")
.http_only(true)
.same_site(SameSite::Strict)
.finish(),
)
.cookie(
2021-06-21 07:24:49 +00:00
Cookie::build("refresh_token", refresh_token + "+" + &name)
2021-05-23 14:20:26 +00:00
.max_age(max_age.num_days().days())
.path("/auth")
2021-05-23 14:20:26 +00:00
.http_only(true)
.same_site(SameSite::Strict)
.finish(),
)
.body(token.as_str().to_owned())
2021-05-20 17:18:15 +00:00
})
.unwrap_or_else(error_to_http_response)
}
2021-06-21 07:24:49 +00:00
async fn opaque_login_finish<Backend>(
data: web::Data<AppState<Backend>>,
request: web::Json<login::ClientLoginFinishRequest>,
) -> HttpResponse
where
Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static,
{
let name = match data.backend_handler.login_finish(request.clone()).await {
Ok(n) => n,
Err(e) => return error_to_http_response(e),
};
get_login_successful_response(&data, &name).await
}
async fn post_authorize<Backend>(
data: web::Data<AppState<Backend>>,
request: web::Json<BindRequest>,
) -> HttpResponse
where
Backend: TcpBackendHandler + BackendHandler + LoginHandler + 'static,
{
if let Err(e) = data.backend_handler.bind(request.clone()).await {
return error_to_http_response(e);
}
get_login_successful_response(&data, &request.name).await
}
async fn opaque_register_start<Backend>(
data: web::Data<AppState<Backend>>,
request: web::Json<registration::ClientRegistrationStartRequest>,
) -> ApiResult<registration::ServerRegistrationStartResponse>
where
Backend: OpaqueHandler + 'static,
{
data.backend_handler
.registration_start(request.clone())
.await
.map(|res| ApiResult::Left(web::Json(res)))
.unwrap_or_else(error_to_api_response)
}
async fn opaque_register_finish<Backend>(
data: web::Data<AppState<Backend>>,
request: web::Json<registration::ClientRegistrationFinishRequest>,
) -> HttpResponse
where
Backend: TcpBackendHandler + BackendHandler + OpaqueHandler + 'static,
{
if let Err(e) = data
.backend_handler
.registration_finish(request.clone())
.await
{
return error_to_http_response(e);
}
HttpResponse::Ok().finish()
}
2021-05-20 17:18:15 +00:00
pub struct CookieToHeaderTranslatorFactory;
impl<S> Transform<S, ServiceRequest> for CookieToHeaderTranslatorFactory
2021-05-20 17:18:15 +00:00
where
S: Service<ServiceRequest, Response = ServiceResponse, Error = actix_web::Error>,
2021-05-23 14:20:26 +00:00
S::Future: 'static,
2021-05-20 17:18:15 +00:00
{
type Response = ServiceResponse;
2021-05-20 17:18:15 +00:00
type Error = actix_web::Error;
type InitError = ();
type Transform = CookieToHeaderTranslator<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ok(CookieToHeaderTranslator { service })
}
}
pub struct CookieToHeaderTranslator<S> {
service: S,
}
impl<S> Service<ServiceRequest> for CookieToHeaderTranslator<S>
2021-05-20 17:18:15 +00:00
where
S: Service<ServiceRequest, Response = ServiceResponse, Error = actix_web::Error>,
2021-05-20 17:18:15 +00:00
S::Future: 'static,
{
type Response = ServiceResponse;
2021-05-20 17:18:15 +00:00
type Error = actix_web::Error;
#[allow(clippy::type_complexity)]
type Future = Pin<Box<dyn core::future::Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&self, mut req: ServiceRequest) -> Self::Future {
if let Some(token_cookie) = req.cookie("token") {
if let Ok(header_value) = actix_http::header::HeaderValue::from_str(&format!(
"Bearer {}",
token_cookie.value()
)) {
req.headers_mut()
.insert(actix_http::header::AUTHORIZATION, header_value);
} else {
return async move {
Ok(req.error_response(ErrorBadRequest("Invalid token cookie")))
}
.boxed_local();
}
};
Box::pin(self.service.call(req))
}
}
pub async fn token_validator<Backend>(
req: ServiceRequest,
credentials: BearerAuth,
) -> Result<ServiceRequest, actix_web::Error>
where
Backend: TcpBackendHandler + BackendHandler + 'static,
{
let state = req
.app_data::<web::Data<AppState<Backend>>>()
.expect("Invalid app config");
let token: Token<_> = VerifyWithKey::verify_with_key(credentials.token(), &state.jwt_key)
.map_err(|_| ErrorUnauthorized("Invalid JWT"))?;
if token.claims().exp.lt(&Utc::now()) {
return Err(ErrorUnauthorized("Expired JWT"));
}
let jwt_hash = {
let mut s = DefaultHasher::new();
credentials.token().hash(&mut s);
s.finish()
};
2021-05-23 14:20:26 +00:00
if state.jwt_blacklist.read().unwrap().contains(&jwt_hash) {
2021-05-20 17:18:15 +00:00
return Err(ErrorUnauthorized("JWT was logged out"));
}
let groups = &token.claims().groups;
if groups.contains("lldap_admin") {
debug!("Got authorized token for user {}", &token.claims().user);
Ok(req)
} else {
Err(ErrorUnauthorized(
"JWT error: User is not in group lldap_admin",
))
}
}
2021-05-23 14:20:26 +00:00
pub fn configure_server<Backend>(cfg: &mut web::ServiceConfig)
where
2021-06-16 20:04:11 +00:00
Backend: TcpBackendHandler + LoginHandler + OpaqueHandler + BackendHandler + 'static,
2021-05-20 17:18:15 +00:00
{
2021-05-23 14:20:26 +00:00
cfg.service(web::resource("").route(web::post().to(post_authorize::<Backend>)))
2021-06-21 07:24:49 +00:00
.service(
web::resource("/opaque/login/start")
.route(web::post().to(opaque_login_start::<Backend>)),
)
.service(
web::resource("/opaque/login/finish")
.route(web::post().to(opaque_login_finish::<Backend>)),
)
.service(
web::resource("/opaque/register/start")
.route(web::post().to(opaque_register_start::<Backend>)),
)
.service(
web::resource("/opaque/register/finish")
.route(web::post().to(opaque_register_finish::<Backend>)),
)
2021-05-23 14:20:26 +00:00
.service(web::resource("/refresh").route(web::get().to(get_refresh::<Backend>)))
.service(web::resource("/logout").route(web::post().to(post_logout::<Backend>)));
2021-05-20 17:18:15 +00:00
}