completely rebuilt the auth implementation to support OIDC in the future

This commit is contained in:
Lennart
2024-10-03 19:47:50 +02:00
parent 235e7b207a
commit 6f12a1d80e
29 changed files with 257 additions and 312 deletions

21
Cargo.lock generated
View File

@@ -1934,7 +1934,6 @@ dependencies = [
"async-trait", "async-trait",
"clap", "clap",
"env_logger", "env_logger",
"rustical_auth",
"rustical_caldav", "rustical_caldav",
"rustical_carddav", "rustical_carddav",
"rustical_frontend", "rustical_frontend",
@@ -1946,18 +1945,6 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "rustical_auth"
version = "0.1.0"
dependencies = [
"actix-web",
"actix-web-httpauth",
"futures-util",
"password-auth",
"serde",
"thiserror",
]
[[package]] [[package]]
name = "rustical_caldav" name = "rustical_caldav"
version = "0.1.0" version = "0.1.0"
@@ -1971,7 +1958,6 @@ dependencies = [
"futures-util", "futures-util",
"quick-xml", "quick-xml",
"roxmltree", "roxmltree",
"rustical_auth",
"rustical_dav", "rustical_dav",
"rustical_store", "rustical_store",
"serde", "serde",
@@ -1993,7 +1979,6 @@ dependencies = [
"futures-util", "futures-util",
"quick-xml", "quick-xml",
"roxmltree", "roxmltree",
"rustical_auth",
"rustical_dav", "rustical_dav",
"rustical_store", "rustical_store",
"serde", "serde",
@@ -2016,7 +2001,7 @@ dependencies = [
"log", "log",
"quick-xml", "quick-xml",
"roxmltree", "roxmltree",
"rustical_auth", "rustical_store",
"serde", "serde",
"strum", "strum",
"thiserror", "thiserror",
@@ -2031,7 +2016,6 @@ dependencies = [
"anyhow", "anyhow",
"askama", "askama",
"askama_actix", "askama_actix",
"rustical_auth",
"rustical_store", "rustical_store",
"serde", "serde",
"thiserror", "thiserror",
@@ -2042,11 +2026,14 @@ dependencies = [
name = "rustical_store" name = "rustical_store"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"actix-web",
"actix-web-httpauth",
"anyhow", "anyhow",
"async-trait", "async-trait",
"chrono", "chrono",
"ical", "ical",
"lazy_static", "lazy_static",
"password-auth",
"regex", "regex",
"rstest", "rstest",
"rstest_reuse", "rstest_reuse",

View File

@@ -9,7 +9,6 @@ members = ["crates/*"]
[dependencies] [dependencies]
rustical_store = { path = "./crates/store/" } rustical_store = { path = "./crates/store/" }
rustical_auth = { path = "./crates/auth/" }
rustical_caldav = { path = "./crates/caldav/" } rustical_caldav = { path = "./crates/caldav/" }
rustical_carddav = { path = "./crates/carddav/" } rustical_carddav = { path = "./crates/carddav/" }
rustical_frontend = { path = "./crates/frontend/" } rustical_frontend = { path = "./crates/frontend/" }

View File

@@ -1,12 +0,0 @@
[package]
name = "rustical_auth"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4.9"
actix-web-httpauth = "0.8"
futures-util = "0.3"
password-auth = "1.0"
serde = { version = "1.0", features = ["derive"] }
thiserror = "1.0"

View File

@@ -1,36 +0,0 @@
use actix_web::{http::StatusCode, HttpResponse};
use thiserror::Error;
#[derive(Debug, Error, Clone)]
pub enum Error {
#[error("Internal server error")]
InternalError,
#[error("Not found")]
NotFound,
#[error("Bad request")]
BadRequest,
#[error("Unauthorized")]
Unauthorized,
}
impl actix_web::error::ResponseError for Error {
fn status_code(&self) -> StatusCode {
match *self {
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
Self::NotFound => StatusCode::NOT_FOUND,
Self::BadRequest => StatusCode::BAD_REQUEST,
Self::Unauthorized => StatusCode::UNAUTHORIZED,
}
}
fn error_response(&self) -> HttpResponse {
match self {
Error::Unauthorized => HttpResponse::build(self.status_code())
.append_header(("WWW-Authenticate", "Basic"))
// This is an unfortunate workaround for https://github.com/actix/actix-web/issues/1805
.force_close()
.body(self.to_string()),
_ => HttpResponse::build(self.status_code()).body(self.to_string()),
}
}
}

View File

@@ -1,40 +0,0 @@
use actix_web::{dev::Payload, web::Data, FromRequest, HttpRequest};
use std::{
future::{ready, Ready},
marker::PhantomData,
};
use crate::error::Error;
use super::{AuthInfo, CheckAuthentication};
#[derive(Clone)]
pub struct AuthInfoExtractor<A: CheckAuthentication> {
pub inner: AuthInfo,
pub _provider_type: PhantomData<A>,
}
impl<T: CheckAuthentication> From<AuthInfo> for AuthInfoExtractor<T> {
fn from(value: AuthInfo) -> Self {
AuthInfoExtractor {
inner: value,
_provider_type: PhantomData::<T>,
}
}
}
impl<A> FromRequest for AuthInfoExtractor<A>
where
A: CheckAuthentication,
{
type Error = Error;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
let result = req.app_data::<Data<A>>().unwrap().validate(req);
ready(result.map(|auth_info| Self {
inner: auth_info,
_provider_type: PhantomData,
}))
}
}

View File

@@ -1,49 +0,0 @@
use crate::error::Error;
use actix_web::{http::header::Header, HttpRequest};
use actix_web_httpauth::headers::authorization::{Authorization, Basic};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::{AuthInfo, CheckAuthentication};
#[derive(Debug)]
pub struct HtpasswdAuth {
pub config: HtpasswdAuthConfig,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct HtpasswdAuthUserConfig {
password: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct HtpasswdAuthConfig {
pub users: HashMap<String, HtpasswdAuthUserConfig>,
}
impl CheckAuthentication for HtpasswdAuth {
fn validate(&self, req: &HttpRequest) -> Result<AuthInfo, Error> {
if let Ok(auth) = Authorization::<Basic>::parse(req) {
let user_id = auth.as_ref().user_id();
// Map None to empty password
let password = auth.as_ref().password().unwrap_or_default();
let user_config = if let Some(user_config) = self.config.users.get(user_id) {
user_config
} else {
return Err(crate::error::Error::Unauthorized);
};
if let Err(e) = password_auth::verify_password(password, &user_config.password) {
dbg!(e);
return Err(crate::error::Error::Unauthorized);
}
Ok(AuthInfo {
user_id: user_id.to_string(),
})
} else {
Err(crate::error::Error::Unauthorized)
}
}
}

View File

@@ -1,39 +0,0 @@
use actix_web::HttpRequest;
use crate::error::Error;
pub use extractor::AuthInfoExtractor;
pub use htpasswd::{HtpasswdAuth, HtpasswdAuthConfig};
pub use none::NoneAuth;
pub mod error;
pub mod extractor;
pub mod htpasswd;
pub mod none;
#[derive(Clone)]
pub struct AuthInfo {
pub user_id: String,
}
pub trait CheckAuthentication: Send + Sync + 'static {
fn validate(&self, req: &HttpRequest) -> Result<AuthInfo, Error>
where
Self: Sized;
}
#[derive(Debug)]
pub enum AuthProvider {
Htpasswd(HtpasswdAuth),
None(NoneAuth),
}
impl CheckAuthentication for AuthProvider {
fn validate(&self, req: &HttpRequest) -> Result<AuthInfo, Error>
where
Self: Sized,
{
match self {
Self::Htpasswd(auth) => auth.validate(req),
Self::None(auth) => auth.validate(req),
}
}
}

View File

@@ -1,21 +0,0 @@
use actix_web::{http::header::Header, HttpRequest};
use actix_web_httpauth::headers::authorization::{Authorization, Basic};
use crate::error::Error;
use super::{AuthInfo, CheckAuthentication};
#[derive(Debug, Clone)]
pub struct NoneAuth;
impl CheckAuthentication for NoneAuth {
fn validate(&self, req: &HttpRequest) -> Result<AuthInfo, Error> {
if let Ok(auth) = Authorization::<Basic>::parse(req) {
Ok(AuthInfo {
user_id: auth.as_ref().user_id().to_string(),
})
} else {
Err(crate::error::Error::Unauthorized)
}
}
}

View File

@@ -17,7 +17,6 @@ quick-xml = { version = "0.36", features = [
roxmltree = "0.20" roxmltree = "0.20"
rustical_store = { path = "../store/" } rustical_store = { path = "../store/" }
rustical_dav = { path = "../dav/" } rustical_dav = { path = "../dav/" }
rustical_auth = { path = "../auth/" }
serde = { version = "1.0", features = ["serde_derive", "derive"] } serde = { version = "1.0", features = ["serde_derive", "derive"] }
serde_json = "1.0" serde_json = "1.0"
tokio = { version = "1.40", features = ["sync", "full"] } tokio = { version = "1.40", features = ["sync", "full"] }

View File

@@ -2,7 +2,7 @@ use crate::CalDavContext;
use crate::Error; use crate::Error;
use actix_web::web::{Data, Path}; use actix_web::web::{Data, Path};
use actix_web::HttpResponse; use actix_web::HttpResponse;
use rustical_auth::{AuthInfoExtractor, CheckAuthentication}; use rustical_store::auth::User;
use rustical_store::model::Calendar; use rustical_store::model::Calendar;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -53,14 +53,14 @@ struct MkcalendarRequest {
set: PropElement<MkcolCalendarProp>, set: PropElement<MkcolCalendarProp>,
} }
pub async fn route_mkcalendar<A: CheckAuthentication, C: CalendarStore + ?Sized>( pub async fn route_mkcalendar<C: CalendarStore + ?Sized>(
path: Path<(String, String)>, path: Path<(String, String)>,
body: String, body: String,
auth: AuthInfoExtractor<A>, user: User,
context: Data<CalDavContext<C>>, context: Data<CalDavContext<C>>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let (principal, cid) = path.into_inner(); let (principal, cid) = path.into_inner();
if principal != auth.inner.user_id { if principal != user.id {
return Err(Error::Unauthorized); return Err(Error::Unauthorized);
} }

View File

@@ -5,9 +5,8 @@ use actix_web::{
}; };
use calendar_multiget::{handle_calendar_multiget, CalendarMultigetRequest}; use calendar_multiget::{handle_calendar_multiget, CalendarMultigetRequest};
use calendar_query::{handle_calendar_query, CalendarQueryRequest}; use calendar_query::{handle_calendar_query, CalendarQueryRequest};
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
use rustical_dav::methods::propfind::ServicePrefix; use rustical_dav::methods::propfind::ServicePrefix;
use rustical_store::CalendarStore; use rustical_store::{auth::User, CalendarStore};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sync_collection::{handle_sync_collection, SyncCollectionRequest}; use sync_collection::{handle_sync_collection, SyncCollectionRequest};
use tokio::sync::RwLock; use tokio::sync::RwLock;
@@ -32,17 +31,17 @@ pub enum ReportRequest {
SyncCollection(SyncCollectionRequest), SyncCollection(SyncCollectionRequest),
} }
pub async fn route_report_calendar<A: CheckAuthentication, C: CalendarStore + ?Sized>( pub async fn route_report_calendar<C: CalendarStore + ?Sized>(
path: Path<(String, String)>, path: Path<(String, String)>,
body: String, body: String,
auth: AuthInfoExtractor<A>, user: User,
req: HttpRequest, req: HttpRequest,
cal_store: Data<RwLock<C>>, cal_store: Data<RwLock<C>>,
prefix: Data<ServicePrefix>, prefix: Data<ServicePrefix>,
) -> Result<impl Responder, Error> { ) -> Result<impl Responder, Error> {
let prefix = prefix.into_inner(); let prefix = prefix.into_inner();
let (principal, cid) = path.into_inner(); let (principal, cid) = path.into_inner();
if principal != auth.inner.user_id { if principal != user.id {
return Err(Error::Unauthorized); return Err(Error::Unauthorized);
} }

View File

@@ -5,18 +5,18 @@ use actix_web::http::header::HeaderValue;
use actix_web::web::{Data, Path}; use actix_web::web::{Data, Path};
use actix_web::HttpRequest; use actix_web::HttpRequest;
use actix_web::HttpResponse; use actix_web::HttpResponse;
use rustical_auth::{AuthInfoExtractor, CheckAuthentication}; use rustical_store::auth::User;
use rustical_store::model::CalendarObject; use rustical_store::model::CalendarObject;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
pub async fn get_event<A: CheckAuthentication, C: CalendarStore + ?Sized>( pub async fn get_event<C: CalendarStore + ?Sized>(
context: Data<CalDavContext<C>>, context: Data<CalDavContext<C>>,
path: Path<(String, String, String)>, path: Path<(String, String, String)>,
auth: AuthInfoExtractor<A>, user: User,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let (principal, cid, mut uid) = path.into_inner(); let (principal, cid, mut uid) = path.into_inner();
if auth.inner.user_id != principal { if user.id != principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
@@ -26,7 +26,7 @@ pub async fn get_event<A: CheckAuthentication, C: CalendarStore + ?Sized>(
.await .await
.get_calendar(&principal, &cid) .get_calendar(&principal, &cid)
.await?; .await?;
if auth.inner.user_id != calendar.principal { if user.id != calendar.principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
@@ -46,16 +46,15 @@ pub async fn get_event<A: CheckAuthentication, C: CalendarStore + ?Sized>(
.body(event.get_ics().to_owned())) .body(event.get_ics().to_owned()))
} }
pub async fn put_event<A: CheckAuthentication, C: CalendarStore + ?Sized>( pub async fn put_event<C: CalendarStore + ?Sized>(
context: Data<CalDavContext<C>>, context: Data<CalDavContext<C>>,
path: Path<(String, String, String)>, path: Path<(String, String, String)>,
body: String, body: String,
auth: AuthInfoExtractor<A>, user: User,
req: HttpRequest, req: HttpRequest,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let (principal, cid, mut uid) = path.into_inner(); let (principal, cid, mut uid) = path.into_inner();
let auth_info = auth.inner; if user.id != principal {
if auth_info.user_id != principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
@@ -65,7 +64,7 @@ pub async fn put_event<A: CheckAuthentication, C: CalendarStore + ?Sized>(
.await .await
.get_calendar(&principal, &cid) .get_calendar(&principal, &cid)
.await?; .await?;
if auth_info.user_id != calendar.principal { if user.id != calendar.principal {
return Ok(HttpResponse::Unauthorized().body("")); return Ok(HttpResponse::Unauthorized().body(""));
} }
// Incredibly bodged method of normalising the uid but works for a prototype // Incredibly bodged method of normalising the uid but works for a prototype

View File

@@ -5,7 +5,6 @@ use calendar::resource::CalendarResourceService;
use calendar_object::resource::CalendarObjectResourceService; use calendar_object::resource::CalendarObjectResourceService;
use principal::PrincipalResourceService; use principal::PrincipalResourceService;
use root::RootResourceService; use root::RootResourceService;
use rustical_auth::CheckAuthentication;
use rustical_dav::methods::{ use rustical_dav::methods::{
propfind::ServicePrefix, route_delete, route_propfind, route_proppatch, propfind::ServicePrefix, route_delete, route_propfind, route_proppatch,
}; };
@@ -30,10 +29,9 @@ pub fn configure_well_known(cfg: &mut web::ServiceConfig, caldav_root: String) {
cfg.service(web::redirect("/caldav", caldav_root).permanent()); cfg.service(web::redirect("/caldav", caldav_root).permanent());
} }
pub fn configure_dav<A: CheckAuthentication, C: CalendarStore + ?Sized>( pub fn configure_dav<C: CalendarStore + ?Sized>(
cfg: &mut web::ServiceConfig, cfg: &mut web::ServiceConfig,
prefix: String, prefix: String,
auth: Arc<A>,
store: Arc<RwLock<C>>, store: Arc<RwLock<C>>,
) { ) {
let propfind_method = || web::method(Method::from_str("PROPFIND").unwrap()); let propfind_method = || web::method(Method::from_str("PROPFIND").unwrap());
@@ -46,7 +44,6 @@ pub fn configure_dav<A: CheckAuthentication, C: CalendarStore + ?Sized>(
})) }))
.app_data(Data::new(ServicePrefix(prefix))) .app_data(Data::new(ServicePrefix(prefix)))
.app_data(Data::from(store.clone())) .app_data(Data::from(store.clone()))
.app_data(Data::from(auth))
.service( .service(
web::resource("{path:.*}") web::resource("{path:.*}")
// Without the guard this service would handle all requests // Without the guard this service would handle all requests
@@ -55,20 +52,17 @@ pub fn configure_dav<A: CheckAuthentication, C: CalendarStore + ?Sized>(
) )
.service( .service(
web::resource("") web::resource("")
.route(propfind_method().to(route_propfind::<A, RootResourceService>)) .route(propfind_method().to(route_propfind::<RootResourceService>))
.route(proppatch_method().to(route_proppatch::<A, RootResourceService>)), .route(proppatch_method().to(route_proppatch::<RootResourceService>)),
) )
.service( .service(
web::scope("/user").service( web::scope("/user").service(
web::scope("/{principal}") web::scope("/{principal}")
.service( .service(
web::resource("") web::resource("")
.route(propfind_method().to(route_propfind::<PrincipalResourceService<C>>))
.route( .route(
propfind_method().to(route_propfind::<A, PrincipalResourceService<C>>), proppatch_method().to(route_proppatch::<PrincipalResourceService<C>>),
)
.route(
proppatch_method()
.to(route_proppatch::<A, PrincipalResourceService<C>>),
), ),
) )
.service( .service(
@@ -76,49 +70,47 @@ pub fn configure_dav<A: CheckAuthentication, C: CalendarStore + ?Sized>(
.service( .service(
web::resource("") web::resource("")
.route( .route(
report_method().to( report_method()
calendar::methods::report::route_report_calendar::<A, C>, .to(calendar::methods::report::route_report_calendar::<C>),
),
) )
.route( .route(
propfind_method() propfind_method()
.to(route_propfind::<A, CalendarResourceService<C>>), .to(route_propfind::<CalendarResourceService<C>>),
) )
.route( .route(
proppatch_method() proppatch_method()
.to(route_proppatch::<A, CalendarResourceService<C>>), .to(route_proppatch::<CalendarResourceService<C>>),
) )
.route( .route(
web::method(Method::DELETE) web::method(Method::DELETE)
.to(route_delete::<A, CalendarResourceService<C>>), .to(route_delete::<CalendarResourceService<C>>),
) )
.route( .route(
mkcalendar_method().to( mkcalendar_method()
calendar::methods::mkcalendar::route_mkcalendar::<A, C>, .to(calendar::methods::mkcalendar::route_mkcalendar::<C>),
),
), ),
) )
.service( .service(
web::resource("/{event}") web::resource("/{event}")
.route( .route(
propfind_method() propfind_method()
.to(route_propfind::<A, CalendarObjectResourceService<C>>), .to(route_propfind::<CalendarObjectResourceService<C>>),
) )
.route( .route(
proppatch_method() proppatch_method()
.to(route_proppatch::<A, CalendarObjectResourceService<C>>), .to(route_proppatch::<CalendarObjectResourceService<C>>),
) )
.route( .route(
web::method(Method::DELETE) web::method(Method::DELETE)
.to(route_delete::<A, CalendarObjectResourceService<C>>), .to(route_delete::<CalendarObjectResourceService<C>>),
) )
.route( .route(
web::method(Method::GET) web::method(Method::GET)
.to(calendar_object::methods::get_event::<A, C>), .to(calendar_object::methods::get_event::<C>),
) )
.route( .route(
web::method(Method::PUT) web::method(Method::PUT)
.to(calendar_object::methods::put_event::<A, C>), .to(calendar_object::methods::put_event::<C>),
), ),
), ),
), ),

View File

@@ -17,7 +17,6 @@ quick-xml = { version = "0.36", features = [
roxmltree = "0.20" roxmltree = "0.20"
rustical_store = { path = "../store/" } rustical_store = { path = "../store/" }
rustical_dav = { path = "../dav/" } rustical_dav = { path = "../dav/" }
rustical_auth = { path = "../auth/" }
serde = { version = "1.0", features = ["serde_derive", "derive"] } serde = { version = "1.0", features = ["serde_derive", "derive"] }
serde_json = "1.0" serde_json = "1.0"
tokio = { version = "1.40", features = ["sync", "full"] } tokio = { version = "1.40", features = ["sync", "full"] }

View File

@@ -1,17 +1,10 @@
use actix_web::{web, HttpResponse, Responder}; use actix_web::{web, HttpResponse, Responder};
use rustical_auth::CheckAuthentication;
use std::sync::Arc;
pub fn configure_well_known(cfg: &mut web::ServiceConfig, carddav_root: String) { pub fn configure_well_known(cfg: &mut web::ServiceConfig, carddav_root: String) {
cfg.service(web::redirect("/carddav", carddav_root).permanent()); cfg.service(web::redirect("/carddav", carddav_root).permanent());
} }
pub fn configure_dav<A: CheckAuthentication>( pub fn configure_dav(_cfg: &mut web::ServiceConfig, _prefix: String) {}
_cfg: &mut web::ServiceConfig,
_prefix: String,
_auth: Arc<A>,
) {
}
pub async fn options_handler() -> impl Responder { pub async fn options_handler() -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()

View File

@@ -13,7 +13,7 @@ quick-xml = { version = "0.36", features = [
"serde-types", "serde-types",
"serialize", "serialize",
] } ] }
rustical_auth = { path = "../auth/" } rustical_store = { path = "../store/" }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
strum = "0.26" strum = "0.26"
itertools = "0.13" itertools = "0.13"

View File

@@ -3,11 +3,12 @@ use actix_web::web::Path;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use actix_web::HttpResponse; use actix_web::HttpResponse;
use actix_web::Responder; use actix_web::Responder;
use rustical_auth::CheckAuthentication; use rustical_store::auth::User;
pub async fn route_delete<A: CheckAuthentication, R: ResourceService>( pub async fn route_delete<R: ResourceService>(
path_components: Path<R::PathComponents>, path_components: Path<R::PathComponents>,
req: HttpRequest, req: HttpRequest,
_user: User,
) -> Result<impl Responder, R::Error> { ) -> Result<impl Responder, R::Error> {
let path_components = path_components.into_inner(); let path_components = path_components.into_inner();

View File

@@ -10,7 +10,7 @@ use actix_web::web::{Data, Path};
use actix_web::HttpRequest; use actix_web::HttpRequest;
use derive_more::derive::Deref; use derive_more::derive::Deref;
use log::debug; use log::debug;
use rustical_auth::{AuthInfoExtractor, CheckAuthentication}; use rustical_store::auth::User;
use serde::Deserialize; use serde::Deserialize;
// This is not the final place for this struct // This is not the final place for this struct
@@ -39,12 +39,12 @@ struct PropfindElement {
prop: PropfindType, prop: PropfindType,
} }
pub async fn route_propfind<A: CheckAuthentication, R: ResourceService>( pub async fn route_propfind<R: ResourceService>(
path_components: Path<R::PathComponents>, path_components: Path<R::PathComponents>,
body: String, body: String,
req: HttpRequest, req: HttpRequest,
prefix: Data<ServicePrefix>, prefix: Data<ServicePrefix>,
auth: AuthInfoExtractor<A>, user: User,
depth: Depth, depth: Depth,
) -> Result< ) -> Result<
MultistatusElement< MultistatusElement<
@@ -86,7 +86,7 @@ pub async fn route_propfind<A: CheckAuthentication, R: ResourceService>(
} }
} }
let resource = resource_service.get_resource(auth.inner.user_id).await?; let resource = resource_service.get_resource(user.id).await?;
let response = resource.propfind(&prefix, req.path(), props).await?; let response = resource.propfind(&prefix, req.path(), props).await?;
Ok(MultistatusElement { Ok(MultistatusElement {

View File

@@ -9,7 +9,7 @@ use crate::Error;
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
use actix_web::{web::Path, HttpRequest}; use actix_web::{web::Path, HttpRequest};
use log::debug; use log::debug;
use rustical_auth::{AuthInfoExtractor, CheckAuthentication}; use rustical_store::auth::User;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
@@ -47,11 +47,11 @@ struct PropertyupdateElement<T> {
operations: Vec<Operation<T>>, operations: Vec<Operation<T>>,
} }
pub async fn route_proppatch<A: CheckAuthentication, R: ResourceService>( pub async fn route_proppatch<R: ResourceService>(
path: Path<R::PathComponents>, path: Path<R::PathComponents>,
body: String, body: String,
req: HttpRequest, req: HttpRequest,
auth: AuthInfoExtractor<A>, user: User,
) -> Result<MultistatusElement<PropstatWrapper<String>, PropstatWrapper<String>>, R::Error> { ) -> Result<MultistatusElement<PropstatWrapper<String>, PropstatWrapper<String>>, R::Error> {
let path_components = path.into_inner(); let path_components = path.into_inner();
let href = req.path().to_owned(); let href = req.path().to_owned();
@@ -75,7 +75,7 @@ pub async fn route_proppatch<A: CheckAuthentication, R: ResourceService>(
}) })
.collect(); .collect();
let mut resource = resource_service.get_resource(auth.inner.user_id).await?; let mut resource = resource_service.get_resource(user.id).await?;
let mut props_ok = Vec::new(); let mut props_ok = Vec::new();
let mut props_conflict = Vec::new(); let mut props_conflict = Vec::new();

View File

@@ -3,8 +3,6 @@ name = "rustical_store"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
anyhow = { version = "1.0", features = ["backtrace"] } anyhow = { version = "1.0", features = ["backtrace"] }
async-trait = "0.1" async-trait = "0.1"
@@ -27,3 +25,6 @@ lazy_static = "1.5"
rstest = "0.23" rstest = "0.23"
rstest_reuse = "0.7" rstest_reuse = "0.7"
thiserror = "1.0" thiserror = "1.0"
password-auth = "1.0"
actix-web = "4.9"
actix-web-httpauth = "0.8"

View File

@@ -0,0 +1,90 @@
use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
error::ErrorUnauthorized,
http::header::Header,
HttpMessage,
};
use actix_web_httpauth::headers::authorization::{Authorization, Basic};
use std::{
future::{ready, Future, Ready},
pin::Pin,
sync::Arc,
};
use super::AuthenticationProvider;
pub struct AuthenticationMiddleware<AP: AuthenticationProvider> {
auth_provider: Arc<AP>,
}
impl<AP: AuthenticationProvider> AuthenticationMiddleware<AP> {
pub fn new(auth_provider: Arc<AP>) -> Self {
Self { auth_provider }
}
}
impl<AP: AuthenticationProvider, S, B> Transform<S, ServiceRequest> for AuthenticationMiddleware<AP>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
S::Future: 'static,
B: 'static,
AP: 'static,
{
type Error = actix_web::Error;
type Response = ServiceResponse<B>;
type InitError = ();
type Transform = InnerAuthenticationMiddleware<S, AP>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(InnerAuthenticationMiddleware {
service: Arc::new(service),
auth_provider: Arc::clone(&self.auth_provider),
}))
}
}
pub struct InnerAuthenticationMiddleware<S, AP: AuthenticationProvider> {
service: Arc<S>,
auth_provider: Arc<AP>,
}
impl<S, B, AP> Service<ServiceRequest> for InnerAuthenticationMiddleware<S, AP>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
S::Future: 'static,
AP: AuthenticationProvider + 'static,
{
type Response = ServiceResponse<B>;
type Error = actix_web::Error;
// type Future = Pin<Box<dyn Future<Output>>>;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let service = Arc::clone(&self.service);
let auth_provider = Arc::clone(&self.auth_provider);
Box::pin(async move {
if let Ok(auth) = Authorization::<Basic>::parse(req.request()) {
let user_id = auth.as_ref().user_id();
let password = auth
.as_ref()
.password()
.ok_or(ErrorUnauthorized("no password"))?;
let user = auth_provider
.validate_user_token(user_id, password)
.await
.map_err(|_| ErrorUnauthorized(""))?
.ok_or(ErrorUnauthorized(""))?;
req.extensions_mut().insert(user);
service.call(req).await
} else {
Err(ErrorUnauthorized(""))
}
})
}
}

View File

@@ -0,0 +1,16 @@
pub mod middleware;
pub mod static_user_store;
pub mod user;
pub mod user_store;
use crate::error::Error;
use async_trait::async_trait;
#[async_trait]
pub trait AuthenticationProvider {
async fn validate_user_token(&self, user_id: &str, token: &str) -> Result<Option<User>, Error>;
}
pub use middleware::AuthenticationMiddleware;
pub use static_user_store::{StaticUserStore, StaticUserStoreConfig};
pub use user::User;

View File

@@ -0,0 +1,43 @@
use crate::{auth::User, error::Error};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::AuthenticationProvider;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StaticUserStoreConfig {
users: Vec<User>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StaticUserStore {
pub users: HashMap<String, User>,
}
impl StaticUserStore {
pub fn new(config: StaticUserStoreConfig) -> Self {
Self {
users: HashMap::from_iter(config.users.into_iter().map(|user| (user.id.clone(), user))),
}
}
}
#[async_trait]
impl AuthenticationProvider for StaticUserStore {
async fn validate_user_token(&self, user_id: &str, token: &str) -> Result<Option<User>, Error> {
let user: User = match self.users.get(user_id) {
Some(user) => user.clone(),
None => return Ok(None),
};
let password = match &user.password {
Some(password) => password,
None => return Ok(None),
};
Ok(password_auth::verify_password(token, password)
.map(|()| user)
.ok())
}
}

View File

@@ -0,0 +1,27 @@
use actix_web::{error::ErrorUnauthorized, FromRequest, HttpMessage};
use serde::{Deserialize, Serialize};
use std::future::{ready, Ready};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct User {
pub id: String,
pub displayname: Option<String>,
pub password: Option<String>,
}
impl FromRequest for User {
type Error = actix_web::Error;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(
req: &actix_web::HttpRequest,
_payload: &mut actix_web::dev::Payload,
) -> Self::Future {
ready(
req.extensions()
.get::<User>()
.cloned()
.ok_or(ErrorUnauthorized("")),
)
}
}

View File

@@ -0,0 +1,8 @@
use crate::{auth::User, error::Error};
use async_trait::async_trait;
#[async_trait]
pub trait UserStore: Send + Sync + 'static {
async fn get_user(&self, id: &str) -> Result<Option<User>, Error>;
async fn put_user(&self, user: User) -> Result<(), Error>;
}

View File

@@ -5,4 +5,4 @@ pub mod sqlite_store;
pub mod timestamp; pub mod timestamp;
pub use calendar_store::CalendarStore; pub use calendar_store::CalendarStore;
pub use error::Error; pub use error::Error;
pub mod auth;

View File

@@ -2,15 +2,15 @@ use actix_web::body::MessageBody;
use actix_web::dev::{ServiceFactory, ServiceRequest, ServiceResponse}; use actix_web::dev::{ServiceFactory, ServiceRequest, ServiceResponse};
use actix_web::middleware::{Logger, NormalizePath}; use actix_web::middleware::{Logger, NormalizePath};
use actix_web::{web, App}; use actix_web::{web, App};
use rustical_auth::CheckAuthentication;
use rustical_frontend::configure_frontend; use rustical_frontend::configure_frontend;
use rustical_store::auth::{AuthenticationMiddleware, AuthenticationProvider};
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock; use tokio::sync::RwLock;
pub fn make_app<CS: CalendarStore + ?Sized, A: CheckAuthentication>( pub fn make_app<CS: CalendarStore + ?Sized, AP: AuthenticationProvider + 'static>(
cal_store: Arc<RwLock<CS>>, cal_store: Arc<RwLock<CS>>,
auth: Arc<A>, auth_provider: Arc<AP>,
) -> App< ) -> App<
impl ServiceFactory< impl ServiceFactory<
ServiceRequest, ServiceRequest,
@@ -23,17 +23,14 @@ pub fn make_app<CS: CalendarStore + ?Sized, A: CheckAuthentication>(
App::new() App::new()
.wrap(Logger::new("[%s] %r")) .wrap(Logger::new("[%s] %r"))
.wrap(NormalizePath::trim()) .wrap(NormalizePath::trim())
.wrap(AuthenticationMiddleware::new(auth_provider))
.service(web::scope("/caldav").configure(|cfg| { .service(web::scope("/caldav").configure(|cfg| {
rustical_caldav::configure_dav( rustical_caldav::configure_dav(cfg, "/caldav".to_string(), cal_store.clone())
cfg,
"/caldav".to_string(),
auth.clone(),
cal_store.clone(),
)
}))
.service(web::scope("/carddav").configure(|cfg| {
rustical_carddav::configure_dav(cfg, "/carddav".to_string(), auth.clone())
})) }))
.service(
web::scope("/carddav")
.configure(|cfg| rustical_carddav::configure_dav(cfg, "/carddav".to_string())),
)
.service( .service(
web::scope("/.well-known") web::scope("/.well-known")
.configure(|cfg| rustical_caldav::configure_well_known(cfg, "/caldav".to_string())), // .configure(|cfg| { .configure(|cfg| rustical_caldav::configure_well_known(cfg, "/caldav".to_string())), // .configure(|cfg| {

View File

@@ -1,4 +1,5 @@
use rustical_auth::{AuthProvider, HtpasswdAuthConfig}; use rustical_frontend::FrontendConfig;
use rustical_store::auth::StaticUserStoreConfig;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
@@ -21,19 +22,7 @@ pub enum CalendarStoreConfig {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "backend", rename_all = "snake_case")] #[serde(tag = "backend", rename_all = "snake_case")]
pub enum AuthConfig { pub enum AuthConfig {
Htpasswd(HtpasswdAuthConfig), Static(StaticUserStoreConfig),
None,
}
impl From<AuthConfig> for AuthProvider {
fn from(value: AuthConfig) -> Self {
match value {
AuthConfig::Htpasswd(config) => {
Self::Htpasswd(rustical_auth::htpasswd::HtpasswdAuth { config })
}
AuthConfig::None => Self::None(rustical_auth::none::NoneAuth),
}
}
} }
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
@@ -41,4 +30,5 @@ pub struct Config {
pub calendar_store: CalendarStoreConfig, pub calendar_store: CalendarStoreConfig,
pub auth: AuthConfig, pub auth: AuthConfig,
pub http: HttpConfig, pub http: HttpConfig,
pub frontend: FrontendConfig,
} }

View File

@@ -4,7 +4,7 @@ use anyhow::Result;
use app::make_app; use app::make_app;
use clap::Parser; use clap::Parser;
use config::{CalendarStoreConfig, SqliteCalendarStoreConfig}; use config::{CalendarStoreConfig, SqliteCalendarStoreConfig};
use rustical_auth::AuthProvider; use rustical_store::auth::StaticUserStore;
use rustical_store::sqlite_store::{create_db_pool, SqliteCalendarStore}; use rustical_store::sqlite_store::{create_db_pool, SqliteCalendarStore};
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use std::fs; use std::fs;
@@ -45,9 +45,11 @@ async fn main() -> Result<()> {
let cal_store = get_cal_store(args.migrate, &config.calendar_store).await?; let cal_store = get_cal_store(args.migrate, &config.calendar_store).await?;
let auth: Arc<AuthProvider> = Arc::new(config.auth.into()); let user_store = Arc::new(match config.auth {
config::AuthConfig::Static(config) => StaticUserStore::new(config),
});
HttpServer::new(move || make_app(cal_store.clone(), auth.clone())) HttpServer::new(move || make_app(cal_store.clone(), user_store.clone()))
.bind((config.http.host, config.http.port))? .bind((config.http.host, config.http.port))?
.run() .run()
.await?; .await?;