Checkpoint: Migration to axum

This commit is contained in:
Lennart
2025-06-08 14:10:12 +02:00
parent 790c657b08
commit 95889e3df1
60 changed files with 1476 additions and 2205 deletions

View File

@@ -53,30 +53,6 @@ impl Error {
}
}
#[cfg(feature = "actix")]
impl actix_web::error::ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
self.status_code()
.as_u16()
.try_into()
.expect("Just converting between versions")
}
fn error_response(&self) -> actix_web::HttpResponse {
use actix_web::ResponseError;
error!("Error: {self}");
match self {
Error::Unauthorized => actix_web::HttpResponse::build(ResponseError::status_code(self))
.append_header(("WWW-Authenticate", "Basic"))
.body(self.to_string()),
_ => actix_web::HttpResponse::build(ResponseError::status_code(self))
.body(self.to_string()),
}
}
}
#[cfg(feature = "axum")]
impl axum::response::IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
use axum::body::Body;

View File

@@ -1,8 +1,4 @@
#[cfg(feature = "actix")]
use actix_web::{HttpRequest, ResponseError};
#[cfg(feature = "axum")]
use axum::{body::Body, extract::FromRequestParts, response::IntoResponse};
use futures_util::future::{Ready, err, ok};
use rustical_xml::{ValueDeserialize, ValueSerialize, XmlError};
use thiserror::Error;
@@ -10,14 +6,6 @@ use thiserror::Error;
#[error("Invalid Depth header")]
pub struct InvalidDepthHeader;
#[cfg(feature = "actix")]
impl ResponseError for InvalidDepthHeader {
fn status_code(&self) -> actix_web::http::StatusCode {
http_02::StatusCode::BAD_REQUEST
}
}
#[cfg(feature = "axum")]
impl IntoResponse for InvalidDepthHeader {
fn into_response(self) -> axum::response::Response {
axum::response::Response::builder()
@@ -71,35 +59,12 @@ impl TryFrom<&[u8]> for Depth {
}
}
#[cfg(feature = "actix")]
impl actix_web::FromRequest for Depth {
type Error = InvalidDepthHeader;
type Future = Ready<Result<Self, Self::Error>>;
fn extract(req: &HttpRequest) -> Self::Future {
if let Some(depth_header) = req.headers().get("Depth") {
match depth_header.as_bytes().try_into() {
Ok(depth) => ok(depth),
Err(e) => err(e),
}
} else {
// default depth
ok(Depth::Zero)
}
}
fn from_request(req: &HttpRequest, _payload: &mut actix_web::dev::Payload) -> Self::Future {
Self::extract(req)
}
}
#[cfg(feature = "axum")]
impl<S: Send + Sync> FromRequestParts<S> for Depth {
type Rejection = InvalidDepthHeader;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
state: &S,
_state: &S,
) -> Result<Self, Self::Rejection> {
if let Some(depth_header) = parts.headers.get("Depth") {
depth_header.as_bytes().try_into()

View File

@@ -1,19 +1,9 @@
#[cfg(feature = "actix")]
use actix_web::{FromRequest, HttpRequest, ResponseError, http::StatusCode};
use futures_util::future::{Ready, err, ok};
use thiserror::Error;
#[derive(Error, Debug)]
#[error("Invalid Overwrite header")]
pub struct InvalidOverwriteHeader;
#[cfg(feature = "actix")]
impl ResponseError for InvalidOverwriteHeader {
fn status_code(&self) -> actix_web::http::StatusCode {
StatusCode::BAD_REQUEST
}
}
#[derive(Debug, PartialEq, Default)]
pub enum Overwrite {
#[default]
@@ -38,25 +28,3 @@ impl TryFrom<&[u8]> for Overwrite {
}
}
}
#[cfg(feature = "actix")]
impl FromRequest for Overwrite {
type Error = InvalidOverwriteHeader;
type Future = Ready<Result<Self, Self::Error>>;
fn extract(req: &HttpRequest) -> Self::Future {
if let Some(overwrite_header) = req.headers().get("Overwrite") {
match overwrite_header.as_bytes().try_into() {
Ok(depth) => ok(depth),
Err(e) => err(e),
}
} else {
// default depth
ok(Overwrite::F)
}
}
fn from_request(req: &HttpRequest, _payload: &mut actix_web::dev::Payload) -> Self::Future {
Self::extract(req)
}
}

View File

@@ -6,7 +6,6 @@ pub mod privileges;
pub mod resource;
pub mod resources;
pub mod xml;
pub use error::Error;
pub trait Principal: std::fmt::Debug + Clone + Send + Sync + 'static {

View File

@@ -2,10 +2,10 @@ use axum::body::Body;
use futures_util::future::BoxFuture;
use headers::Allow;
use http::{Method, Request, Response};
use std::{convert::Infallible, str::FromStr, sync::Arc};
use std::{convert::Infallible, str::FromStr};
pub type MethodFunction<Service> =
fn(Arc<Service>, Request<Body>) -> BoxFuture<'static, Result<Response<Body>, Infallible>>;
fn(Service, Request<Body>) -> BoxFuture<'static, Result<Response<Body>, Infallible>>;
pub trait AxumMethods: Sized + Send + Sync + 'static {
#[inline]

View File

@@ -2,6 +2,7 @@ use super::methods::{axum_route_propfind, axum_route_proppatch};
use crate::resource::{ResourceService, axum_methods::AxumMethods};
use axum::{
body::Body,
extract::FromRequestParts,
handler::Handler,
http::{Request, Response},
response::IntoResponse,
@@ -9,16 +10,16 @@ use axum::{
use futures_util::future::BoxFuture;
use headers::HeaderMapExt;
use http::{HeaderValue, StatusCode};
use std::{convert::Infallible, sync::Arc};
use std::convert::Infallible;
use tower::Service;
#[derive(Clone)]
pub struct AxumService<RS: ResourceService + AxumMethods> {
resource_service: Arc<RS>,
resource_service: RS,
}
impl<RS: ResourceService + AxumMethods> AxumService<RS> {
pub fn new(resource_service: Arc<RS>) -> Self {
pub fn new(resource_service: RS) -> Self {
Self { resource_service }
}
}
@@ -27,6 +28,7 @@ impl<RS: ResourceService + AxumMethods + Clone + Send + Sync> Service<Request<Bo
for AxumService<RS>
where
RS::Error: IntoResponse + Send + Sync + 'static,
RS::Principal: FromRequestParts<RS>,
{
type Error = Infallible;
type Response = Response<Body>;

View File

@@ -2,77 +2,15 @@ use crate::Error;
use crate::privileges::UserPrivilege;
use crate::resource::Resource;
use crate::resource::ResourceService;
#[cfg(feature = "axum")]
use axum::extract::{Extension, Path, State};
#[cfg(feature = "axum")]
use axum::extract::{Path, State};
use axum_extra::TypedHeader;
use headers::Header;
use headers::{HeaderValue, IfMatch, IfNoneMatch};
#[cfg(feature = "axum")]
use headers::{IfMatch, IfNoneMatch};
use http::HeaderMap;
use itertools::Itertools;
#[cfg(feature = "axum")]
use std::sync::Arc;
use tracing::instrument;
#[cfg(feature = "actix")]
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))]
pub async fn actix_route_delete<R: ResourceService>(
path: actix_web::web::Path<R::PathComponents>,
req: actix_web::HttpRequest,
principal: R::Principal,
resource_service: actix_web::web::Data<R>,
root_span: tracing_actix_web::RootSpan,
) -> Result<actix_web::HttpResponse, R::Error> {
let no_trash = req
.headers()
.get("X-No-Trashbin")
.map(|val| matches!(val.to_str(), Ok("1")))
.unwrap_or(false);
// This weird conversion stuff is because we want to use the headers library (to be
// framework-agnostic in the future) which uses http==1.0,
// while actix-web still uses http==0.2
let if_match = req
.headers()
.get_all(http_02::header::IF_MATCH)
.map(|val_02| HeaderValue::from_bytes(val_02.as_bytes()).unwrap())
.collect_vec();
let if_none_match = req
.headers()
.get_all(http_02::header::IF_NONE_MATCH)
.map(|val_02| HeaderValue::from_bytes(val_02.as_bytes()).unwrap())
.collect_vec();
let if_match = if if_match.is_empty() {
None
} else {
Some(IfMatch::decode(&mut if_match.iter()).unwrap())
};
let if_none_match = if if_none_match.is_empty() {
None
} else {
Some(IfNoneMatch::decode(&mut if_none_match.iter()).unwrap())
};
route_delete(
&path.into_inner(),
&principal,
resource_service.as_ref(),
no_trash,
if_match,
if_none_match,
)
.await?;
Ok(actix_web::HttpResponse::Ok().body(""))
}
#[cfg(feature = "axum")]
pub(crate) async fn axum_route_delete<R: ResourceService>(
Path(path): Path<R::PathComponents>,
State(resource_service): State<Arc<R>>,
Extension(principal): Extension<R::Principal>,
State(resource_service): State<R>,
principal: R::Principal,
if_match: Option<TypedHeader<IfMatch>>,
if_none_match: Option<TypedHeader<IfNoneMatch>>,
header_map: HeaderMap,
@@ -84,7 +22,7 @@ pub(crate) async fn axum_route_delete<R: ResourceService>(
route_delete(
&path,
&principal,
resource_service.as_ref(),
&resource_service,
no_trash,
if_match.map(|hdr| hdr.0),
if_none_match.map(|hdr| hdr.0),

View File

@@ -2,17 +2,6 @@ mod delete;
mod propfind;
mod proppatch;
#[cfg(feature = "actix")]
pub(crate) use delete::actix_route_delete;
#[cfg(feature = "axum")]
pub(crate) use delete::axum_route_delete;
#[cfg(feature = "actix")]
pub(crate) use propfind::actix_route_propfind;
#[cfg(feature = "axum")]
pub(crate) use propfind::axum_route_propfind;
#[cfg(feature = "actix")]
pub(crate) use proppatch::actix_route_proppatch;
#[cfg(feature = "axum")]
pub(crate) use proppatch::axum_route_proppatch;

View File

@@ -7,47 +7,15 @@ use crate::resource::ResourceService;
use crate::xml::MultistatusElement;
use crate::xml::PropfindElement;
use crate::xml::PropfindType;
#[cfg(feature = "axum")]
use axum::extract::{Extension, OriginalUri, Path, State};
use rustical_xml::PropName;
use rustical_xml::XmlDocument;
use std::sync::Arc;
use tracing::instrument;
#[cfg(feature = "actix")]
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service, puri))]
#[allow(clippy::type_complexity)]
pub(crate) async fn actix_route_propfind<R: ResourceService>(
path: ::actix_web::web::Path<R::PathComponents>,
body: String,
req: ::actix_web::HttpRequest,
user: R::Principal,
depth: Depth,
root_span: tracing_actix_web::RootSpan,
resource_service: ::actix_web::web::Data<R>,
puri: ::actix_web::web::Data<R::PrincipalUri>,
) -> Result<
MultistatusElement<<R::Resource as Resource>::Prop, <R::MemberType as Resource>::Prop>,
R::Error,
> {
route_propfind(
&path.into_inner(),
req.path(),
&body,
&user,
&depth,
resource_service.as_ref(),
puri.as_ref(),
)
.await
}
#[cfg(feature = "axum")]
pub(crate) async fn axum_route_propfind<R: ResourceService>(
Path(path): Path<R::PathComponents>,
State(resource_service): State<Arc<R>>,
State(resource_service): State<R>,
depth: Depth,
Extension(principal): Extension<R::Principal>,
principal: R::Principal,
uri: OriginalUri,
Extension(puri): Extension<R::PrincipalUri>,
body: String,
@@ -61,7 +29,7 @@ pub(crate) async fn axum_route_propfind<R: ResourceService>(
&body,
&principal,
&depth,
resource_service.as_ref(),
&resource_service,
&puri,
)
.await
@@ -115,7 +83,7 @@ pub(crate) async fn route_propfind<R: ResourceService>(
}
}
let response = resource.propfind_typed(path, &propfind_self.prop, puri, &principal)?;
let response = resource.propfind_typed(path, &propfind_self.prop, puri, principal)?;
Ok(MultistatusElement {
responses: vec![response],

View File

@@ -1,13 +1,11 @@
use crate::Error;
use crate::privileges::UserPrivilege;
use std::sync::Arc;
use crate::resource::Resource;
use crate::resource::ResourceService;
#[cfg(feature = "axum")]
use axum::extract::{Extension, OriginalUri, Path, State};
use crate::xml::MultistatusElement;
use crate::xml::TagList;
use crate::xml::multistatus::{PropstatElement, PropstatWrapper, ResponseElement};
use axum::extract::{OriginalUri, Path, State};
use http::StatusCode;
use quick_xml::name::Namespace;
use rustical_xml::NamespaceOwned;
@@ -17,7 +15,6 @@ use rustical_xml::XmlDeserialize;
use rustical_xml::XmlDocument;
use rustical_xml::XmlRootTag;
use std::str::FromStr;
use tracing::instrument;
#[derive(XmlDeserialize, Clone, Debug)]
#[xml(untagged)]
@@ -64,46 +61,14 @@ enum Operation<T: XmlDeserialize> {
#[xml(ns = "crate::namespace::NS_DAV")]
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))]
pub(crate) async fn actix_route_proppatch<R: ResourceService>(
path: actix_web::web::Path<R::PathComponents>,
body: String,
req: actix_web::HttpRequest,
principal: R::Principal,
root_span: tracing_actix_web::RootSpan,
resource_service: actix_web::web::Data<R>,
) -> Result<MultistatusElement<String, String>, R::Error> {
route_proppatch(
&path.into_inner(),
req.path(),
&body,
&principal,
resource_service.as_ref(),
)
.await
}
#[cfg(feature = "axum")]
pub(crate) async fn axum_route_proppatch<R: ResourceService>(
Path(path): Path<R::PathComponents>,
State(resource_service): State<Arc<R>>,
Extension(principal): Extension<R::Principal>,
State(resource_service): State<R>,
principal: R::Principal,
uri: OriginalUri,
body: String,
) -> Result<
MultistatusElement<String, String>,
R::Error,
> {
route_proppatch(
&path,
uri.path(),
&body,
&principal,
resource_service.as_ref(),
)
.await
) -> Result<MultistatusElement<String, String>, R::Error> {
route_proppatch(&path, uri.path(), &body, &principal, &resource_service).await
}
pub(crate) async fn route_proppatch<R: ResourceService>(
@@ -118,10 +83,10 @@ pub(crate) async fn route_proppatch<R: ResourceService>(
// Extract operations
let PropertyupdateElement::<SetPropertyPropWrapperWrapper<<R::Resource as Resource>::Prop>>(
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_components).await?;
let privileges = resource.get_user_privileges(&principal)?;
let privileges = resource.get_user_privileges(principal)?;
if !privileges.has(&UserPrivilege::Write) {
return Err(Error::Unauthorized.into());
}

View File

@@ -12,17 +12,13 @@ use rustical_xml::{EnumVariants, NamespaceOwned, PropName, XmlDeserialize, XmlSe
use std::collections::HashSet;
use std::str::FromStr;
#[cfg(feature = "axum")]
mod axum_methods;
#[cfg(feature = "axum")]
mod axum_service;
mod methods;
mod principal_uri;
mod resource_service;
#[cfg(feature = "axum")]
pub use axum_methods::AxumMethods;
#[cfg(feature = "axum")]
pub use axum_service::AxumService;
pub use principal_uri::PrincipalUri;

View File

@@ -1,14 +1,8 @@
#[cfg(feature = "actix")]
use super::methods::{actix_route_delete, actix_route_propfind, actix_route_proppatch};
use super::{PrincipalUri, Resource};
use crate::Principal;
#[cfg(feature = "axum")]
use crate::resource::{AxumMethods, AxumService};
#[cfg(feature = "actix")]
use actix_web::{http::Method, web, web::Data};
use async_trait::async_trait;
use serde::Deserialize;
use std::{str::FromStr, sync::Arc};
#[async_trait]
pub trait ResourceService: Sized + Send + Sync + 'static {
@@ -28,11 +22,6 @@ pub trait ResourceService: Sized + Send + Sync + 'static {
Ok(vec![])
}
async fn test_get_members(&self, _path: &Self::PathComponents) -> Result<String, Self::Error> {
// ) -> Result<Vec<Self::MemberType>, Self::Error> {
Ok("asd".to_string())
}
async fn get_resource(
&self,
_path: &Self::PathComponents,
@@ -54,36 +43,10 @@ pub trait ResourceService: Sized + Send + Sync + 'static {
Err(crate::Error::Unauthorized.into())
}
#[cfg(feature = "actix")]
#[inline]
fn actix_resource(self) -> actix_web::Resource
where
Self::Error: actix_web::ResponseError,
Self::Principal: actix_web::FromRequest,
{
web::resource("")
.app_data(Data::new(self))
.route(
web::method(Method::from_str("PROPFIND").unwrap()).to(actix_route_propfind::<Self>),
)
.route(
web::method(Method::from_str("PROPPATCH").unwrap())
.to(actix_route_proppatch::<Self>),
)
.delete(actix_route_delete::<Self>)
}
#[cfg(feature = "actix")]
fn actix_scope(self) -> actix_web::Scope
where
Self::Error: actix_web::ResponseError,
Self::Principal: actix_web::FromRequest;
#[cfg(feature = "axum")]
fn axum_service(self) -> AxumService<Self>
where
Self: Clone + Send + Sync + AxumMethods,
{
AxumService::new(Arc::new(self))
AxumService::new(self)
}
}

View File

@@ -3,7 +3,7 @@ use crate::extensions::{
CommonPropertiesExtension, CommonPropertiesProp, CommonPropertiesPropName,
};
use crate::privileges::UserPrivilegeSet;
use crate::resource::{PrincipalUri, Resource, ResourceService};
use crate::resource::{AxumMethods, PrincipalUri, Resource, ResourceService};
use crate::xml::{Resourcetype, ResourcetypeInner};
use async_trait::async_trait;
use std::marker::PhantomData;
@@ -74,15 +74,9 @@ impl<PRS: ResourceService<Principal = P> + Clone, P: Principal, PURI: PrincipalU
async fn get_resource(&self, _: &()) -> Result<Self::Resource, Self::Error> {
Ok(RootResource::<PRS::Resource, P>::default())
}
#[cfg(feature = "actix")]
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.actix_resource())
}
}
impl<PRS: ResourceService<Principal = P> + Clone, P: Principal, PURI: PrincipalUri> AxumMethods
for RootResourceService<PRS, P, PURI>
{
}

View File

@@ -1,8 +1,4 @@
use crate::xml::TagList;
#[cfg(feature = "actix")]
use actix_web::{
HttpRequest, HttpResponse, Responder, ResponseError, body::BoxBody, http::header::ContentType,
};
use http::StatusCode;
use quick_xml::name::Namespace;
use rustical_xml::{XmlRootTag, XmlSerialize, XmlSerializeRoot};
@@ -108,24 +104,6 @@ impl<T1: XmlSerialize, T2: XmlSerialize> Default for MultistatusElement<T1, T2>
}
}
#[cfg(feature = "actix")]
impl<T1: XmlSerialize, T2: XmlSerialize> Responder for MultistatusElement<T1, T2> {
type Body = BoxBody;
fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> {
let mut output: Vec<_> = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".into();
let mut writer = quick_xml::Writer::new_with_indent(&mut output, b' ', 4);
if let Err(err) = self.serialize_root(&mut writer) {
return crate::Error::from(err).error_response();
}
HttpResponse::MultiStatus()
.content_type(ContentType::xml())
.body(String::from_utf8(output).unwrap())
}
}
#[cfg(feature = "axum")]
impl<T1: XmlSerialize, T2: XmlSerialize> axum::response::IntoResponse
for MultistatusElement<T1, T2>
{