rustical_dav: Make actix-web a completely optional dependency

This commit is contained in:
Lennart
2025-06-02 21:58:46 +02:00
parent 05ff2536f6
commit 9836a696ad
10 changed files with 87 additions and 36 deletions

View File

@@ -1,4 +1,4 @@
use actix_web::{HttpResponse, http::StatusCode}; use http::StatusCode;
use rustical_xml::XmlError; use rustical_xml::XmlError;
use thiserror::Error; use thiserror::Error;
use tracing::error; use tracing::error;
@@ -30,8 +30,8 @@ pub enum Error {
PreconditionFailed, PreconditionFailed,
} }
impl actix_web::error::ResponseError for Error { impl Error {
fn status_code(&self) -> StatusCode { pub fn status_code(&self) -> StatusCode {
match self { match self {
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR, Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
Self::NotFound => StatusCode::NOT_FOUND, Self::NotFound => StatusCode::NOT_FOUND,
@@ -51,14 +51,21 @@ impl actix_web::error::ResponseError for Error {
Self::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR, Self::IOError(_) => StatusCode::INTERNAL_SERVER_ERROR,
} }
} }
}
fn error_response(&self) -> HttpResponse { #[cfg(feature = "actix")]
impl actix_web::error::ResponseError for Error {
fn status_code(&self) -> StatusCode {
self.status_code()
}
fn error_response(&self) -> actix_web::HttpResponse {
error!("Error: {self}"); error!("Error: {self}");
match self { match self {
Error::Unauthorized => HttpResponse::build(self.status_code()) Error::Unauthorized => actix_web::HttpResponse::build(self.status_code())
.append_header(("WWW-Authenticate", "Basic")) .append_header(("WWW-Authenticate", "Basic"))
.body(self.to_string()), .body(self.to_string()),
_ => HttpResponse::build(self.status_code()).body(self.to_string()), _ => actix_web::HttpResponse::build(self.status_code()).body(self.to_string()),
} }
} }
} }

View File

@@ -1,5 +1,7 @@
use actix_web::{FromRequest, HttpRequest, ResponseError, http::StatusCode}; #[cfg(feature = "actix")]
use actix_web::{HttpRequest, ResponseError};
use futures_util::future::{Ready, err, ok}; use futures_util::future::{Ready, err, ok};
use http::StatusCode;
use rustical_xml::{ValueDeserialize, ValueSerialize, XmlError}; use rustical_xml::{ValueDeserialize, ValueSerialize, XmlError};
use thiserror::Error; use thiserror::Error;
@@ -7,6 +9,7 @@ use thiserror::Error;
#[error("Invalid Depth header")] #[error("Invalid Depth header")]
pub struct InvalidDepthHeader; pub struct InvalidDepthHeader;
#[cfg(feature = "actix")]
impl ResponseError for InvalidDepthHeader { impl ResponseError for InvalidDepthHeader {
fn status_code(&self) -> actix_web::http::StatusCode { fn status_code(&self) -> actix_web::http::StatusCode {
StatusCode::BAD_REQUEST StatusCode::BAD_REQUEST
@@ -57,7 +60,8 @@ impl TryFrom<&[u8]> for Depth {
} }
} }
impl FromRequest for Depth { #[cfg(feature = "actix")]
impl actix_web::FromRequest for Depth {
type Error = InvalidDepthHeader; type Error = InvalidDepthHeader;
type Future = Ready<Result<Self, Self::Error>>; type Future = Ready<Result<Self, Self::Error>>;

View File

@@ -1,3 +1,4 @@
#[cfg(feature = "actix")]
use actix_web::{FromRequest, HttpRequest, ResponseError, http::StatusCode}; use actix_web::{FromRequest, HttpRequest, ResponseError, http::StatusCode};
use futures_util::future::{Ready, err, ok}; use futures_util::future::{Ready, err, ok};
use thiserror::Error; use thiserror::Error;
@@ -6,6 +7,7 @@ use thiserror::Error;
#[error("Invalid Overwrite header")] #[error("Invalid Overwrite header")]
pub struct InvalidOverwriteHeader; pub struct InvalidOverwriteHeader;
#[cfg(feature = "actix")]
impl ResponseError for InvalidOverwriteHeader { impl ResponseError for InvalidOverwriteHeader {
fn status_code(&self) -> actix_web::http::StatusCode { fn status_code(&self) -> actix_web::http::StatusCode {
StatusCode::BAD_REQUEST StatusCode::BAD_REQUEST
@@ -37,6 +39,7 @@ impl TryFrom<&[u8]> for Overwrite {
} }
} }
#[cfg(feature = "actix")]
impl FromRequest for Overwrite { impl FromRequest for Overwrite {
type Error = InvalidOverwriteHeader; type Error = InvalidOverwriteHeader;
type Future = Ready<Result<Self, Self::Error>>; type Future = Ready<Result<Self, Self::Error>>;

View File

@@ -7,9 +7,8 @@ pub mod resource;
pub mod resources; pub mod resources;
pub mod xml; pub mod xml;
use actix_web::FromRequest;
pub use error::Error; pub use error::Error;
pub trait Principal: std::fmt::Debug + Clone + FromRequest + 'static { pub trait Principal: std::fmt::Debug + Clone + 'static {
fn get_id(&self) -> &str; fn get_id(&self) -> &str;
} }

View File

@@ -69,7 +69,7 @@ pub async fn route_delete<R: ResourceService>(
if_match: Option<IfMatch>, if_match: Option<IfMatch>,
if_none_match: Option<IfNoneMatch>, if_none_match: Option<IfNoneMatch>,
) -> Result<(), R::Error> { ) -> Result<(), R::Error> {
let resource = resource_service.get_resource(&path_components).await?; let resource = resource_service.get_resource(path_components).await?;
let privileges = resource.get_user_privileges(&principal)?; let privileges = resource.get_user_privileges(&principal)?;
if !privileges.has(&UserPrivilege::Write) { if !privileges.has(&UserPrivilege::Write) {

View File

@@ -11,3 +11,6 @@ pub(crate) use delete::actix_route_delete;
#[cfg(feature = "actix")] #[cfg(feature = "actix")]
pub(crate) use propfind::actix_route_propfind; pub(crate) use propfind::actix_route_propfind;
#[cfg(feature = "actix")]
pub(crate) use proppatch::actix_route_proppatch;

View File

@@ -5,9 +5,7 @@ use crate::resource::ResourceService;
use crate::xml::MultistatusElement; use crate::xml::MultistatusElement;
use crate::xml::TagList; use crate::xml::TagList;
use crate::xml::multistatus::{PropstatElement, PropstatWrapper, ResponseElement}; use crate::xml::multistatus::{PropstatElement, PropstatWrapper, ResponseElement};
use actix_web::http::StatusCode; use http::StatusCode;
use actix_web::web::Data;
use actix_web::{HttpRequest, web::Path};
use quick_xml::name::Namespace; use quick_xml::name::Namespace;
use rustical_xml::EnumUnitVariants; use rustical_xml::EnumUnitVariants;
use rustical_xml::Unparsed; use rustical_xml::Unparsed;
@@ -63,23 +61,41 @@ enum Operation<T: XmlDeserialize> {
#[xml(ns = "crate::namespace::NS_DAV")] #[xml(ns = "crate::namespace::NS_DAV")]
struct PropertyupdateElement<T: XmlDeserialize>(#[xml(ty = "untagged", flatten)] Vec<Operation<T>>); struct PropertyupdateElement<T: XmlDeserialize>(#[xml(ty = "untagged", flatten)] Vec<Operation<T>>);
#[cfg(feature = "actix")]
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))] #[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
pub(crate) async fn route_proppatch<R: ResourceService>( pub(crate) async fn actix_route_proppatch<R: ResourceService>(
path: Path<R::PathComponents>, path: actix_web::web::Path<R::PathComponents>,
body: String, body: String,
req: HttpRequest, req: actix_web::HttpRequest,
principal: R::Principal, principal: R::Principal,
root_span: RootSpan, root_span: RootSpan,
resource_service: Data<R>, resource_service: actix_web::web::Data<R>,
) -> Result<MultistatusElement<String, String>, R::Error> { ) -> Result<MultistatusElement<String, String>, R::Error> {
let href = req.path().to_owned(); route_proppatch(
&path.into_inner(),
req.path(),
body,
principal,
resource_service.as_ref(),
)
.await
}
pub(crate) async fn route_proppatch<R: ResourceService>(
path_components: &R::PathComponents,
path: &str,
body: String,
principal: R::Principal,
resource_service: &R,
) -> Result<MultistatusElement<String, String>, R::Error> {
let href = path.to_owned();
// Extract operations // Extract operations
let PropertyupdateElement::<SetPropertyPropWrapperWrapper<<R::Resource as Resource>::Prop>>( let PropertyupdateElement::<SetPropertyPropWrapperWrapper<<R::Resource as Resource>::Prop>>(
operations, operations,
) = XmlDocument::parse_str(&body).map_err(Error::XmlError)?; ) = XmlDocument::parse_str(&body).map_err(Error::XmlError)?;
let mut resource = resource_service.get_resource(&path).await?; let mut resource = resource_service.get_resource(path_components).await?;
let privileges = resource.get_user_privileges(&principal)?; let privileges = resource.get_user_privileges(&principal)?;
if !privileges.has(&UserPrivilege::Write) { if !privileges.has(&UserPrivilege::Write) {
return Err(Error::Unauthorized.into()); return Err(Error::Unauthorized.into());
@@ -151,7 +167,9 @@ pub(crate) async fn route_proppatch<R: ResourceService>(
if props_not_found.is_empty() && props_conflict.is_empty() { if props_not_found.is_empty() && props_conflict.is_empty() {
// Only save if no errors occured // Only save if no errors occured
resource_service.save_resource(&path, resource).await?; resource_service
.save_resource(path_components, resource)
.await?;
} }
Ok(MultistatusElement { Ok(MultistatusElement {

View File

@@ -1,8 +1,9 @@
use super::methods::{actix_route_delete, actix_route_propfind, route_proppatch}; #[cfg(feature = "actix")]
use super::methods::{actix_route_delete, actix_route_propfind, actix_route_proppatch};
use super::{PrincipalUri, Resource}; use super::{PrincipalUri, Resource};
use crate::Principal; use crate::Principal;
use actix_web::web::Data; #[cfg(feature = "actix")]
use actix_web::{ResponseError, http::Method, web}; use actix_web::{http::Method, web, web::Data};
use async_trait::async_trait; use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use std::str::FromStr; use std::str::FromStr;
@@ -12,7 +13,7 @@ pub trait ResourceService: Sized + 'static {
type MemberType: Resource<Error = Self::Error, Principal = Self::Principal>; type MemberType: Resource<Error = Self::Error, Principal = Self::Principal>;
type PathComponents: for<'de> Deserialize<'de> + Sized + Clone + 'static; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String) type PathComponents: for<'de> Deserialize<'de> + Sized + Clone + 'static; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
type Resource: Resource<Error = Self::Error, Principal = Self::Principal>; type Resource: Resource<Error = Self::Error, Principal = Self::Principal>;
type Error: ResponseError + From<crate::Error>; type Error: From<crate::Error>;
type Principal: Principal; type Principal: Principal;
type PrincipalUri: PrincipalUri; type PrincipalUri: PrincipalUri;
@@ -44,16 +45,28 @@ pub trait ResourceService: Sized + 'static {
Err(crate::Error::Unauthorized.into()) Err(crate::Error::Unauthorized.into())
} }
#[cfg(feature = "actix")]
#[inline] #[inline]
fn actix_resource(self) -> actix_web::Resource { fn actix_resource(self) -> actix_web::Resource
where
Self::Error: actix_web::ResponseError,
Self::Principal: actix_web::FromRequest,
{
web::resource("") web::resource("")
.app_data(Data::new(self)) .app_data(Data::new(self))
.route( .route(
web::method(Method::from_str("PROPFIND").unwrap()).to(actix_route_propfind::<Self>), web::method(Method::from_str("PROPFIND").unwrap()).to(actix_route_propfind::<Self>),
) )
.route(web::method(Method::from_str("PROPPATCH").unwrap()).to(route_proppatch::<Self>)) .route(
web::method(Method::from_str("PROPPATCH").unwrap())
.to(actix_route_proppatch::<Self>),
)
.delete(actix_route_delete::<Self>) .delete(actix_route_delete::<Self>)
} }
fn actix_scope(self) -> actix_web::Scope; #[cfg(feature = "actix")]
fn actix_scope(self) -> actix_web::Scope
where
Self::Error: actix_web::ResponseError,
Self::Principal: actix_web::FromRequest;
} }

View File

@@ -5,7 +5,6 @@ use crate::extensions::{
use crate::privileges::UserPrivilegeSet; use crate::privileges::UserPrivilegeSet;
use crate::resource::{PrincipalUri, Resource, ResourceService}; use crate::resource::{PrincipalUri, Resource, ResourceService};
use crate::xml::{Resourcetype, ResourcetypeInner}; use crate::xml::{Resourcetype, ResourcetypeInner};
use actix_web::web;
use async_trait::async_trait; use async_trait::async_trait;
use std::marker::PhantomData; use std::marker::PhantomData;
@@ -74,8 +73,13 @@ impl<PRS: ResourceService<Principal = P> + Clone, P: Principal, PURI: PrincipalU
Ok(RootResource::<PRS::Resource, P>::default()) Ok(RootResource::<PRS::Resource, P>::default())
} }
fn actix_scope(self) -> actix_web::Scope { #[cfg(feature = "actix")]
web::scope("") fn actix_scope(self) -> actix_web::Scope
where
Self::Error: actix_web::ResponseError,
Self::Principal: actix_web::FromRequest,
{
actix_web::web::scope("")
.service(self.0.clone().actix_scope()) .service(self.0.clone().actix_scope())
.service(self.actix_resource()) .service(self.actix_resource())
} }

View File

@@ -1,13 +1,12 @@
use std::collections::HashMap;
use crate::xml::TagList; use crate::xml::TagList;
#[cfg(feature = "actix")]
use actix_web::{ use actix_web::{
body::BoxBody, HttpRequest, HttpResponse, Responder, ResponseError, body::BoxBody, http::header::ContentType,
http::{header::ContentType, StatusCode},
HttpRequest, HttpResponse, Responder, ResponseError,
}; };
use http::StatusCode;
use quick_xml::name::Namespace; use quick_xml::name::Namespace;
use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot}; use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot};
use std::collections::HashMap;
#[derive(XmlSerialize)] #[derive(XmlSerialize)]
pub struct PropTagWrapper<T: XmlSerialize>(#[xml(flatten, ty = "untagged")] pub Vec<T>); pub struct PropTagWrapper<T: XmlSerialize>(#[xml(flatten, ty = "untagged")] pub Vec<T>);
@@ -109,6 +108,7 @@ impl<T1: XmlSerialize, T2: XmlSerialize> Default for MultistatusElement<T1, T2>
} }
} }
#[cfg(feature = "actix")]
impl<T1: XmlSerialize, T2: XmlSerialize> Responder for MultistatusElement<T1, T2> { impl<T1: XmlSerialize, T2: XmlSerialize> Responder for MultistatusElement<T1, T2> {
type Body = BoxBody; type Body = BoxBody;