Add initial carddav support

This commit is contained in:
Lennart
2024-10-27 14:10:01 +01:00
parent 30a795b816
commit 86feb4e189
30 changed files with 2094 additions and 94 deletions

View File

@@ -7,22 +7,22 @@ repository.workspace = true
publish = false
[dependencies]
actix-web = "4.9"
actix-web-httpauth = "0.8"
anyhow = { version = "1.0", features = ["backtrace"] }
base64 = "0.22"
futures-util = "0.3"
quick-xml = { version = "0.36", features = [
"serde",
"serde-types",
"serialize",
] }
roxmltree = "0.20"
rustical_store = { path = "../store/" }
rustical_dav = { path = "../dav/" }
serde = { version = "1.0", features = ["serde_derive", "derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["sync", "full"] }
async-trait = "0.1"
thiserror = "1.0"
strum = { version = "0.26", features = ["strum_macros", "derive"] }
anyhow = { workspace = true }
actix-web = { workspace = true }
async-trait = { workspace = true }
thiserror = { workspace = true }
quick-xml = { workspace = true }
strum = { workspace = true }
tracing = { workspace = true }
tracing-actix-web = { workspace = true }
futures-util = { workspace = true }
derive_more = { workspace = true }
actix-web-httpauth = { workspace = true }
base64 = { workspace = true }
serde = { workspace = true }
tokio = { workspace = true }
roxmltree = { workspace = true }
url = { workspace = true }
rustical_dav = { workspace = true }
rustical_store = { workspace = true }
chrono = { workspace = true }

View File

@@ -0,0 +1,111 @@
use super::resource::AddressObjectPathComponents;
use crate::Error;
use actix_web::http::header;
use actix_web::http::header::HeaderValue;
use actix_web::web::{Data, Path};
use actix_web::HttpRequest;
use actix_web::HttpResponse;
use rustical_store::auth::User;
use rustical_store::model::AddressObject;
use rustical_store::AddressbookStore;
use tokio::sync::RwLock;
use tracing::instrument;
use tracing_actix_web::RootSpan;
#[instrument(parent = root_span.id(), skip(store, root_span))]
pub async fn get_object<AS: AddressbookStore + ?Sized>(
path: Path<AddressObjectPathComponents>,
store: Data<RwLock<AS>>,
user: User,
root_span: RootSpan,
) -> Result<HttpResponse, Error> {
let AddressObjectPathComponents {
principal,
cal_id,
object_id,
} = path.into_inner();
if user.id != principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
let addressbook = store
.read()
.await
.get_addressbook(&principal, &cal_id)
.await?;
if user.id != addressbook.principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
let object = store
.read()
.await
.get_object(&principal, &cal_id, &object_id)
.await?;
Ok(HttpResponse::Ok()
.insert_header(("ETag", object.get_etag()))
.insert_header(("Content-Type", "text/calendar"))
.body(object.get_vcf().to_owned()))
}
#[instrument(parent = root_span.id(), skip(store, req, root_span))]
pub async fn put_object<AS: AddressbookStore + ?Sized>(
path: Path<AddressObjectPathComponents>,
store: Data<RwLock<AS>>,
body: String,
user: User,
req: HttpRequest,
root_span: RootSpan,
) -> Result<HttpResponse, Error> {
let AddressObjectPathComponents {
principal,
cal_id: addressbook_id,
object_id,
} = path.into_inner();
if user.id != principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
let addressbook = store
.read()
.await
.get_addressbook(&principal, &addressbook_id)
.await?;
if user.id != addressbook.principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
// TODO: implement If-Match
//
let mut store_write = store.write().await;
if Some(&HeaderValue::from_static("*")) == req.headers().get(header::IF_NONE_MATCH) {
// Only write if not existing
match store_write
.get_object(&principal, &addressbook_id, &object_id)
.await
{
Ok(_) => {
// Conflict
return Ok(HttpResponse::Conflict().body("Resource with this URI already exists"));
}
Err(rustical_store::Error::NotFound) => {
// Path unused, we can proceed
}
Err(err) => {
// Some unknown error :(
return Err(err.into());
}
}
}
let object = AddressObject::from_vcf(object_id, body)?;
store_write
.put_object(principal, addressbook_id, object)
.await?;
Ok(HttpResponse::Created().body(""))
}

View File

@@ -0,0 +1,2 @@
pub mod methods;
pub mod resource;

View File

@@ -0,0 +1,167 @@
use crate::Error;
use actix_web::{dev::ResourceMap, web::Data, HttpRequest};
use async_trait::async_trait;
use derive_more::derive::{From, Into};
use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_store::{model::AddressObject, AddressbookStore};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
use super::methods::{get_object, put_object};
pub struct AddressObjectResourceService<AS: AddressbookStore + ?Sized> {
pub addr_store: Arc<RwLock<AS>>,
pub path: String,
pub principal: String,
pub cal_id: String,
pub object_id: String,
}
#[derive(EnumString, Debug, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum AddressObjectPropName {
Getetag,
AddressData,
Getcontenttype,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum AddressObjectProp {
// WebDAV (RFC 2518)
Getetag(String),
Getcontenttype(String),
// CalDAV (RFC 4791)
#[serde(rename = "CARD:address-data")]
AddressData(String),
#[serde(other)]
Invalid,
}
impl InvalidProperty for AddressObjectProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Clone, From, Into)]
pub struct AddressObjectResource(AddressObject);
impl Resource for AddressObjectResource {
type PropName = AddressObjectPropName;
type Prop = AddressObjectProp;
type Error = Error;
fn get_prop(
&self,
_rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
Ok(match prop {
AddressObjectPropName::Getetag => AddressObjectProp::Getetag(self.0.get_etag()),
AddressObjectPropName::AddressData => {
AddressObjectProp::AddressData(self.0.get_vcf().to_owned())
}
AddressObjectPropName::Getcontenttype => {
AddressObjectProp::Getcontenttype("text/calendar;charset=utf-8".to_owned())
}
})
}
#[inline]
fn resource_name() -> &'static str {
"caldav_calendar_object"
}
}
#[derive(Debug, Clone)]
pub struct AddressObjectPathComponents {
pub principal: String,
pub cal_id: String,
pub object_id: String,
}
impl<'de> Deserialize<'de> for AddressObjectPathComponents {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
type Inner = (String, String, String);
let (principal, calendar, mut object) = Inner::deserialize(deserializer)?;
if object.ends_with(".ics") {
object.truncate(object.len() - 4);
}
Ok(Self {
principal,
cal_id: calendar,
object_id: object,
})
}
}
#[async_trait(?Send)]
impl<AS: AddressbookStore + ?Sized> ResourceService for AddressObjectResourceService<AS> {
type PathComponents = AddressObjectPathComponents;
type Resource = AddressObjectResource;
type MemberType = AddressObjectResource;
type Error = Error;
async fn new(
req: &HttpRequest,
path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
let AddressObjectPathComponents {
principal,
cal_id,
object_id,
} = path_components;
let addr_store = req
.app_data::<Data<RwLock<AS>>>()
.expect("no addressbook store in app_data!")
.clone()
.into_inner();
Ok(Self {
addr_store,
principal,
cal_id,
object_id,
path: req.path().to_string(),
})
}
async fn get_resource(&self, principal: String) -> Result<Self::Resource, Self::Error> {
if self.principal != principal {
return Err(Error::Unauthorized);
}
let event = self
.addr_store
.read()
.await
.get_object(&self.principal, &self.cal_id, &self.object_id)
.await?;
Ok(event.into())
}
async fn save_resource(&self, _file: Self::Resource) -> Result<(), Self::Error> {
Err(Error::NotImplemented)
}
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> {
self.addr_store
.write()
.await
.delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin)
.await?;
Ok(())
}
#[inline]
fn actix_additional_routes(res: actix_web::Resource) -> actix_web::Resource {
res.get(get_object::<AS>).put(put_object::<AS>)
}
}

View File

@@ -0,0 +1,90 @@
use crate::Error;
use actix_web::web::Path;
use actix_web::{web::Data, HttpResponse};
use rustical_store::model::Addressbook;
use rustical_store::{auth::User, AddressbookStore};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct Resourcetype {
#[serde(rename = "CARD:addressbook", alias = "addressbook")]
addressbook: Option<()>,
collection: Option<()>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct MkcolAddressbookProp {
resourcetype: Option<Resourcetype>,
displayname: Option<String>,
description: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PropElement<T: Serialize> {
prop: T,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
#[serde(rename = "mkcol")]
struct MkcolRequest {
set: PropElement<MkcolAddressbookProp>,
}
pub async fn route_mkcol<AS: AddressbookStore + ?Sized>(
path: Path<(String, String)>,
body: String,
user: User,
store: Data<RwLock<AS>>,
) -> Result<HttpResponse, Error> {
let (principal, addressbook_id) = path.into_inner();
if principal != user.id {
return Err(Error::Unauthorized);
}
let request: MkcolRequest = quick_xml::de::from_str(&body)?;
let request = request.set.prop;
let addressbook = Addressbook {
id: addressbook_id.to_owned(),
principal: principal.to_owned(),
displayname: request.displayname,
description: request.description,
deleted_at: None,
synctoken: 0,
};
match store
.read()
.await
.get_addressbook(&principal, &addressbook_id)
.await
{
Err(rustical_store::Error::NotFound) => {
// No conflict, no worries
}
Ok(_) => {
// oh no, there's a conflict
return Ok(HttpResponse::Conflict().body("An addressbook already exists at this URI"));
}
Err(err) => {
// some other error
return Err(err.into());
}
}
match store.write().await.insert_addressbook(addressbook).await {
// TODO: The spec says we should return a mkcol-response.
// However, it works without one but breaks on iPadOS when using an empty one :)
Ok(()) => Ok(HttpResponse::Created()
.insert_header(("Cache-Control", "no-cache"))
.body("")),
Err(err) => {
dbg!(err.to_string());
Err(err.into())
}
}
}

View File

@@ -0,0 +1,2 @@
pub mod mkcol;
pub mod report;

View File

@@ -0,0 +1,118 @@
use crate::{
address_object::resource::{AddressObjectProp, AddressObjectResource},
principal::PrincipalResource,
Error,
};
use actix_web::{
dev::{Path, ResourceDef},
http::StatusCode,
HttpRequest,
};
use rustical_dav::{
methods::propfind::{PropElement, PropfindType},
resource::Resource,
xml::{
multistatus::{PropstatWrapper, ResponseElement},
MultistatusElement,
},
};
use rustical_store::{model::AddressObject, AddressbookStore};
use serde::Deserialize;
use tokio::sync::RwLock;
#[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
#[allow(dead_code)]
pub struct AddressbookMultigetRequest {
#[serde(flatten)]
prop: PropfindType,
href: Vec<String>,
}
pub async fn get_objects_addressbook_multiget<AS: AddressbookStore + ?Sized>(
addressbook_multiget: &AddressbookMultigetRequest,
principal_url: &str,
principal: &str,
addressbook_id: &str,
store: &RwLock<AS>,
) -> Result<(Vec<AddressObject>, Vec<String>), Error> {
let resource_def =
ResourceDef::prefix(principal_url).join(&ResourceDef::new("/{addressbook_id}/{object_id}"));
let mut result = vec![];
let mut not_found = vec![];
let store = store.read().await;
for href in &addressbook_multiget.href {
let mut path = Path::new(href.as_str());
if !resource_def.capture_match_info(&mut path) {
not_found.push(href.to_owned());
};
if path.get("addressbook_id").unwrap() != addressbook_id {
not_found.push(href.to_owned());
}
let object_id = path.get("object_id").unwrap();
match store.get_object(principal, addressbook_id, object_id).await {
Ok(object) => result.push(object),
Err(rustical_store::Error::NotFound) => not_found.push(href.to_owned()),
// TODO: Maybe add error handling on a per-object basis
Err(err) => return Err(err.into()),
};
}
Ok((result, not_found))
}
pub async fn handle_addressbook_multiget<AS: AddressbookStore + ?Sized>(
addr_multiget: AddressbookMultigetRequest,
req: HttpRequest,
principal: &str,
cal_id: &str,
addr_store: &RwLock<AS>,
) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> {
let principal_url = PrincipalResource::get_url(req.resource_map(), vec![principal]).unwrap();
let (objects, not_found) = get_objects_addressbook_multiget(
&addr_multiget,
&principal_url,
principal,
cal_id,
addr_store,
)
.await?;
let props = match addr_multiget.prop {
PropfindType::Allprop => {
vec!["allprop".to_owned()]
}
PropfindType::Propname => {
vec!["propname".to_owned()]
}
PropfindType::Prop(PropElement { prop: prop_tags }) => prop_tags.into_inner(),
};
let props: Vec<&str> = props.iter().map(String::as_str).collect();
let mut responses = Vec::new();
for object in objects {
let path = format!("{}/{}", req.path(), object.get_id());
responses.push(AddressObjectResource::from(object).propfind(
&path,
props.clone(),
req.resource_map(),
)?);
}
let not_found_responses = not_found
.into_iter()
.map(|path| ResponseElement {
href: path,
status: Some(format!("HTTP/1.1 {}", StatusCode::NOT_FOUND)),
..Default::default()
})
.collect();
Ok(MultistatusElement {
responses,
member_responses: not_found_responses,
..Default::default()
})
}

View File

@@ -0,0 +1,68 @@
use crate::Error;
use actix_web::{
web::{Data, Path},
HttpRequest, Responder,
};
use addressbook_multiget::{handle_addressbook_multiget, AddressbookMultigetRequest};
use rustical_store::{auth::User, AddressbookStore};
use serde::{Deserialize, Serialize};
use sync_collection::{handle_sync_collection, SyncCollectionRequest};
use tokio::sync::RwLock;
use tracing::instrument;
mod addressbook_multiget;
mod sync_collection;
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum PropQuery {
Allprop,
Prop,
Propname,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum ReportRequest {
AddressbookMultiget(AddressbookMultigetRequest),
SyncCollection(SyncCollectionRequest),
}
#[instrument(skip(req, addr_store))]
pub async fn route_report_addressbook<AS: AddressbookStore + ?Sized>(
path: Path<(String, String)>,
body: String,
user: User,
req: HttpRequest,
addr_store: Data<RwLock<AS>>,
) -> Result<impl Responder, Error> {
let (principal, addressbook_id) = path.into_inner();
if principal != user.id {
return Err(Error::Unauthorized);
}
let request: ReportRequest = quick_xml::de::from_str(&body)?;
Ok(match request.clone() {
ReportRequest::AddressbookMultiget(addr_multiget) => {
handle_addressbook_multiget(
addr_multiget,
req,
&principal,
&addressbook_id,
&addr_store,
)
.await?
}
ReportRequest::SyncCollection(sync_collection) => {
handle_sync_collection(
sync_collection,
req,
&principal,
&addressbook_id,
&addr_store,
)
.await?
}
})
}

View File

@@ -0,0 +1,100 @@
use crate::{
address_object::resource::{AddressObjectProp, AddressObjectResource},
Error,
};
use actix_web::{http::StatusCode, HttpRequest};
use rustical_dav::{
methods::propfind::{PropElement, PropfindType},
resource::Resource,
xml::{
multistatus::{PropstatWrapper, ResponseElement},
MultistatusElement,
},
};
use rustical_store::{
model::addressbook::{format_synctoken, parse_synctoken},
AddressbookStore,
};
use serde::Deserialize;
use tokio::sync::RwLock;
#[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
enum SyncLevel {
#[serde(rename = "1")]
One,
Infinity,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
#[allow(dead_code)]
// <!ELEMENT sync-collection (sync-token, sync-level, limit?, prop)>
// <!-- DAV:limit defined in RFC 5323, Section 5.17 -->
// <!-- DAV:prop defined in RFC 4918, Section 14.18 -->
pub struct SyncCollectionRequest {
sync_token: String,
sync_level: SyncLevel,
#[serde(flatten)]
pub prop: PropfindType,
limit: Option<u64>,
}
pub async fn handle_sync_collection<AS: AddressbookStore + ?Sized>(
sync_collection: SyncCollectionRequest,
req: HttpRequest,
principal: &str,
addressbook_id: &str,
addr_store: &RwLock<AS>,
) -> Result<MultistatusElement<PropstatWrapper<AddressObjectProp>, String>, Error> {
let props = match sync_collection.prop {
PropfindType::Allprop => {
vec!["allprop".to_owned()]
}
PropfindType::Propname => {
vec!["propname".to_owned()]
}
PropfindType::Prop(PropElement { prop: prop_tags }) => prop_tags.into_inner(),
};
let props: Vec<&str> = props.iter().map(String::as_str).collect();
let old_synctoken = parse_synctoken(&sync_collection.sync_token).unwrap_or(0);
let (new_objects, deleted_objects, new_synctoken) = addr_store
.read()
.await
.sync_changes(principal, addressbook_id, old_synctoken)
.await?;
let mut responses = Vec::new();
for object in new_objects {
let path = AddressObjectResource::get_url(
req.resource_map(),
vec![principal, addressbook_id, &object.get_id()],
)
.unwrap();
responses.push(AddressObjectResource::from(object).propfind(
&path,
props.clone(),
req.resource_map(),
)?);
}
for object_id in deleted_objects {
let path = AddressObjectResource::get_url(
req.resource_map(),
vec![principal, addressbook_id, &object_id],
)
.unwrap();
responses.push(ResponseElement {
href: path,
status: Some(format!("HTTP/1.1 {}", StatusCode::NOT_FOUND)),
..Default::default()
});
}
Ok(MultistatusElement {
responses,
sync_token: Some(format_synctoken(new_synctoken)),
..Default::default()
})
}

View File

@@ -0,0 +1,3 @@
pub mod methods;
pub mod prop;
pub mod resource;

View File

@@ -0,0 +1,137 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct AddressDataType {
#[serde(rename = "@content-type")]
pub content_type: String,
#[serde(rename = "@version")]
pub version: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedAddressData {
#[serde(rename = "CARD:address-data-type", alias = "address-data-type")]
address_data_type: Vec<AddressDataType>,
}
impl Default for SupportedAddressData {
fn default() -> Self {
Self {
address_data_type: vec![
AddressDataType {
content_type: "text/vcard".to_owned(),
version: "3.0".to_owned(),
},
AddressDataType {
content_type: "text/vcard".to_owned(),
version: "4.0".to_owned(),
},
],
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct Resourcetype {
#[serde(rename = "CARD:addressbook", alias = "addressbook")]
addressbook: (),
collection: (),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum UserPrivilege {
Read,
ReadAcl,
Write,
WriteAcl,
WriteContent,
ReadCurrentUserPrivilegeSet,
Bind,
Unbind,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct UserPrivilegeWrapper {
#[serde(rename = "$value")]
privilege: UserPrivilege,
}
impl From<UserPrivilege> for UserPrivilegeWrapper {
fn from(value: UserPrivilege) -> Self {
Self { privilege: value }
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct UserPrivilegeSet {
privilege: Vec<UserPrivilegeWrapper>,
}
impl Default for UserPrivilegeSet {
fn default() -> Self {
Self {
privilege: vec![
UserPrivilege::Read.into(),
UserPrivilege::ReadAcl.into(),
UserPrivilege::Write.into(),
UserPrivilege::WriteAcl.into(),
UserPrivilege::WriteContent.into(),
UserPrivilege::ReadCurrentUserPrivilegeSet.into(),
UserPrivilege::Bind.into(),
UserPrivilege::Unbind.into(),
],
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ReportMethod {
AddressbookMultiget,
SyncCollection,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct ReportWrapper {
#[serde(rename = "$value")]
report: ReportMethod,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedReportWrapper {
report: ReportWrapper,
}
impl From<ReportMethod> for SupportedReportWrapper {
fn from(value: ReportMethod) -> Self {
Self {
report: ReportWrapper { report: value },
}
}
}
// RFC 3253 section-3.1.5
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedReportSet {
supported_report: Vec<SupportedReportWrapper>,
}
impl Default for SupportedReportSet {
fn default() -> Self {
Self {
supported_report: vec![
ReportMethod::AddressbookMultiget.into(),
ReportMethod::SyncCollection.into(),
],
}
}
}

View File

@@ -0,0 +1,286 @@
use super::methods::mkcol::route_mkcol;
use super::methods::report::route_report_addressbook;
use super::prop::{Resourcetype, SupportedAddressData, SupportedReportSet, UserPrivilegeSet};
use crate::address_object::resource::AddressObjectResource;
use crate::principal::PrincipalResource;
use crate::Error;
use actix_web::dev::ResourceMap;
use actix_web::http::Method;
use actix_web::web;
use actix_web::{web::Data, HttpRequest};
use async_trait::async_trait;
use derive_more::derive::{From, Into};
use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_dav::xml::HrefElement;
use rustical_store::model::Addressbook;
use rustical_store::AddressbookStore;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use std::sync::Arc;
use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
pub struct AddressbookResourceService<AS: AddressbookStore + ?Sized> {
pub addr_store: Arc<RwLock<AS>>,
pub path: String,
pub principal: String,
pub addressbook_id: String,
}
#[derive(EnumString, Debug, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum AddressbookPropName {
Resourcetype,
Displayname,
Getcontenttype,
CurrentUserPrincipal,
Owner,
CurrentUserPrivilegeSet,
AddressbookDescription,
SupportedAddressData,
SupportedReportSet,
MaxResourceSize,
SyncToken,
Getctag,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum AddressbookProp {
// WebDAV (RFC 2518)
Resourcetype(Resourcetype),
Displayname(Option<String>),
Getcontenttype(String),
// WebDAV Current Principal Extension (RFC 5397)
CurrentUserPrincipal(HrefElement),
// WebDAV Access Control (RFC 3744)
Owner(HrefElement),
CurrentUserPrivilegeSet(UserPrivilegeSet),
// CardDAV (RFC 6352)
#[serde(
rename = "CARD:addressbook-description",
alias = "addressbook-description"
)]
AddressbookDescription(Option<String>),
#[serde(
rename = "CARD:supported-address-data",
alias = "supported-address-data"
)]
SupportedAddressData(SupportedAddressData),
SupportedReportSet(SupportedReportSet),
MaxResourceSize(i64),
// Collection Synchronization (RFC 6578)
SyncToken(String),
// Didn't find the spec
Getctag(String),
#[serde(other)]
Invalid,
}
impl InvalidProperty for AddressbookProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Clone, Debug, From, Into)]
pub struct AddressbookResource(Addressbook);
impl Resource for AddressbookResource {
type PropName = AddressbookPropName;
type Prop = AddressbookProp;
type Error = Error;
fn get_prop(
&self,
rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
Ok(match prop {
AddressbookPropName::Resourcetype => {
AddressbookProp::Resourcetype(Resourcetype::default())
}
AddressbookPropName::CurrentUserPrincipal => {
AddressbookProp::CurrentUserPrincipal(HrefElement::new(
PrincipalResource::get_url(rmap, vec![&self.0.principal]).unwrap(),
))
}
AddressbookPropName::Owner => AddressbookProp::Owner(HrefElement::new(
PrincipalResource::get_url(rmap, vec![&self.0.principal]).unwrap(),
)),
AddressbookPropName::Displayname => {
AddressbookProp::Displayname(self.0.displayname.clone())
}
AddressbookPropName::Getcontenttype => {
AddressbookProp::Getcontenttype("text/vcard;charset=utf-8".to_owned())
}
AddressbookPropName::MaxResourceSize => AddressbookProp::MaxResourceSize(10000000),
AddressbookPropName::CurrentUserPrivilegeSet => {
AddressbookProp::CurrentUserPrivilegeSet(UserPrivilegeSet::default())
}
AddressbookPropName::SupportedReportSet => {
AddressbookProp::SupportedReportSet(SupportedReportSet::default())
}
AddressbookPropName::AddressbookDescription => {
AddressbookProp::AddressbookDescription(self.0.description.to_owned())
}
AddressbookPropName::SupportedAddressData => {
AddressbookProp::SupportedAddressData(SupportedAddressData::default())
}
AddressbookPropName::SyncToken => AddressbookProp::SyncToken(self.0.format_synctoken()),
AddressbookPropName::Getctag => AddressbookProp::Getctag(self.0.format_synctoken()),
})
}
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> {
match prop {
AddressbookProp::Resourcetype(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::CurrentUserPrincipal(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::Owner(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::Displayname(displayname) => {
self.0.displayname = displayname;
Ok(())
}
AddressbookProp::AddressbookDescription(description) => {
self.0.description = description;
Ok(())
}
AddressbookProp::Getcontenttype(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::MaxResourceSize(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::CurrentUserPrivilegeSet(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::SupportedReportSet(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::SupportedAddressData(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::SyncToken(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::Getctag(_) => Err(rustical_dav::Error::PropReadOnly),
AddressbookProp::Invalid => Err(rustical_dav::Error::PropReadOnly),
}
}
fn remove_prop(&mut self, prop: Self::PropName) -> Result<(), rustical_dav::Error> {
match prop {
AddressbookPropName::Resourcetype => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::CurrentUserPrincipal => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::Owner => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::Displayname => {
self.0.displayname = None;
Ok(())
}
AddressbookPropName::AddressbookDescription => {
self.0.description = None;
Ok(())
}
AddressbookPropName::Getcontenttype => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::MaxResourceSize => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::CurrentUserPrivilegeSet => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::SupportedReportSet => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::SupportedAddressData => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::SyncToken => Err(rustical_dav::Error::PropReadOnly),
AddressbookPropName::Getctag => Err(rustical_dav::Error::PropReadOnly),
}
}
#[inline]
fn resource_name() -> &'static str {
"carddav_addressbook"
}
}
#[async_trait(?Send)]
impl<AS: AddressbookStore + ?Sized> ResourceService for AddressbookResourceService<AS> {
type MemberType = AddressObjectResource;
type PathComponents = (String, String); // principal, addressbook_id
type Resource = AddressbookResource;
type Error = Error;
async fn get_resource(&self, principal: String) -> Result<Self::Resource, Error> {
if self.principal != principal {
return Err(Error::Unauthorized);
}
let addressbook = self
.addr_store
.read()
.await
.get_addressbook(&self.principal, &self.addressbook_id)
.await
.map_err(|_e| Error::NotFound)?;
Ok(addressbook.into())
}
async fn get_members(
&self,
rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(self
.addr_store
.read()
.await
.get_objects(&self.principal, &self.addressbook_id)
.await?
.into_iter()
.map(|object| {
(
AddressObjectResource::get_url(
rmap,
vec![&self.principal, &self.addressbook_id, object.get_id()],
)
.unwrap(),
object.into(),
)
})
.collect())
}
async fn new(
req: &HttpRequest,
path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
let addr_store = req
.app_data::<Data<RwLock<AS>>>()
.expect("no addressbook store in app_data!")
.clone()
.into_inner();
Ok(Self {
path: req.path().to_owned(),
principal: path_components.0,
addressbook_id: path_components.1,
addr_store,
})
}
async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error> {
self.addr_store
.write()
.await
.update_addressbook(
self.principal.to_owned(),
self.addressbook_id.to_owned(),
file.into(),
)
.await?;
Ok(())
}
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> {
self.addr_store
.write()
.await
.delete_addressbook(&self.principal, &self.addressbook_id, use_trashbin)
.await?;
Ok(())
}
#[inline]
fn actix_additional_routes(res: actix_web::Resource) -> actix_web::Resource {
let mkcol_method = web::method(Method::from_str("MKCOL").unwrap());
let report_method = web::method(Method::from_str("REPORT").unwrap());
res.route(mkcol_method.to(route_mkcol::<AS>))
.route(report_method.to(route_report_addressbook::<AS>))
}
}

View File

@@ -0,0 +1,49 @@
use actix_web::{http::StatusCode, HttpResponse};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Unauthorized")]
Unauthorized,
#[error("Not Found")]
NotFound,
#[error("Not implemented")]
NotImplemented,
#[error(transparent)]
StoreError(#[from] rustical_store::Error),
#[error(transparent)]
DavError(#[from] rustical_dav::Error),
#[error(transparent)]
XmlDecodeError(#[from] quick_xml::DeError),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
impl actix_web::ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
match self {
Error::StoreError(err) => match err {
rustical_store::Error::NotFound => StatusCode::NOT_FOUND,
rustical_store::Error::InvalidIcs(_) => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR,
},
Error::DavError(err) => err.status_code(),
Error::Unauthorized => StatusCode::UNAUTHORIZED,
Error::XmlDecodeError(_) => StatusCode::BAD_REQUEST,
Error::NotImplemented => 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> {
match self {
Error::DavError(err) => err.error_response(),
_ => HttpResponse::build(self.status_code()).body(self.to_string()),
}
}
}

View File

@@ -1,17 +1,81 @@
use actix_web::{web, HttpResponse, Responder};
use actix_web::{
dev::Service,
http::{
header::{HeaderName, HeaderValue},
Method, StatusCode,
},
web::{self, Data},
};
use address_object::resource::AddressObjectResourceService;
use addressbook::resource::AddressbookResourceService;
pub use error::Error;
use futures_util::FutureExt;
use principal::PrincipalResourceService;
use root::RootResourceService;
use rustical_dav::resource::ResourceService;
use rustical_store::{
auth::{AuthenticationMiddleware, AuthenticationProvider},
AddressbookStore,
};
use std::sync::Arc;
use tokio::sync::RwLock;
pub mod address_object;
pub mod addressbook;
pub mod error;
pub mod principal;
pub mod root;
pub fn configure_well_known(cfg: &mut web::ServiceConfig, carddav_root: String) {
cfg.service(web::redirect("/carddav", carddav_root).permanent());
}
pub fn configure_dav(_cfg: &mut web::ServiceConfig, _prefix: String) {}
pub async fn options_handler() -> impl Responder {
HttpResponse::Ok()
.insert_header((
"Allow",
"OPTIONS, GET, HEAD, POST, PUT, REPORT, PROPFIND, PROPPATCH, MKCOL",
))
.insert_header(("DAV", "1, 2, 3, addressbook, extended-mkcol"))
.body("options")
pub fn configure_dav<AP: AuthenticationProvider, A: AddressbookStore + ?Sized>(
cfg: &mut web::ServiceConfig,
auth_provider: Arc<AP>,
store: Arc<RwLock<A>>,
) {
cfg.service(
web::scope("")
.wrap(AuthenticationMiddleware::new(auth_provider))
.wrap_fn(|req, srv| {
// Middleware to set the DAV header
// Could be more elegant if actix_web::guard::RegisteredMethods was public :(
let method = req.method().clone();
srv.call(req).map(move |res| {
if method == Method::OPTIONS {
return res.map(|mut response| {
if response.status() == StatusCode::METHOD_NOT_ALLOWED {
response.headers_mut().insert(
HeaderName::from_static("dav"),
HeaderValue::from_static(
"1, 2, 3, access-control, addressbook, extended-mkcol",
),
);
*response.response_mut().status_mut() = StatusCode::OK;
}
response
});
}
res
})
})
.app_data(Data::from(store.clone()))
.service(RootResourceService::actix_resource())
.service(
web::scope("/user").service(
web::scope("/{principal}")
.service(PrincipalResourceService::<A>::actix_resource())
.service(
web::scope("/{addressbook}")
.service(AddressbookResourceService::<A>::actix_resource())
.service(
web::scope("/{object}").service(
AddressObjectResourceService::<A>::actix_resource(),
),
),
),
),
),
);
}

View File

@@ -0,0 +1,159 @@
use crate::addressbook::resource::AddressbookResource;
use crate::Error;
use actix_web::dev::ResourceMap;
use actix_web::web::Data;
use actix_web::HttpRequest;
use async_trait::async_trait;
use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_dav::xml::HrefElement;
use rustical_store::AddressbookStore;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
pub struct PrincipalResourceService<A: AddressbookStore + ?Sized> {
principal: String,
addr_store: Arc<RwLock<A>>,
}
#[derive(Clone)]
pub struct PrincipalResource {
principal: String,
}
#[derive(Deserialize, Serialize, Default, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct Resourcetype {
principal: (),
collection: (),
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum PrincipalProp {
// WebDAV (RFC 2518)
Resourcetype(Resourcetype),
// WebDAV Access Control (RFC 3744)
#[serde(rename = "principal-URL")]
PrincipalUrl(HrefElement),
// WebDAV Current Principal Extension (RFC 5397)
CurrentUserPrincipal(HrefElement),
// CardDAV (RFC 6352)
#[serde(rename = "CARD:addressbook-home-set")]
AddressbookHomeSet(HrefElement),
#[serde(rename = "CARD:principal-address")]
PrincipalAddress(Option<HrefElement>),
#[serde(other)]
Invalid,
}
impl InvalidProperty for PrincipalProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(EnumString, Debug, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum PrincipalPropName {
Resourcetype,
CurrentUserPrincipal,
#[strum(serialize = "principal-URL")]
PrincipalUrl,
AddressbookHomeSet,
PrincipalAddress,
}
impl Resource for PrincipalResource {
type PropName = PrincipalPropName;
type Prop = PrincipalProp;
type Error = Error;
fn get_prop(
&self,
rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
let principal_href = HrefElement::new(Self::get_url(rmap, vec![&self.principal]).unwrap());
Ok(match prop {
PrincipalPropName::Resourcetype => PrincipalProp::Resourcetype(Resourcetype::default()),
PrincipalPropName::CurrentUserPrincipal => {
PrincipalProp::CurrentUserPrincipal(principal_href)
}
PrincipalPropName::PrincipalUrl => PrincipalProp::PrincipalUrl(principal_href),
PrincipalPropName::AddressbookHomeSet => {
PrincipalProp::AddressbookHomeSet(principal_href)
}
PrincipalPropName::PrincipalAddress => PrincipalProp::PrincipalAddress(None),
})
}
#[inline]
fn resource_name() -> &'static str {
"carddav_principal"
}
}
#[async_trait(?Send)]
impl<A: AddressbookStore + ?Sized> ResourceService for PrincipalResourceService<A> {
type PathComponents = (String,);
type MemberType = AddressbookResource;
type Resource = PrincipalResource;
type Error = Error;
async fn new(
req: &HttpRequest,
(principal,): Self::PathComponents,
) -> Result<Self, Self::Error> {
let addr_store = req
.app_data::<Data<RwLock<A>>>()
.expect("no addressbook store in app_data!")
.clone()
.into_inner();
Ok(Self {
addr_store,
principal,
})
}
async fn get_resource(&self, principal: String) -> Result<Self::Resource, Self::Error> {
if self.principal != principal {
return Err(Error::Unauthorized);
}
Ok(PrincipalResource {
principal: self.principal.to_owned(),
})
}
async fn get_members(
&self,
rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
let addressbooks = self
.addr_store
.read()
.await
.get_addressbooks(&self.principal)
.await?;
Ok(addressbooks
.into_iter()
.map(|addressbook| {
(
AddressbookResource::get_url(rmap, vec![&self.principal, &addressbook.id])
.unwrap(),
addressbook.into(),
)
})
.collect())
}
async fn save_resource(&self, _file: Self::Resource) -> Result<(), Self::Error> {
Err(Error::NotImplemented)
}
}

View File

@@ -0,0 +1,95 @@
use crate::principal::PrincipalResource;
use crate::Error;
use actix_web::dev::ResourceMap;
use actix_web::HttpRequest;
use async_trait::async_trait;
use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_dav::xml::HrefElement;
use serde::{Deserialize, Serialize};
use strum::{EnumString, VariantNames};
#[derive(EnumString, Debug, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum RootPropName {
Resourcetype,
// Defined by RFC 5397
CurrentUserPrincipal,
}
#[derive(Deserialize, Serialize, Default, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct Resourcetype {
collection: (),
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum RootProp {
// WebDAV (RFC 2518)
Resourcetype(Resourcetype),
// WebDAV Current Principal Extension (RFC 5397)
CurrentUserPrincipal(HrefElement),
#[serde(other)]
Invalid,
}
impl InvalidProperty for RootProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Clone)]
pub struct RootResource {
principal: String,
}
impl Resource for RootResource {
type PropName = RootPropName;
type Prop = RootProp;
type Error = Error;
fn get_prop(
&self,
rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
Ok(match prop {
RootPropName::Resourcetype => RootProp::Resourcetype(Resourcetype::default()),
RootPropName::CurrentUserPrincipal => RootProp::CurrentUserPrincipal(HrefElement::new(
PrincipalResource::get_url(rmap, vec![&self.principal]).unwrap(),
)),
})
}
#[inline]
fn resource_name() -> &'static str {
"carddav_root"
}
}
pub struct RootResourceService;
#[async_trait(?Send)]
impl ResourceService for RootResourceService {
type PathComponents = ();
type MemberType = PrincipalResource;
type Resource = RootResource;
type Error = Error;
async fn new(
_req: &HttpRequest,
_path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
Ok(Self)
}
async fn get_resource(&self, principal: String) -> Result<Self::Resource, Self::Error> {
Ok(RootResource { principal })
}
async fn save_resource(&self, _file: Self::Resource) -> Result<(), Self::Error> {
Err(Error::NotImplemented)
}
}