Remove all that extension business and replace with internal properties

This commit is contained in:
Lennart
2024-11-05 17:22:48 +01:00
parent 4da0ca34c7
commit d5ef6669a6
21 changed files with 176 additions and 264 deletions

View File

@@ -10,7 +10,7 @@ use actix_web::{
}; };
use rustical_dav::{ use rustical_dav::{
methods::propfind::{PropElement, PropfindType}, methods::propfind::{PropElement, PropfindType},
resource::Resource, resource::{CommonPropertiesProp, EitherProp, Resource},
xml::{ xml::{
multistatus::{PropstatWrapper, ResponseElement}, multistatus::{PropstatWrapper, ResponseElement},
MultistatusElement, MultistatusElement,
@@ -69,7 +69,13 @@ pub async fn handle_calendar_multiget<C: CalendarStore + ?Sized>(
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
cal_store: &C, cal_store: &C,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<
MultistatusElement<
PropstatWrapper<EitherProp<CalendarObjectProp, CommonPropertiesProp>>,
String,
>,
Error,
> {
let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap(); let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap();
let (objects, not_found) = let (objects, not_found) =
get_objects_calendar_multiget(&cal_multiget, &principal_url, principal, cal_id, cal_store) get_objects_calendar_multiget(&cal_multiget, &principal_url, principal, cal_id, cal_store)

View File

@@ -2,7 +2,7 @@ use actix_web::HttpRequest;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use rustical_dav::{ use rustical_dav::{
methods::propfind::{PropElement, PropfindType}, methods::propfind::{PropElement, PropfindType},
resource::Resource, resource::{CommonPropertiesProp, EitherProp, Resource},
xml::{multistatus::PropstatWrapper, MultistatusElement}, xml::{multistatus::PropstatWrapper, MultistatusElement},
}; };
use rustical_store::{auth::User, CalendarObject, CalendarStore}; use rustical_store::{auth::User, CalendarObject, CalendarStore};
@@ -210,7 +210,13 @@ pub async fn handle_calendar_query<C: CalendarStore + ?Sized>(
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
cal_store: &C, cal_store: &C,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<
MultistatusElement<
PropstatWrapper<EitherProp<CalendarObjectProp, CommonPropertiesProp>>,
String,
>,
Error,
> {
let objects = get_objects_calendar_query(&cal_query, principal, cal_id, cal_store).await?; let objects = get_objects_calendar_query(&cal_query, principal, cal_id, cal_store).await?;
let props = match cal_query.prop { let props = match cal_query.prop {

View File

@@ -1,7 +1,7 @@
use actix_web::{http::StatusCode, HttpRequest}; use actix_web::{http::StatusCode, HttpRequest};
use rustical_dav::{ use rustical_dav::{
methods::propfind::{PropElement, PropfindType}, methods::propfind::{PropElement, PropfindType},
resource::Resource, resource::{CommonPropertiesProp, EitherProp, Resource},
xml::{ xml::{
multistatus::{PropstatWrapper, ResponseElement}, multistatus::{PropstatWrapper, ResponseElement},
MultistatusElement, MultistatusElement,
@@ -49,7 +49,13 @@ pub async fn handle_sync_collection<C: CalendarStore + ?Sized>(
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
cal_store: &C, cal_store: &C,
) -> Result<MultistatusElement<PropstatWrapper<CalendarObjectProp>, String>, Error> { ) -> Result<
MultistatusElement<
PropstatWrapper<EitherProp<CalendarObjectProp, CommonPropertiesProp>>,
String,
>,
Error,
> {
let props = match sync_collection.prop { let props = match sync_collection.prop {
PropfindType::Allprop => { PropfindType::Allprop => {
vec!["allprop".to_owned()] vec!["allprop".to_owned()]

View File

@@ -13,7 +13,6 @@ use actix_web::web;
use actix_web::{web::Data, HttpRequest}; use actix_web::{web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::extensions::CommonPropertiesProp;
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
use rustical_store::auth::User; use rustical_store::auth::User;
@@ -46,7 +45,7 @@ pub enum CalendarPropName {
Getctag, Getctag,
} }
#[derive(Default, Deserialize, Serialize, From, PartialEq)] #[derive(Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum CalendarProp { pub enum CalendarProp {
// WebDAV (RFC 2518) // WebDAV (RFC 2518)
@@ -83,10 +82,6 @@ pub enum CalendarProp {
// Didn't find the spec // Didn't find the spec
Getctag(String), Getctag(String),
#[serde(skip_deserializing, rename = "$value")]
#[from]
ExtCommonProperties(CommonPropertiesProp),
#[serde(other)] #[serde(other)]
#[default] #[default]
Invalid, Invalid,
@@ -183,7 +178,6 @@ impl Resource for CalendarResource {
CalendarProp::SyncToken(_) => Err(rustical_dav::Error::PropReadOnly), CalendarProp::SyncToken(_) => Err(rustical_dav::Error::PropReadOnly),
CalendarProp::Getctag(_) => Err(rustical_dav::Error::PropReadOnly), CalendarProp::Getctag(_) => Err(rustical_dav::Error::PropReadOnly),
CalendarProp::Invalid => Err(rustical_dav::Error::PropReadOnly), CalendarProp::Invalid => Err(rustical_dav::Error::PropReadOnly),
_ => panic!("we shouldn't end up here"),
} }
} }

View File

@@ -4,7 +4,6 @@ use actix_web::{dev::ResourceMap, web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::{ use rustical_dav::{
extensions::CommonPropertiesProp,
privileges::UserPrivilegeSet, privileges::UserPrivilegeSet,
resource::{Resource, ResourceService}, resource::{Resource, ResourceService},
}; };
@@ -28,7 +27,7 @@ pub enum CalendarObjectPropName {
Getcontenttype, Getcontenttype,
} }
#[derive(Default, Deserialize, Serialize, From, PartialEq)] #[derive(Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum CalendarObjectProp { pub enum CalendarObjectProp {
// WebDAV (RFC 2518) // WebDAV (RFC 2518)
@@ -39,10 +38,6 @@ pub enum CalendarObjectProp {
#[serde(rename = "C:calendar-data")] #[serde(rename = "C:calendar-data")]
CalendarData(String), CalendarData(String),
#[serde(skip_deserializing, rename = "$value")]
#[from]
ExtCommonProperties(CommonPropertiesProp),
#[serde(other)] #[serde(other)]
#[default] #[default]
Invalid, Invalid,

View File

@@ -1,4 +1,5 @@
use actix_web::{http::StatusCode, HttpResponse}; use actix_web::{http::StatusCode, HttpResponse};
use tracing::error;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
@@ -41,6 +42,7 @@ impl actix_web::ResponseError for Error {
} }
} }
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
error!("Error: {self}");
match self { match self {
Error::DavError(err) => err.error_response(), Error::DavError(err) => err.error_response(),
_ => HttpResponse::build(self.status_code()).body(self.to_string()), _ => HttpResponse::build(self.status_code()).body(self.to_string()),

View File

@@ -4,8 +4,6 @@ use actix_web::dev::ResourceMap;
use actix_web::web::Data; use actix_web::web::Data;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::From;
use rustical_dav::extensions::CommonPropertiesProp;
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
use rustical_dav::xml::HrefElement; use rustical_dav::xml::HrefElement;
@@ -25,7 +23,7 @@ pub struct PrincipalResource {
principal: String, principal: String,
} }
#[derive(Default, Deserialize, Serialize, From, PartialEq)] #[derive(Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum PrincipalProp { pub enum PrincipalProp {
// WebDAV Access Control (RFC 3744) // WebDAV Access Control (RFC 3744)
@@ -38,10 +36,6 @@ pub enum PrincipalProp {
#[serde(rename = "C:calendar-user-address-set")] #[serde(rename = "C:calendar-user-address-set")]
CalendarUserAddressSet(HrefElement), CalendarUserAddressSet(HrefElement),
#[serde(skip_deserializing, rename = "$value")]
#[from]
ExtCommonProperties(CommonPropertiesProp),
#[serde(other)] #[serde(other)]
#[default] #[default]
Invalid, Invalid,

View File

@@ -3,7 +3,6 @@ use actix_web::{dev::ResourceMap, web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::{ use rustical_dav::{
extensions::CommonPropertiesProp,
privileges::UserPrivilegeSet, privileges::UserPrivilegeSet,
resource::{Resource, ResourceService}, resource::{Resource, ResourceService},
}; };
@@ -29,7 +28,7 @@ pub enum AddressObjectPropName {
Getcontenttype, Getcontenttype,
} }
#[derive(Default, Deserialize, Serialize, From, PartialEq)] #[derive(Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum AddressObjectProp { pub enum AddressObjectProp {
// WebDAV (RFC 2518) // WebDAV (RFC 2518)
@@ -40,10 +39,6 @@ pub enum AddressObjectProp {
#[serde(rename = "CARD:address-data")] #[serde(rename = "CARD:address-data")]
AddressData(String), AddressData(String),
#[serde(skip_deserializing, rename = "$value")]
#[from]
ExtCommonProperties(CommonPropertiesProp),
#[serde(other)] #[serde(other)]
#[default] #[default]
Invalid, Invalid,

View File

@@ -10,7 +10,7 @@ use actix_web::{
}; };
use rustical_dav::{ use rustical_dav::{
methods::propfind::{PropElement, PropfindType}, methods::propfind::{PropElement, PropfindType},
resource::Resource, resource::{CommonPropertiesProp, EitherProp, Resource},
xml::{ xml::{
multistatus::{PropstatWrapper, ResponseElement}, multistatus::{PropstatWrapper, ResponseElement},
MultistatusElement, MultistatusElement,
@@ -68,7 +68,13 @@ pub async fn handle_addressbook_multiget<AS: AddressbookStore + ?Sized>(
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
addr_store: &AS, addr_store: &AS,
) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> { ) -> Result<
MultistatusElement<
PropstatWrapper<EitherProp<AddressObjectProp, CommonPropertiesProp>>,
String,
>,
Error,
> {
let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap(); let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap();
let (objects, not_found) = get_objects_addressbook_multiget( let (objects, not_found) = get_objects_addressbook_multiget(
&addr_multiget, &addr_multiget,

View File

@@ -5,7 +5,7 @@ use crate::{
use actix_web::{http::StatusCode, HttpRequest}; use actix_web::{http::StatusCode, HttpRequest};
use rustical_dav::{ use rustical_dav::{
methods::propfind::{PropElement, PropfindType}, methods::propfind::{PropElement, PropfindType},
resource::Resource, resource::{CommonPropertiesProp, EitherProp, Resource},
xml::{ xml::{
multistatus::{PropstatWrapper, ResponseElement}, multistatus::{PropstatWrapper, ResponseElement},
MultistatusElement, MultistatusElement,
@@ -47,7 +47,13 @@ pub async fn handle_sync_collection<AS: AddressbookStore + ?Sized>(
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
addr_store: &AS, addr_store: &AS,
) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> { ) -> Result<
MultistatusElement<
PropstatWrapper<EitherProp<AddressObjectProp, CommonPropertiesProp>>,
String,
>,
Error,
> {
let props = match sync_collection.prop { let props = match sync_collection.prop {
PropfindType::Allprop => { PropfindType::Allprop => {
vec!["allprop".to_owned()] vec!["allprop".to_owned()]

View File

@@ -10,7 +10,6 @@ use actix_web::web;
use actix_web::{web::Data, HttpRequest}; use actix_web::{web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::extensions::CommonPropertiesProp;
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
use rustical_store::auth::User; use rustical_store::auth::User;
@@ -39,7 +38,7 @@ pub enum AddressbookPropName {
Getctag, Getctag,
} }
#[derive(Default, Deserialize, Serialize, From, PartialEq)] #[derive(Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum AddressbookProp { pub enum AddressbookProp {
// WebDAV (RFC 2518) // WebDAV (RFC 2518)
@@ -68,10 +67,6 @@ pub enum AddressbookProp {
// Didn't find the spec // Didn't find the spec
Getctag(String), Getctag(String),
#[serde(skip_deserializing, rename = "$value")]
#[from]
ExtCommonProperties(CommonPropertiesProp),
#[serde(other)] #[serde(other)]
#[default] #[default]
Invalid, Invalid,
@@ -135,7 +130,6 @@ impl Resource for AddressbookResource {
AddressbookProp::SyncToken(_) => Err(rustical_dav::Error::PropReadOnly), AddressbookProp::SyncToken(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::Getctag(_) => Err(rustical_dav::Error::PropReadOnly), AddressbookProp::Getctag(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::Invalid => Err(rustical_dav::Error::PropReadOnly), AddressbookProp::Invalid => Err(rustical_dav::Error::PropReadOnly),
_ => panic!("we shouldn't end up here"),
} }
} }

View File

@@ -1,4 +1,5 @@
use actix_web::{http::StatusCode, HttpResponse}; use actix_web::{http::StatusCode, HttpResponse};
use tracing::error;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
@@ -41,6 +42,7 @@ impl actix_web::ResponseError for Error {
} }
} }
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
error!("Error: {self}");
match self { match self {
Error::DavError(err) => err.error_response(), Error::DavError(err) => err.error_response(),
_ => HttpResponse::build(self.status_code()).body(self.to_string()), _ => HttpResponse::build(self.status_code()).body(self.to_string()),

View File

@@ -4,8 +4,6 @@ use actix_web::dev::ResourceMap;
use actix_web::web::Data; use actix_web::web::Data;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::From;
use rustical_dav::extensions::CommonPropertiesProp;
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{Resource, ResourceService};
use rustical_dav::xml::HrefElement; use rustical_dav::xml::HrefElement;
@@ -25,7 +23,7 @@ pub struct PrincipalResource {
principal: String, principal: String,
} }
#[derive(Default, Deserialize, Serialize, From, PartialEq)] #[derive(Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum PrincipalProp { pub enum PrincipalProp {
// WebDAV Access Control (RFC 3744) // WebDAV Access Control (RFC 3744)
@@ -38,10 +36,6 @@ pub enum PrincipalProp {
#[serde(rename = "CARD:principal-address")] #[serde(rename = "CARD:principal-address")]
PrincipalAddress(Option<HrefElement>), PrincipalAddress(Option<HrefElement>),
#[serde(skip_deserializing, rename = "$value")]
#[from]
ExtCommonProperties(CommonPropertiesProp),
#[serde(other)] #[serde(other)]
#[default] #[default]
Invalid, Invalid,

View File

@@ -1,7 +1,6 @@
use actix_web::{http::StatusCode, HttpResponse}; use actix_web::{http::StatusCode, HttpResponse};
use thiserror::Error; use thiserror::Error;
use tracing::error;
// use crate::routes::propfind;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum Error { pub enum Error {
@@ -41,6 +40,7 @@ impl actix_web::error::ResponseError for Error {
} }
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> HttpResponse {
error!("Error: {self}");
match self { match self {
Error::Unauthorized => HttpResponse::build(self.status_code()) Error::Unauthorized => HttpResponse::build(self.status_code())
.append_header(("WWW-Authenticate", "Basic")) .append_header(("WWW-Authenticate", "Basic"))

View File

@@ -1,55 +0,0 @@
use crate::resource::{Resource, ResourceProp, ResourcePropName};
use actix_web::dev::ResourceMap;
use rustical_store::auth::User;
use std::str::FromStr;
use strum::VariantNames;
pub trait ResourceExtension<R: Resource>: Clone {
type PropName: ResourcePropName;
type Prop: ResourceProp + Into<R::Prop>;
type Error: Into<R::Error> + From<crate::Error>;
fn list_props(&self) -> &'static [&'static str] {
Self::PropName::VARIANTS
}
fn get_prop(
&self,
resource: &R,
rmap: &ResourceMap,
user: &User,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error>;
fn propfind<'a>(
&self,
resource: &R,
props: Vec<&'a str>,
user: &User,
rmap: &ResourceMap,
) -> Result<(Vec<&'a str>, Vec<R::Prop>), R::Error> {
let (valid_props, invalid_props): (Vec<Option<Self::PropName>>, Vec<Option<&str>>) = props
.into_iter()
.map(|prop| {
if let Ok(valid_prop) = Self::PropName::from_str(prop) {
(Some(valid_prop), None)
} else {
(None, Some(prop))
}
})
.unzip();
let valid_props: Vec<Self::PropName> = valid_props.into_iter().flatten().collect();
let invalid_props: Vec<&str> = invalid_props.into_iter().flatten().collect();
let prop_responses = valid_props
.into_iter()
.map(|prop| <Self as ResourceExtension<_>>::get_prop(self, resource, rmap, user, prop))
.collect::<Result<Vec<_>, Self::Error>>()
.map_err(Self::Error::into)?
.into_iter()
.map(|prop| prop.into())
.collect::<Vec<_>>();
Ok((invalid_props, prop_responses))
}
}

View File

@@ -1,91 +0,0 @@
use crate::{
extension::ResourceExtension,
privileges::UserPrivilegeSet,
resource::{InvalidProperty, Resource},
xml::{HrefElement, Resourcetype},
};
use actix_web::dev::ResourceMap;
use rustical_store::auth::User;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use strum::{EnumString, VariantNames};
#[derive(Clone)]
pub struct CommonPropertiesExtension<R: Resource>(PhantomData<R>);
impl<R: Resource> Default for CommonPropertiesExtension<R> {
fn default() -> Self {
Self(PhantomData)
}
}
#[derive(Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum CommonPropertiesProp {
// WebDAV (RFC 2518)
#[serde(skip_deserializing)]
Resourcetype(Resourcetype),
// WebDAV Current Principal Extension (RFC 5397)
CurrentUserPrincipal(HrefElement),
// WebDAV Access Control Protocol (RFC 3477)
CurrentUserPrivilegeSet(UserPrivilegeSet),
Owner(Option<HrefElement>),
#[serde(other)]
Invalid,
}
impl InvalidProperty for CommonPropertiesProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(EnumString, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum CommonPropertiesPropName {
Resourcetype,
CurrentUserPrincipal,
CurrentUserPrivilegeSet,
Owner,
}
impl<R: Resource> ResourceExtension<R> for CommonPropertiesExtension<R>
where
R::Prop: From<CommonPropertiesProp>,
{
type Prop = CommonPropertiesProp;
type PropName = CommonPropertiesPropName;
type Error = R::Error;
fn get_prop(
&self,
resource: &R,
rmap: &ResourceMap,
user: &User,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
Ok(match prop {
CommonPropertiesPropName::Resourcetype => {
CommonPropertiesProp::Resourcetype(Resourcetype(R::get_resourcetype()))
}
CommonPropertiesPropName::CurrentUserPrincipal => {
CommonPropertiesProp::CurrentUserPrincipal(
R::PrincipalResource::get_url(rmap, [&user.id])
.unwrap()
.into(),
)
}
CommonPropertiesPropName::CurrentUserPrivilegeSet => {
CommonPropertiesProp::CurrentUserPrivilegeSet(resource.get_user_privileges(user)?)
}
CommonPropertiesPropName::Owner => CommonPropertiesProp::Owner(
resource
.get_owner()
.map(|owner| R::PrincipalResource::get_url(rmap, [owner]).unwrap().into()),
),
})
}
}

View File

@@ -1,7 +1,5 @@
pub mod depth_header; pub mod depth_header;
pub mod error; pub mod error;
pub mod extension;
pub mod extensions;
pub mod methods; pub mod methods;
pub mod namespace; pub mod namespace;
pub mod privileges; pub mod privileges;

View File

@@ -1,5 +1,7 @@
use crate::depth_header::Depth; use crate::depth_header::Depth;
use crate::privileges::UserPrivilege; use crate::privileges::UserPrivilege;
use crate::resource::CommonPropertiesProp;
use crate::resource::EitherProp;
use crate::resource::Resource; use crate::resource::Resource;
use crate::resource::ResourceService; use crate::resource::ResourceService;
use crate::xml::multistatus::PropstatWrapper; use crate::xml::multistatus::PropstatWrapper;
@@ -46,8 +48,8 @@ pub async fn route_propfind<R: ResourceService>(
root_span: RootSpan, root_span: RootSpan,
) -> Result< ) -> Result<
MultistatusElement< MultistatusElement<
PropstatWrapper<<R::Resource as Resource>::Prop>, PropstatWrapper<EitherProp<<R::Resource as Resource>::Prop, CommonPropertiesProp>>,
PropstatWrapper<<R::MemberType as Resource>::Prop>, PropstatWrapper<EitherProp<<R::MemberType as Resource>::Prop, CommonPropertiesProp>>,
>, >,
R::Error, R::Error,
> { > {

View File

@@ -93,10 +93,10 @@ pub async fn route_proppatch<R: ResourceService>(
prop: PropertyElement { prop }, prop: PropertyElement { prop },
}) => { }) => {
if prop.invalid_property() { if prop.invalid_property() {
if <R::Resource as Resource>::list_all_props().contains(&propname.as_str()) { if <R::Resource as Resource>::list_props().contains(&propname.as_str()) {
// This happens in following cases: // This happens in following cases:
// - read-only properties with #[serde(skip_deserializing)] // - read-only properties with #[serde(skip_deserializing)]
// - for read-only properties from extensions // - internal properties
props_conflict.push(propname) props_conflict.push(propname)
} else { } else {
props_not_found.push(propname); props_not_found.push(propname);

View File

@@ -1,9 +1,8 @@
use crate::extension::ResourceExtension;
use crate::extensions::{CommonPropertiesExtension, CommonPropertiesProp};
use crate::methods::{route_delete, route_propfind, route_proppatch}; use crate::methods::{route_delete, route_propfind, route_proppatch};
use crate::privileges::UserPrivilegeSet; use crate::privileges::UserPrivilegeSet;
use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper}; use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper};
use crate::xml::{multistatus::ResponseElement, TagList}; use crate::xml::{multistatus::ResponseElement, TagList};
use crate::xml::{HrefElement, Resourcetype};
use crate::Error; use crate::Error;
use actix_web::dev::ResourceMap; use actix_web::dev::ResourceMap;
use actix_web::error::UrlGenerationError; use actix_web::error::UrlGenerationError;
@@ -16,7 +15,7 @@ use itertools::Itertools;
use rustical_store::auth::User; use rustical_store::auth::User;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
use strum::VariantNames; use strum::{EnumString, VariantNames};
pub trait ResourceProp: InvalidProperty + Serialize + for<'de> Deserialize<'de> {} pub trait ResourceProp: InvalidProperty + Serialize + for<'de> Deserialize<'de> {}
impl<T: InvalidProperty + Serialize + for<'de> Deserialize<'de>> ResourceProp for T {} impl<T: InvalidProperty + Serialize + for<'de> Deserialize<'de>> ResourceProp for T {}
@@ -27,31 +26,91 @@ impl<T: FromStr + VariantNames> ResourcePropName for T {}
pub trait ResourceType: Serialize + for<'de> Deserialize<'de> {} pub trait ResourceType: Serialize + for<'de> Deserialize<'de> {}
impl<T: Serialize + for<'de> Deserialize<'de>> ResourceType for T {} impl<T: Serialize + for<'de> Deserialize<'de>> ResourceType for T {}
#[derive(Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum CommonPropertiesProp {
// WebDAV (RFC 2518)
#[serde(skip_deserializing)]
Resourcetype(Resourcetype),
// WebDAV Current Principal Extension (RFC 5397)
CurrentUserPrincipal(HrefElement),
// WebDAV Access Control Protocol (RFC 3477)
CurrentUserPrivilegeSet(UserPrivilegeSet),
Owner(Option<HrefElement>),
#[serde(other)]
Invalid,
}
#[derive(Serialize)]
pub enum EitherProp<Left: ResourceProp, Right: ResourceProp> {
#[serde(untagged)]
Left(Left),
#[serde(untagged)]
Right(Right),
}
impl InvalidProperty for CommonPropertiesProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(EnumString, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum CommonPropertiesPropName {
Resourcetype,
CurrentUserPrincipal,
CurrentUserPrivilegeSet,
Owner,
}
pub trait Resource: Clone + 'static { pub trait Resource: Clone + 'static {
type PropName: ResourcePropName; type PropName: ResourcePropName;
type Prop: ResourceProp + From<CommonPropertiesProp> + PartialEq; type Prop: ResourceProp + PartialEq;
type Error: ResponseError + From<crate::Error>; type Error: ResponseError + From<crate::Error>;
type PrincipalResource: Resource; type PrincipalResource: Resource;
fn get_resourcetype() -> &'static [&'static str]; fn get_resourcetype() -> &'static [&'static str];
fn list_extensions() -> Vec<impl ResourceExtension<Self>> { fn list_props() -> Vec<&'static str> {
vec![CommonPropertiesExtension::default()] [
&Self::PropName::VARIANTS[..],
&CommonPropertiesPropName::VARIANTS[..],
]
.concat()
} }
fn list_props() -> &'static [&'static str] { fn get_internal_prop(
Self::PropName::VARIANTS &self,
} rmap: &ResourceMap,
user: &User,
fn list_all_props() -> Vec<&'static str> { prop: &CommonPropertiesPropName,
let mut props = Self::list_props().to_vec(); ) -> Result<CommonPropertiesProp, Self::Error> {
props.extend( Ok(match prop {
Self::list_extensions() CommonPropertiesPropName::Resourcetype => {
.into_iter() CommonPropertiesProp::Resourcetype(Resourcetype(Self::get_resourcetype()))
.map(|ext| ext.list_props().to_vec()) }
.concat(), CommonPropertiesPropName::CurrentUserPrincipal => {
); CommonPropertiesProp::CurrentUserPrincipal(
props Self::PrincipalResource::get_url(rmap, [&user.id])
.unwrap()
.into(),
)
}
CommonPropertiesPropName::CurrentUserPrivilegeSet => {
CommonPropertiesProp::CurrentUserPrivilegeSet(self.get_user_privileges(user)?)
}
CommonPropertiesPropName::Owner => {
CommonPropertiesProp::Owner(self.get_owner().map(|owner| {
Self::PrincipalResource::get_url(rmap, [owner])
.unwrap()
.into()
}))
}
})
} }
fn get_prop( fn get_prop(
@@ -98,7 +157,10 @@ pub trait Resource: Clone + 'static {
mut props: Vec<&str>, mut props: Vec<&str>,
user: &User, user: &User,
rmap: &ResourceMap, rmap: &ResourceMap,
) -> Result<ResponseElement<PropstatWrapper<Self::Prop>>, Self::Error> { ) -> Result<
ResponseElement<PropstatWrapper<EitherProp<Self::Prop, CommonPropertiesProp>>>,
Self::Error,
> {
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
@@ -106,18 +168,11 @@ pub trait Resource: Clone + 'static {
Error::BadRequest("propname MUST be the only queried prop".to_owned()).into(), Error::BadRequest("propname MUST be the only queried prop".to_owned()).into(),
); );
} }
let mut props: Vec<String> = Self::list_props() let props: Vec<String> = Self::list_props()
.iter() .iter()
.map(|&prop| prop.to_string()) .map(|&prop| prop.to_string())
.collect(); .collect();
for extension in Self::list_extensions() {
let ext_props: Vec<String> = extension
.list_props()
.iter()
.map(|&prop| prop.to_string())
.collect();
props.extend(ext_props);
}
return Ok(ResponseElement { return Ok(ResponseElement {
href: path.to_owned(), href: path.to_owned(),
propstat: vec![PropstatWrapper::TagList(PropstatElement { propstat: vec![PropstatWrapper::TagList(PropstatElement {
@@ -134,40 +189,36 @@ pub trait Resource: Clone + 'static {
Error::BadRequest("allprop MUST be the only queried prop".to_owned()).into(), Error::BadRequest("allprop MUST be the only queried prop".to_owned()).into(),
); );
} }
props = Self::list_props().to_vec(); props = Self::list_props();
for extension in Self::list_extensions() { }
let ext_props: Vec<&str> = extension.list_props().into();
props.extend(ext_props); let mut valid_props = vec![];
let mut internal_props = vec![];
let mut invalid_props = vec![];
for prop in props {
if let Ok(valid_prop) = Self::PropName::from_str(prop) {
valid_props.push(valid_prop);
} else if let Ok(internal_prop) = CommonPropertiesPropName::from_str(prop) {
internal_props.push(internal_prop);
} else {
invalid_props.push(prop)
} }
} }
let mut prop_responses = Vec::new(); let internal_prop_responses: Vec<_> = internal_props
for extension in Self::list_extensions() {
let (ext_invalid_props, ext_responses) = extension.propfind(self, props, user, rmap)?;
props = ext_invalid_props;
prop_responses.extend(ext_responses);
}
let (valid_props, invalid_props): (Vec<Option<Self::PropName>>, Vec<Option<&str>>) = props
.into_iter() .into_iter()
.map(|prop| { .map(|prop| self.get_internal_prop(rmap, user, &prop))
if let Ok(valid_prop) = Self::PropName::from_str(prop) { .collect::<Result<Vec<CommonPropertiesProp>, Self::Error>>()?
(Some(valid_prop), None) .into_iter()
} else { .map(EitherProp::Right)
(None, Some(prop)) .collect();
}
})
.unzip();
let valid_props: Vec<Self::PropName> = valid_props.into_iter().flatten().collect();
let invalid_props: Vec<&str> = invalid_props.into_iter().flatten().collect();
prop_responses.extend( let mut prop_responses = valid_props
valid_props .into_iter()
.into_iter() .map(|prop| self.get_prop(rmap, user, &prop))
.map(|prop| self.get_prop(rmap, user, &prop)) .map_ok(EitherProp::Left)
.collect::<Result<Vec<Self::Prop>, Self::Error>>()?, .collect::<Result<Vec<_>, Self::Error>>()?;
); prop_responses.extend(internal_prop_responses);
let mut propstats = vec![PropstatWrapper::Normal(PropstatElement { let mut propstats = vec![PropstatWrapper::Normal(PropstatElement {
status: format!("HTTP/1.1 {}", StatusCode::OK), status: format!("HTTP/1.1 {}", StatusCode::OK),

View File

@@ -1,10 +1,10 @@
use crate::extensions::CommonPropertiesProp;
use crate::privileges::UserPrivilegeSet; use crate::privileges::UserPrivilegeSet;
use crate::resource::{Resource, ResourceService}; use crate::resource::{Resource, ResourceService};
use actix_web::dev::ResourceMap; use actix_web::dev::ResourceMap;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_store::auth::User; use rustical_store::auth::User;
use serde::{Deserialize, Serialize};
use std::any::type_name; use std::any::type_name;
use std::marker::PhantomData; use std::marker::PhantomData;
use strum::{EnumString, VariantNames}; use strum::{EnumString, VariantNames};
@@ -22,9 +22,16 @@ impl<PR: Resource> Default for RootResource<PR> {
#[strum(serialize_all = "kebab-case")] #[strum(serialize_all = "kebab-case")]
pub enum RootResourcePropName {} pub enum RootResourcePropName {}
#[derive(Deserialize, Serialize, Default, Clone, PartialEq)]
pub enum RootResourceProp {
#[serde(other)]
#[default]
Invalid,
}
impl<PR: Resource> Resource for RootResource<PR> { impl<PR: Resource> Resource for RootResource<PR> {
type PropName = RootResourcePropName; type PropName = RootResourcePropName;
type Prop = CommonPropertiesProp; type Prop = RootResourceProp;
type Error = PR::Error; type Error = PR::Error;
type PrincipalResource = PR; type PrincipalResource = PR;