Add explicit error type to propfind resources

This commit is contained in:
Lennart
2024-06-01 13:58:43 +02:00
parent 1d763b5c8f
commit bee4675f82
8 changed files with 97 additions and 41 deletions

View File

@@ -1,8 +1,8 @@
use crate::Error;
use actix_web::{web::Data, HttpRequest}; use actix_web::{web::Data, HttpRequest};
use anyhow::{anyhow, Result}; use anyhow::anyhow;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use rustical_dav::error::Error;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
use rustical_dav::xml_snippets::{HrefElement, TextNode}; use rustical_dav::xml_snippets::{HrefElement, TextNode};
use rustical_store::calendar::Calendar; use rustical_store::calendar::Calendar;
@@ -166,8 +166,13 @@ pub struct CalendarFile {
impl Resource for CalendarFile { impl Resource for CalendarFile {
type PropType = CalendarProp; type PropType = CalendarProp;
type PropResponse = CalendarPropResponse; type PropResponse = CalendarPropResponse;
type Error = Error;
fn get_prop(&self, prefix: &str, prop: Self::PropType) -> Result<Self::PropResponse> { fn get_prop(
&self,
prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error> {
match prop { match prop {
CalendarProp::Resourcetype => { CalendarProp::Resourcetype => {
Ok(CalendarPropResponse::Resourcetype(Resourcetype::default())) Ok(CalendarPropResponse::Resourcetype(Resourcetype::default()))
@@ -220,8 +225,9 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResource<C> {
type MemberType = CalendarFile; type MemberType = CalendarFile;
type PathComponents = (String, String); // principal, calendar_id type PathComponents = (String, String); // principal, calendar_id
type File = CalendarFile; type File = CalendarFile;
type Error = Error;
async fn get_file(&self) -> Result<Self::File> { async fn get_file(&self) -> Result<Self::File, Error> {
let calendar = self let calendar = self
.cal_store .cal_store
.read() .read()
@@ -236,7 +242,10 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResource<C> {
}) })
} }
async fn get_members(&self, _auth_info: AuthInfo) -> Result<Vec<Self::MemberType>> { async fn get_members(
&self,
_auth_info: AuthInfo,
) -> Result<Vec<Self::MemberType>, Self::Error> {
// As of now the calendar resource has no members since events are shown with REPORT // As of now the calendar resource has no members since events are shown with REPORT
Ok(vec![]) Ok(vec![])
} }
@@ -245,7 +254,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResource<C> {
req: HttpRequest, req: HttpRequest,
auth_info: AuthInfo, auth_info: AuthInfo,
path_components: Self::PathComponents, path_components: Self::PathComponents,
) -> Result<Self, rustical_dav::error::Error> { ) -> Result<Self, Self::Error> {
let cal_store = req let cal_store = req
.app_data::<Data<RwLock<C>>>() .app_data::<Data<RwLock<C>>>()
.ok_or(anyhow!("no calendar store in app_data!"))? .ok_or(anyhow!("no calendar store in app_data!"))?

View File

@@ -5,6 +5,9 @@ pub enum Error {
#[error("Unauthorized")] #[error("Unauthorized")]
Unauthorized, Unauthorized,
#[error("Not Found")]
NotFound,
#[error("Not implemented")] #[error("Not implemented")]
NotImplemented, NotImplemented,
@@ -33,6 +36,7 @@ impl actix_web::ResponseError for Error {
Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST, Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR, Error::NotImplemented => StatusCode::INTERNAL_SERVER_ERROR,
Error::Other(_) => StatusCode::INTERNAL_SERVER_ERROR, Error::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
Error::NotFound => StatusCode::NOT_FOUND,
} }
} }
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {

View File

@@ -1,8 +1,8 @@
use crate::Error;
use actix_web::{web::Data, HttpRequest}; use actix_web::{web::Data, HttpRequest};
use anyhow::{anyhow, Result}; use anyhow::anyhow;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use rustical_dav::error::Error;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
use rustical_dav::xml_snippets::TextNode; use rustical_dav::xml_snippets::TextNode;
use rustical_store::event::Event; use rustical_store::event::Event;
@@ -43,12 +43,17 @@ pub struct EventFile {
impl Resource for EventFile { impl Resource for EventFile {
type PropType = EventProp; type PropType = EventProp;
type PropResponse = PrincipalPropResponse; type PropResponse = PrincipalPropResponse;
type Error = Error;
fn get_path(&self) -> &str { fn get_path(&self) -> &str {
&self.path &self.path
} }
fn get_prop(&self, _prefix: &str, prop: Self::PropType) -> Result<Self::PropResponse> { fn get_prop(
&self,
_prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error> {
match prop { match prop {
EventProp::Getetag => Ok(PrincipalPropResponse::Getetag(TextNode(Some( EventProp::Getetag => Ok(PrincipalPropResponse::Getetag(TextNode(Some(
self.event.get_etag(), self.event.get_etag(),
@@ -68,8 +73,12 @@ impl<C: CalendarStore + ?Sized> ResourceService for EventResource<C> {
type PathComponents = (String, String, String); // principal, calendar, event type PathComponents = (String, String, String); // principal, calendar, event
type File = EventFile; type File = EventFile;
type MemberType = EventFile; type MemberType = EventFile;
type Error = Error;
async fn get_members(&self, _auth_info: AuthInfo) -> Result<Vec<Self::MemberType>> { async fn get_members(
&self,
_auth_info: AuthInfo,
) -> Result<Vec<Self::MemberType>, Self::Error> {
Ok(vec![]) Ok(vec![])
} }
@@ -77,7 +86,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for EventResource<C> {
req: HttpRequest, req: HttpRequest,
_auth_info: AuthInfo, _auth_info: AuthInfo,
path_components: Self::PathComponents, path_components: Self::PathComponents,
) -> Result<Self, Error> { ) -> Result<Self, Self::Error> {
let (_principal, cid, uid) = path_components; let (_principal, cid, uid) = path_components;
let cal_store = req let cal_store = req
@@ -94,7 +103,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for EventResource<C> {
}) })
} }
async fn get_file(&self) -> Result<Self::File> { async fn get_file(&self) -> Result<Self::File, Self::Error> {
let event = self let event = self
.cal_store .cal_store
.read() .read()

View File

@@ -1,14 +1,14 @@
use std::sync::Arc; use crate::Error;
use actix_web::web::Data; use actix_web::web::Data;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use anyhow::{anyhow, Result}; use anyhow::anyhow;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
use rustical_dav::xml_snippets::HrefElement; use rustical_dav::xml_snippets::HrefElement;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use serde::Serialize; use serde::Serialize;
use std::sync::Arc;
use strum::{EnumString, IntoStaticStr, VariantNames}; use strum::{EnumString, IntoStaticStr, VariantNames};
use tokio::sync::RwLock; use tokio::sync::RwLock;
@@ -60,8 +60,13 @@ pub enum PrincipalProp {
impl Resource for PrincipalFile { impl Resource for PrincipalFile {
type PropType = PrincipalProp; type PropType = PrincipalProp;
type PropResponse = PrincipalPropResponse; type PropResponse = PrincipalPropResponse;
type Error = Error;
fn get_prop(&self, prefix: &str, prop: Self::PropType) -> Result<Self::PropResponse> { fn get_prop(
&self,
prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error> {
match prop { match prop {
PrincipalProp::Resourcetype => { PrincipalProp::Resourcetype => {
Ok(PrincipalPropResponse::Resourcetype(Resourcetype::default())) Ok(PrincipalPropResponse::Resourcetype(Resourcetype::default()))
@@ -93,14 +98,15 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResource<C> {
type PathComponents = (String,); type PathComponents = (String,);
type MemberType = CalendarFile; type MemberType = CalendarFile;
type File = PrincipalFile; type File = PrincipalFile;
type Error = Error;
async fn new( async fn new(
req: HttpRequest, req: HttpRequest,
auth_info: AuthInfo, auth_info: AuthInfo,
(principal,): Self::PathComponents, (principal,): Self::PathComponents,
) -> Result<Self, rustical_dav::error::Error> { ) -> Result<Self, Self::Error> {
if auth_info.user_id != principal { if auth_info.user_id != principal {
return Err(rustical_dav::error::Error::Unauthorized); return Err(Error::Unauthorized);
} }
let cal_store = req let cal_store = req
.app_data::<Data<RwLock<C>>>() .app_data::<Data<RwLock<C>>>()
@@ -115,14 +121,17 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResource<C> {
}) })
} }
async fn get_file(&self) -> Result<Self::File> { async fn get_file(&self) -> Result<Self::File, Self::Error> {
Ok(PrincipalFile { Ok(PrincipalFile {
principal: self.principal.to_owned(), principal: self.principal.to_owned(),
path: self.path.to_owned(), path: self.path.to_owned(),
}) })
} }
async fn get_members(&self, _auth_info: AuthInfo) -> Result<Vec<Self::MemberType>> { async fn get_members(
&self,
_auth_info: AuthInfo,
) -> Result<Vec<Self::MemberType>, Self::Error> {
let calendars = self let calendars = self
.cal_store .cal_store
.read() .read()

View File

@@ -1,8 +1,8 @@
use crate::Error;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use rustical_dav::error::Error;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
use rustical_dav::xml_snippets::HrefElement; use rustical_dav::xml_snippets::HrefElement;
use serde::Serialize; use serde::Serialize;
@@ -41,8 +41,13 @@ pub struct RootFile {
impl Resource for RootFile { impl Resource for RootFile {
type PropType = RootProp; type PropType = RootProp;
type PropResponse = RootPropResponse; type PropResponse = RootPropResponse;
type Error = Error;
fn get_prop(&self, prefix: &str, prop: Self::PropType) -> Result<Self::PropResponse> { fn get_prop(
&self,
prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error> {
match prop { match prop {
RootProp::Resourcetype => Ok(RootPropResponse::Resourcetype(Resourcetype::default())), RootProp::Resourcetype => Ok(RootPropResponse::Resourcetype(Resourcetype::default())),
RootProp::CurrentUserPrincipal => Ok(RootPropResponse::CurrentUserPrincipal( RootProp::CurrentUserPrincipal => Ok(RootPropResponse::CurrentUserPrincipal(
@@ -61,8 +66,12 @@ impl ResourceService for RootResource {
type PathComponents = (); type PathComponents = ();
type MemberType = RootFile; type MemberType = RootFile;
type File = RootFile; type File = RootFile;
type Error = Error;
async fn get_members(&self, _auth_info: AuthInfo) -> Result<Vec<Self::MemberType>> { async fn get_members(
&self,
_auth_info: AuthInfo,
) -> Result<Vec<Self::MemberType>, Self::Error> {
Ok(vec![]) Ok(vec![])
} }
@@ -70,14 +79,14 @@ impl ResourceService for RootResource {
req: HttpRequest, req: HttpRequest,
auth_info: AuthInfo, auth_info: AuthInfo,
_path_components: Self::PathComponents, _path_components: Self::PathComponents,
) -> Result<Self, Error> { ) -> Result<Self, Self::Error> {
Ok(Self { Ok(Self {
principal: auth_info.user_id, principal: auth_info.user_id,
path: req.path().to_string(), path: req.path().to_string(),
}) })
} }
async fn get_file(&self) -> Result<Self::File> { async fn get_file(&self) -> Result<Self::File, Self::Error> {
Ok(RootFile { Ok(RootFile {
path: self.path.to_owned(), path: self.path.to_owned(),
principal: self.principal.to_owned(), principal: self.principal.to_owned(),

View File

@@ -13,6 +13,8 @@ pub enum Error {
Unauthorized, Unauthorized,
#[error("Internal server error :(")] #[error("Internal server error :(")]
InternalError, InternalError,
#[error(transparent)]
XmlDecodeError(#[from] quick_xml::DeError),
#[error("Internal server error")] #[error("Internal server error")]
Other(#[from] anyhow::Error), Other(#[from] anyhow::Error),
} }
@@ -25,6 +27,7 @@ impl actix_web::error::ResponseError for Error {
Self::NotFound => StatusCode::NOT_FOUND, Self::NotFound => StatusCode::NOT_FOUND,
Self::BadRequest => StatusCode::BAD_REQUEST, Self::BadRequest => StatusCode::BAD_REQUEST,
Self::Unauthorized => StatusCode::UNAUTHORIZED, Self::Unauthorized => StatusCode::UNAUTHORIZED,
Self::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
} }
} }

View File

@@ -3,6 +3,7 @@ use crate::namespace::Namespace;
use crate::resource::HandlePropfind; use crate::resource::HandlePropfind;
use crate::resource::ResourceService; use crate::resource::ResourceService;
use crate::xml::tag_list::TagList; use crate::xml::tag_list::TagList;
use crate::Error;
use actix_web::http::header::ContentType; use actix_web::http::header::ContentType;
use actix_web::web::{Data, Path}; use actix_web::web::{Data, Path};
use actix_web::{HttpRequest, HttpResponse}; use actix_web::{HttpRequest, HttpResponse};
@@ -58,21 +59,22 @@ pub async fn route_propfind<A: CheckAuthentication, R: ResourceService + ?Sized>
prefix: Data<ServicePrefix>, prefix: Data<ServicePrefix>,
auth: AuthInfoExtractor<A>, auth: AuthInfoExtractor<A>,
depth: Depth, depth: Depth,
) -> Result<HttpResponse, crate::error::Error> { ) -> Result<HttpResponse, R::Error> {
let auth_info = auth.inner; let auth_info = auth.inner;
let prefix = prefix.0.to_owned(); let prefix = prefix.0.to_owned();
let path_components = path.into_inner(); let path_components = path.into_inner();
let resource_service = R::new(req, auth_info.clone(), path_components.clone()).await?; let resource_service = R::new(req, auth_info.clone(), path_components.clone()).await?;
let propfind: PropfindElement = quick_xml::de::from_str(&body).unwrap(); let propfind: PropfindElement =
quick_xml::de::from_str(&body).map_err(Error::XmlDecodeError)?;
let props = match propfind.prop { let props = match propfind.prop {
PropfindType::Allprop => { PropfindType::Allprop => {
vec!["allprop".to_owned()] vec!["allprop".to_owned()]
} }
PropfindType::Propname => { PropfindType::Propname => {
// TODO: Implement // TODO: Implement
return Err(crate::error::Error::InternalError); return Err(Error::InternalError.into());
} }
PropfindType::Prop(PropElement { prop: prop_tags }) => prop_tags.into(), PropfindType::Prop(PropElement { prop: prop_tags }) => prop_tags.into(),
}; };

View File

@@ -1,6 +1,6 @@
use crate::{error::Error, xml::tag_list::TagList}; use crate::xml::tag_list::TagList;
use actix_web::{http::StatusCode, HttpRequest}; use actix_web::{http::StatusCode, HttpRequest, ResponseError};
use anyhow::{anyhow, Result}; use anyhow::anyhow;
use async_trait::async_trait; use async_trait::async_trait;
use itertools::Itertools; use itertools::Itertools;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
@@ -12,12 +12,17 @@ use strum::VariantNames;
pub trait Resource { pub trait Resource {
type PropType: FromStr + VariantNames + Clone; type PropType: FromStr + VariantNames + Clone;
type PropResponse: Serialize; type PropResponse: Serialize;
type Error: ResponseError + From<crate::Error> + From<anyhow::Error>;
fn list_dead_props() -> &'static [&'static str] { fn list_dead_props() -> &'static [&'static str] {
Self::PropType::VARIANTS Self::PropType::VARIANTS
} }
fn get_prop(&self, prefix: &str, prop: Self::PropType) -> Result<Self::PropResponse>; fn get_prop(
&self,
prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error>;
fn get_path(&self) -> &str; fn get_path(&self) -> &str;
} }
@@ -28,19 +33,20 @@ pub trait Resource {
// A resource exists // A resource exists
#[async_trait(?Send)] #[async_trait(?Send)]
pub trait ResourceService: Sized { pub trait ResourceService: Sized {
type MemberType: Resource; type MemberType: Resource<Error = Self::Error>;
type PathComponents: Sized + Clone; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String) type PathComponents: Sized + Clone; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
type File: Resource; type File: Resource<Error = Self::Error>;
type Error: ResponseError + From<crate::Error> + From<anyhow::Error>;
async fn new( async fn new(
req: HttpRequest, req: HttpRequest,
auth_info: AuthInfo, auth_info: AuthInfo,
path_components: Self::PathComponents, path_components: Self::PathComponents,
) -> Result<Self, Error>; ) -> Result<Self, Self::Error>;
async fn get_file(&self) -> Result<Self::File>; async fn get_file(&self) -> Result<Self::File, Self::Error>;
async fn get_members(&self, auth_info: AuthInfo) -> Result<Vec<Self::MemberType>>; async fn get_members(&self, auth_info: AuthInfo) -> Result<Vec<Self::MemberType>, Self::Error>;
} }
#[derive(Serialize)] #[derive(Serialize)]
@@ -72,21 +78,26 @@ enum PropstatType<T1: Serialize, T2: Serialize> {
#[async_trait(?Send)] #[async_trait(?Send)]
pub trait HandlePropfind { pub trait HandlePropfind {
async fn propfind(&self, prefix: &str, props: Vec<&str>) -> Result<impl Serialize>; type Error: ResponseError + From<crate::Error> + From<anyhow::Error>;
async fn propfind(&self, prefix: &str, props: Vec<&str>)
-> Result<impl Serialize, Self::Error>;
} }
#[async_trait(?Send)] #[async_trait(?Send)]
impl<R: Resource> HandlePropfind for R { impl<R: Resource> HandlePropfind for R {
type Error = R::Error;
async fn propfind( async fn propfind(
&self, &self,
prefix: &str, prefix: &str,
props: Vec<&str>, props: Vec<&str>,
) -> Result<PropstatResponseElement<PropWrapper<Vec<R::PropResponse>>, TagList>> { ) -> Result<PropstatResponseElement<PropWrapper<Vec<R::PropResponse>>, TagList>, R::Error> {
let mut props = props; let mut props = props;
if props.contains(&"propname") { if props.contains(&"propname") {
if props.len() != 1 { if props.len() != 1 {
// propname MUST be the only queried prop per spec // propname MUST be the only queried prop per spec
return Err(anyhow!("propname MUST be the only queried prop")); return Err(anyhow!("propname MUST be the only queried prop").into());
} }
// TODO: implement propname // TODO: implement propname
props = R::list_dead_props().into(); props = R::list_dead_props().into();
@@ -94,7 +105,7 @@ impl<R: Resource> HandlePropfind for R {
if props.contains(&"allprop") { if props.contains(&"allprop") {
if props.len() != 1 { if props.len() != 1 {
// allprop MUST be the only queried prop per spec // allprop MUST be the only queried prop per spec
return Err(anyhow!("allprop MUST be the only queried prop")); return Err(anyhow!("allprop MUST be the only queried prop").into());
} }
props = R::list_dead_props().into(); props = R::list_dead_props().into();
} }