diff --git a/crates/common/src/auth/oauth/introspect.rs b/crates/common/src/auth/oauth/introspect.rs index 39a4c3ba..0a5bea5e 100644 --- a/crates/common/src/auth/oauth/introspect.rs +++ b/crates/common/src/auth/oauth/introspect.rs @@ -2,11 +2,13 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ -use crate::{Server, auth::AccessToken}; +use crate::{Server, auth::oauth::GrantType}; use serde::{Deserialize, Serialize}; -use trc::{AddContext, AuthEvent, EventType}; +use trc::{AuthEvent, EventType}; #[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)] pub struct OAuthIntrospect { @@ -47,26 +49,29 @@ pub struct OAuthIntrospect { } impl Server { - pub async fn introspect_access_token( - &self, - token: &str, - access_token: &AccessToken, - ) -> trc::Result { - match self.validate_access_token(None, token).await { - Ok(token_info) => Ok(OAuthIntrospect { - active: true, - username: self - .account(access_token.account_id()) - .await - .caused_by(trc::location!())? - .name() - .to_string() - .into(), - token_type: Some("bearer".into()), - exp: Some(token_info.expiry as i64), - iat: Some(token_info.issued_at as i64), - ..Default::default() - }), + pub async fn introspect_access_token(&self, token: &str) -> trc::Result { + // inbuxa: only an access token is active; refresh, RSVP and live + // tokens can't be presented as a bearer token + match self + .validate_access_token(Some(GrantType::AccessToken), token) + .await + { + // inbuxa: the token is described by its owner, not by whoever + // asks; a token whose account is gone is inactive + Ok(token_info) => match self.account(token_info.account_id).await { + Ok(owner) => Ok(OAuthIntrospect { + active: true, + username: owner.name().to_string().into(), + token_type: Some("bearer".into()), + exp: Some(token_info.expiry as i64), + iat: Some(token_info.issued_at as i64), + ..Default::default() + }), + Err(err) if err.matches(EventType::Auth(AuthEvent::Error)) => { + Ok(OAuthIntrospect::default()) + } + Err(err) => Err(err.caused_by(trc::location!())), + }, Err(err) if matches!( err.event_type(), diff --git a/crates/common/src/network/dns/update.rs b/crates/common/src/network/dns/update.rs index 3fa1c13d..2ada2d15 100644 --- a/crates/common/src/network/dns/update.rs +++ b/crates/common/src/network/dns/update.rs @@ -1202,13 +1202,27 @@ impl DnsUpdater { records: Vec, ) -> Result<(), String> { check_zone(origin, name)?; + self.replace_rrset(origin, name, record_type, records) + .await + .map_err(|err| format!("Failed to set DNS RRSet: {}", err)) + } + + /// inbuxa: `set_rrset` with the provider's error as it came, so a caller + /// can tell a failure that may pass from one that won't. + pub async fn replace_rrset( + &self, + origin: &str, + name: &str, + record_type: DnsRecordType, + records: Vec, + ) -> dns_update::Result<()> { + check_zone(origin, name).map_err(dns_update::Error::Client)?; let record_values = records .iter() .map(|r| trc::Value::String(r.to_string().into())) .collect::>(); - if let Err(err) = self - .updater + self.updater .set_rrset( name, record_type, @@ -1216,10 +1230,7 @@ impl DnsUpdater { records, origin, ) - .await - { - return Err(format!("Failed to set DNS RRSet: {}", err)); - } + .await?; trc::event!( Dns(DnsEvent::RecordCreated), diff --git a/crates/dav/src/calendar/copy_move.rs b/crates/dav/src/calendar/copy_move.rs index 66614fd7..8e301148 100644 --- a/crates/dav/src/calendar/copy_move.rs +++ b/crates/dav/src/calendar/copy_move.rs @@ -6,7 +6,7 @@ * Modified by Coffey Labs in 2026 for INBUXA. */ -use super::assert_is_unique_uid; +use super::{assert_is_unique_uid, privacy::check_copy_out}; use crate::{ DavError, DavMethod, common::{ @@ -545,6 +545,15 @@ async fn copy_event( let mut new_event = event .deserialize::() .caused_by(trc::location!())?; + // inbuxa: a sharee takes out only what it may + check_copy_out( + server, + access_token, + from_account_id, + from_document_id, + &mut new_event, + ) + .await?; new_event.names = vec![DavName { name: new_name.to_string(), parent_id: to_calendar_id, @@ -714,6 +723,15 @@ async fn move_event( let mut new_event = event .deserialize::() .caused_by(trc::location!())?; + // inbuxa: a sharee takes out only what it may + check_copy_out( + server, + access_token, + from_account_id, + from_document_id, + &mut new_event, + ) + .await?; new_event.names = vec![DavName { name: new_name.to_string(), parent_id: to_calendar_id, @@ -1036,6 +1054,15 @@ async fn copy_container( ) .caused_by(trc::location!())?; } else { + // inbuxa: a sharee takes out only what it may + check_copy_out( + server, + access_token, + from_account_id, + from_child_document_id, + &mut new_event, + ) + .await?; let next_email_alarm = event.inner.data.next_alarm(now() as i64, Tz::Floating); if remove_source { DestroyArchive(event) diff --git a/crates/dav/src/calendar/get.rs b/crates/dav/src/calendar/get.rs index f786aeaf..f7c5e62d 100644 --- a/crates/dav/src/calendar/get.rs +++ b/crates/dav/src/calendar/get.rs @@ -2,10 +2,13 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use crate::{ DavError, DavMethod, + calendar::privacy::ShareeView, common::{ ETag, lock::{LockRequestHandler, ResourceState}, @@ -14,7 +17,10 @@ use crate::{ }; use common::{Server, auth::AccessToken}; use dav_proto::{RequestHeaders, schema::property::Rfc1123DateTime}; -use groupware::{cache::GroupwareCache, calendar::CalendarEvent}; +use groupware::{ + cache::GroupwareCache, + calendar::{CalendarEvent, privacy::archived_event_view}, +}; use http_proto::HttpResponse; use hyper::StatusCode; use store::{ @@ -119,7 +125,39 @@ impl CalendarGetRequestHandler for Server { .with_schedule_tag_opt(schedule_tag) .with_last_modified(Rfc1123DateTime::new(i64::from(event.modified)).to_string()); - let ical = event.data.event.to_string(); + // inbuxa: a reader who isn't the calendar's owner gets the event as + // JMAP shows it + let view = if !access_token.reads_as_owner(account_id) { + ShareeView::new(archived_event_view(event), || { + resources + .shared_items(access_token, [Acl::ModifyItems], true) + .contains(resource.document_id()) + }) + } else { + None + }; + let ical = if let Some(view) = view { + let mut event = event_ + .deserialize::() + .caused_by(trc::location!())?; + let reader = if view.hide_attendees { + Some( + self.account_info(access_token.account_id()) + .await + .caused_by(trc::location!())?, + ) + } else { + None + }; + view.apply( + &mut event, + reader.as_ref().map(|r| r.addresses()).unwrap_or_default(), + self.core.groupware.max_ical_instances, + ); + event.data.event.to_string() + } else { + event.data.event.to_string() + }; if !is_head { Ok(response.with_binary_body(ical)) diff --git a/crates/dav/src/calendar/mod.rs b/crates/dav/src/calendar/mod.rs index fdb0178a..08cd9283 100644 --- a/crates/dav/src/calendar/mod.rs +++ b/crates/dav/src/calendar/mod.rs @@ -11,6 +11,7 @@ pub mod delete; pub mod freebusy; pub mod get; pub mod mkcol; +pub mod privacy; // inbuxa: what sharees see of events pub mod proppatch; pub mod query; pub mod scheduling; diff --git a/crates/dav/src/calendar/privacy.rs b/crates/dav/src/calendar/privacy.rs new file mode 100644 index 00000000..db1a3800 --- /dev/null +++ b/crates/dav/src/calendar/privacy.rs @@ -0,0 +1,131 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! What a reader who isn't a calendar's owner gets of its events over CalDAV: +//! what JMAP shows it. The time only of a private or confidential event, and +//! only the owners and the reader among the attendees of an event that hides +//! them, unless the reader may change it. + +use crate::DavError; +use calcard::common::timezone::Tz; +use common::{EVENT_VIEW_HIDE_ATTENDEES, EVENT_VIEW_PRIVATE, Server, auth::AccessToken}; +use groupware::{ + cache::GroupwareCache, + calendar::{ + CalendarEvent, CalendarEventData, + privacy::{event_view, hide_attendees, redact_private_event}, + }, +}; +use hyper::StatusCode; +use store::{ + Deserialize, Serialize, + write::{AlignedBytes, Archive, Archiver}, +}; +use trc::AddContext; +use types::{acl::Acl, collection::SyncCollection}; + +#[derive(Debug, Clone, Copy)] +pub(crate) struct ShareeView { + pub private: bool, + pub hide_attendees: bool, +} + +impl ShareeView { + /// The view of an event with these EVENT_VIEW_* flags, or None when the + /// reader may see all of it. `may_modify` tells whether the reader may + /// change the event. + pub fn new(view: u8, may_modify: impl FnOnce() -> bool) -> Option { + let private = view & EVENT_VIEW_PRIVATE != 0; + let hide_attendees = view & EVENT_VIEW_HIDE_ATTENDEES != 0 && !may_modify(); + (private || hide_attendees).then_some(ShareeView { + private, + hide_attendees, + }) + } + + /// Leaves of `event` what the reader, at `addresses`, may see + pub fn apply(&self, event: &mut CalendarEvent, addresses: &[String], max_expansions: usize) { + if self.private { + redact_private_event(&mut event.data.event); + // Alarms and overrides may be gone, so the dates are worked out + // again for what is left + event.data = CalendarEventData::new( + std::mem::take(&mut event.data.event), + Tz::Floating, + max_expansions, + &mut None, + ); + } + if self.hide_attendees { + hide_attendees(&mut event.data.event, addresses); + } + } + + /// A stored event as the reader may see it, under the stored one's ETag + pub fn apply_archive( + &self, + archive: &Archive, + addresses: &[String], + max_expansions: usize, + ) -> trc::Result> { + let mut event = archive + .deserialize::() + .caused_by(trc::location!())?; + self.apply(&mut event, addresses, max_expansions); + event.size = event.data.event.to_string().len() as u32; + let mut result = Archive::::deserialize_owned( + Archiver::new(event) + .serialize() + .caused_by(trc::location!())?, + ) + .caused_by(trc::location!())?; + result.version = archive.version; + Ok(result) + } +} + +/// An event copied or moved out of its account by a reader who isn't the +/// calendar's owner takes what JMAP's CalendarEvent/copy lets it take: a +/// private or confidential event can't leave, and one that hides its +/// attendees leaves without those the reader may not see. +pub(crate) async fn check_copy_out( + server: &Server, + access_token: &AccessToken, + from_account_id: u32, + from_document_id: u32, + event: &mut CalendarEvent, +) -> crate::Result<()> { + if access_token.reads_as_owner(from_account_id) { + return Ok(()); + } + let resources = server + .fetch_dav_resources( + access_token.account_id(), + from_account_id, + SyncCollection::Calendar, + ) + .await + .caused_by(trc::location!())?; + if let Some(view) = ShareeView::new(event_view(event), || { + resources + .shared_items(access_token, [Acl::ModifyItems], true) + .contains(from_document_id) + }) { + if view.private { + return Err(DavError::Code(StatusCode::FORBIDDEN)); + } + let reader = server + .account_info(access_token.account_id()) + .await + .caused_by(trc::location!())?; + view.apply( + event, + reader.addresses(), + server.core.groupware.max_ical_instances, + ); + } + Ok(()) +} diff --git a/crates/dav/src/calendar/update.rs b/crates/dav/src/calendar/update.rs index fba65473..9dff669d 100644 --- a/crates/dav/src/calendar/update.rs +++ b/crates/dav/src/calendar/update.rs @@ -9,7 +9,7 @@ use super::assert_is_unique_uid; use crate::{ DavError, DavErrorCondition, DavMethod, - calendar::ItipPrecondition, + calendar::{ItipPrecondition, privacy::ShareeView}, common::{ ETag, ExtractETag, lock::{LockRequestHandler, ResourceState}, @@ -31,8 +31,10 @@ use dav_proto::{ use groupware::{ cache::GroupwareCache, calendar::{ - CalendarEvent, CalendarEventData, dates::has_oversized_rrule, itip::ItipSendStatus, - privacy::itip_messages_for, + CalendarEvent, CalendarEventData, + dates::has_oversized_rrule, + itip::ItipSendStatus, + privacy::{archived_event_view, itip_messages_for}, }, scheduling::{ ItipMessages, event_create::itip_create, event_update::itip_update, @@ -154,6 +156,20 @@ impl CalendarUpdateRequestHandler for Server { .to_unarchived::() .caused_by(trc::location!())?; + // inbuxa: a reader who isn't the calendar's owner and doesn't see all + // of the event (see `ShareeView`) can't replace it, as what it + // sends back would wipe the rest + if !access_token.reads_as_owner(account_id) + && ShareeView::new(archived_event_view(event.inner), || { + resources + .shared_items(access_token, [Acl::ModifyItems], true) + .contains(document_id) + }) + .is_some() + { + return Err(DavError::Code(StatusCode::FORBIDDEN)); + } + // Validate headers match self .validate_headers( diff --git a/crates/dav/src/common/propfind.rs b/crates/dav/src/common/propfind.rs index cfd2d912..74d942cc 100644 --- a/crates/dav/src/common/propfind.rs +++ b/crates/dav/src/common/propfind.rs @@ -16,6 +16,7 @@ use crate::{ DavError, DavErrorCondition, calendar::{ CALENDAR_CONTAINER_PROPS, CALENDAR_ITEM_PROPS, + privacy::ShareeView, query::{CalendarQueryHandler, try_parse_tz}, }, card::{ @@ -52,7 +53,9 @@ use dav_proto::{ }, }, }; -use groupware::calendar::{SCHEDULE_INBOX_ID, SupportedComponent}; +use groupware::calendar::{ + CalendarEvent, SCHEDULE_INBOX_ID, SupportedComponent, privacy::archived_event_view, +}; use groupware::{ DavCalendarResource, DavResourceName, cache::GroupwareCache, calendar::ArchivedTimezone, }; @@ -200,9 +203,10 @@ impl PropFindRequestHandler for Server { StatusCode::NOT_FOUND, )); } else if access_token.has_account_access(account_id) - || (self.core.groupware.allow_directory_query + || ((self.core.groupware.allow_directory_query && access_token.has_permission(Permission::DavPrincipalList)) - || access_token.has_permission(Permission::SysAccountQuery) + || access_token.has_permission(Permission::SysAccountQuery)) + && is_in_tenant(self, access_token, account_id).await? { self.prepare_principal_propfind_response( access_token, @@ -427,6 +431,8 @@ impl PropFindRequestHandler for Server { } let is_scheduling = collection_container == Collection::CalendarEventNotification; + let mut writable_ids: AHashMap = AHashMap::new(); + let mut reader_info = None; let account_info = self .account(access_token.account_id()) .await @@ -458,7 +464,53 @@ impl PropFindRequestHandler for Server { .await .caused_by(trc::location!())? { - archive_ = archive; + // inbuxa: a reader who isn't the calendar's owner gets an event + // as JMAP shows it, in its data and in what a query matches + let view = if collection == Collection::CalendarEvent + && !access_token.reads_as_owner(account_id) + { + let resources = data + .resources(self, access_token, account_id, SyncCollection::Calendar) + .await + .caused_by(trc::location!())?; + ShareeView::new( + archived_event_view( + archive + .unarchive::() + .caused_by(trc::location!())?, + ), + || { + writable_ids + .entry(account_id) + .or_insert_with(|| { + resources.shared_items(access_token, [Acl::ModifyItems], true) + }) + .contains(document_id) + }, + ) + } else { + None + }; + archive_ = if let Some(view) = view { + if view.hide_attendees && reader_info.is_none() { + reader_info = Some( + self.account_info(access_token.account_id()) + .await + .caused_by(trc::location!())?, + ); + } + view.apply_archive( + &archive, + reader_info + .as_ref() + .map(|info| info.addresses()) + .unwrap_or_default(), + self.core.groupware.max_ical_instances, + ) + .caused_by(trc::location!())? + } else { + archive + }; ArchivedResource::from_archive(&archive_, collection).caused_by(trc::location!())? } else { response.add_response(Response::new_status([item.name], StatusCode::NOT_FOUND)); @@ -1726,6 +1778,24 @@ impl SyncTokenUrn for DavResources { } } +// inbuxa: reading the directory stays inside the caller's tenant, the same +// rule as the principal listing and JMAP Principal/get; a caller outside +// any tenant isn't limited. +async fn is_in_tenant( + server: &Server, + access_token: &AccessToken, + account_id: u32, +) -> trc::Result { + match access_token.tenant_id() { + Some(tenant_id) => Ok(server + .try_account(account_id) + .await + .caused_by(trc::location!())? + .is_some_and(|account| account.id_tenant == Some(tenant_id))), + None => Ok(true), + } +} + async fn add_base_collection_response( server: &Server, request: &PropFind, diff --git a/crates/email/src/mailbox/manage.rs b/crates/email/src/mailbox/manage.rs index 3bc662a9..c48f58d7 100644 --- a/crates/email/src/mailbox/manage.rs +++ b/crates/email/src/mailbox/manage.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use super::*; @@ -123,10 +125,10 @@ impl MailboxFnc for Server { // Create missing folders if !create_paths.is_empty() { - if create_paths - .iter() - .any(|name| name.len() > self.core.email.mailbox_name_max_len) - { + if create_paths.iter().any(|name| { + name.len() > self.core.email.mailbox_name_max_len + || super::mailbox_name_has_control_chars(name) + }) { return Ok(None); } diff --git a/crates/email/src/mailbox/mod.rs b/crates/email/src/mailbox/mod.rs index 49658c25..7683e8b5 100644 --- a/crates/email/src/mailbox/mod.rs +++ b/crates/email/src/mailbox/mod.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use types::{acl::AclGrant, special_use::SpecialUse}; @@ -17,6 +19,12 @@ pub const DRAFTS_ID: u32 = 3; pub const SENT_ID: u32 = 4; pub const ARCHIVE_ID: u32 = 5; +/// Mailbox names never hold control characters: IMAP sends names as +/// quoted strings, where CR or LF would end the response line. +pub fn mailbox_name_has_control_chars(name: &str) -> bool { + name.chars().any(char::is_control) +} + #[derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize, Debug, Clone, PartialEq, Eq)] #[rkyv(derive(Debug))] pub struct Mailbox { diff --git a/crates/http/src/api/diagnose.rs b/crates/http/src/api/diagnose.rs index d0a1b598..a2a069ec 100644 --- a/crates/http/src/api/diagnose.rs +++ b/crates/http/src/api/diagnose.rs @@ -196,15 +196,42 @@ impl ElapsedMs for Instant { self.elapsed().as_millis() as u64 } } +/// Splits a delivery test target into its domain and, for an address, the +/// address itself. The address is sent in RCPT TO and the domain is looked +/// up and fetched over HTTPS, so anything that is not a plain address or +/// domain (control characters, spaces, angle brackets) is refused. +pub(crate) fn parse_delivery_target(target: &str) -> Option<(String, Option)> { + if target + .chars() + .any(|ch| ch.is_control() || ch.is_whitespace() || matches!(ch, '<' | '>')) + { + return None; + } + + let (domain, email) = if target.contains('@') { + let email = utils::sanitize_email(target)?; + let (_, domain) = email.rsplit_once('@')?; + (domain.to_string(), Some(email)) + } else { + (utils::sanitize_domain(target)?, None) + }; + + domain + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.')) + .then_some((domain, email)) +} + pub(crate) fn spawn_delivery_diagnose( server: Server, - domain_or_email: String, + domain: String, + email: Option, timeout: Duration, ) -> mpsc::Receiver { let (tx, rx) = mpsc::channel(10); tokio::spawn(async move { - let _ = delivery_diagnose(tx, server, domain_or_email, timeout).await; + let _ = delivery_diagnose(tx, server, domain, email, timeout).await; }); rx @@ -213,15 +240,10 @@ pub(crate) fn spawn_delivery_diagnose( async fn delivery_diagnose( tx: mpsc::Sender, server: Server, - domain_or_email: String, + domain: String, + email: Option, timeout: Duration, ) -> Result<(), mpsc::error::SendError> { - let (domain, email) = if let Some((_, domain)) = domain_or_email.rsplit_once('@') { - (domain.to_string(), Some(domain_or_email)) - } else { - (domain_or_email, None) - }; - let local_host = &server.core.network.server_name; let conn_strategy = server.get_connection_or_default("default", 0); @@ -785,3 +807,40 @@ async fn delivery_diagnose( Ok(()) } + +#[cfg(test)] +mod tests { + use super::parse_delivery_target; + + #[test] + fn delivery_target_is_an_address_or_a_domain() { + assert_eq!( + parse_delivery_target("user@example.com"), + Some(("example.com".into(), Some("user@example.com".into()))) + ); + assert_eq!( + parse_delivery_target("example.com"), + Some(("example.com".into(), None)) + ); + + // Anything that could end or extend an SMTP command is refused + for target in [ + "user@example.com>\r\nRSET\r\nMAIL FROM:", + "user@example.com> NOTIFY=NEVER", + "example.com\r\nRSET", + "example.com/.well-known", + "example.com:8443", + "example.com/x", + "", + "@", + "user@", + ] { + assert_eq!(parse_delivery_target(target), None, "accepted {target:?}"); + } + } +} diff --git a/crates/http/src/api/mod.rs b/crates/http/src/api/mod.rs index ccd90de0..76f87f2e 100644 --- a/crates/http/src/api/mod.rs +++ b/crates/http/src/api/mod.rs @@ -9,7 +9,7 @@ pub mod diagnose; use crate::{ - api::diagnose::{DeliveryStage, spawn_delivery_diagnose}, + api::diagnose::{DeliveryStage, parse_delivery_target, spawn_delivery_diagnose}, auth::{ authenticate::Authenticator, oauth::auth::OAuthApiHandler, permissions::AccountApiHandler, }, @@ -271,11 +271,14 @@ impl ManagementApi for Server { .unwrap_or(30), ); - let mut rx = spawn_delivery_diagnose( - self.clone(), - decode_path_element(target).to_lowercase(), - timeout, - ); + let (domain, email) = + parse_delivery_target(&decode_path_element(target).to_lowercase()) + .ok_or_else(|| { + trc::ResourceEvent::BadParameters + .into_err() + .details("Expected an email address or a domain name.") + })?; + let mut rx = spawn_delivery_diagnose(self.clone(), domain, email, timeout); Ok(HttpResponse::new(StatusCode::OK) .with_content_type("text/event-stream") diff --git a/crates/http/src/auth/oauth/token.rs b/crates/http/src/auth/oauth/token.rs index c2c64e3a..66db7bc2 100644 --- a/crates/http/src/auth/oauth/token.rs +++ b/crates/http/src/auth/oauth/token.rs @@ -17,10 +17,7 @@ use base64::{ }; use common::{ KV_OAUTH, KV_OAUTH_DEVICE, Server, - auth::{ - AccessToken, - oauth::{GrantType, oidc::StandardClaims}, - }, + auth::oauth::{GrantType, oidc::StandardClaims}, }; use http_proto::*; use hyper::StatusCode; @@ -42,7 +39,6 @@ pub trait TokenHandler: Sync + Send { fn handle_token_introspect( &self, req: &mut HttpRequest, - access_token: &AccessToken, session_id: u64, ) -> impl Future> + Send; @@ -318,7 +314,6 @@ impl TokenHandler for Server { async fn handle_token_introspect( &self, req: &mut HttpRequest, - access_token: &AccessToken, session_id: u64, ) -> trc::Result { // Parse token @@ -331,7 +326,7 @@ impl TokenHandler for Server { .details("Client ID is missing.") })?; - self.introspect_access_token(&token, access_token) + self.introspect_access_token(&token) .await .map(|response| JsonResponse::new(response).no_cache().into_http_response()) } diff --git a/crates/http/src/request.rs b/crates/http/src/request.rs index e1c9e324..36b98df3 100644 --- a/crates/http/src/request.rs +++ b/crates/http/src/request.rs @@ -440,11 +440,10 @@ impl ParseHttp for Server { } ("introspect", &Method::POST) => { // Authenticate request - let (_in_flight, access_token) = - self.authenticate_headers(&req, &session).await?; + let (_in_flight, _) = self.authenticate_headers(&req, &session).await?; return self - .handle_token_introspect(&mut req, &access_token, session.session_id) + .handle_token_introspect(&mut req, session.session_id) .await; } ("userinfo", &Method::GET) => { diff --git a/crates/imap-proto/src/protocol/list.rs b/crates/imap-proto/src/protocol/list.rs index 1ff338a7..07b2530d 100644 --- a/crates/imap-proto/src/protocol/list.rs +++ b/crates/imap-proto/src/protocol/list.rs @@ -367,6 +367,32 @@ mod tests { } } + #[test] + fn serialize_list_item_with_line_breaks() { + // A stored name with CR/LF is sent as a literal, never as raw lines + let item = ListItem { + mailbox_name: "x\r\n* 1 EXPUNGE".into(), + attributes: vec![], + tags: vec![], + }; + for (is_rev2, is_utf8, expected) in [ + ( + true, + true, + concat!( + "* LIST () \"/\" {14}\r\nx\r\n* 1 EXPUNGE ", + "(\"OLDNAME\" (\"x&AA0ACg-* 1 EXPUNGE\"))\r\n" + ), + ), + (false, true, "* LIST () \"/\" {14}\r\nx\r\n* 1 EXPUNGE\r\n"), + (false, false, "* LIST () \"/\" \"x&AA0ACg-* 1 EXPUNGE\"\r\n"), + ] { + let mut buf = Vec::new(); + item.serialize(&mut buf, is_rev2, is_utf8, false); + assert_eq!(String::from_utf8(buf).unwrap(), expected); + } + } + #[test] fn serialize_list_objectid() { let mut buf = Vec::new(); diff --git a/crates/imap-proto/src/protocol/mod.rs b/crates/imap-proto/src/protocol/mod.rs index 399027f4..7ef86bd2 100644 --- a/crates/imap-proto/src/protocol/mod.rs +++ b/crates/imap-proto/src/protocol/mod.rs @@ -198,6 +198,12 @@ pub trait ImapResponse { } pub fn quoted_string(buf: &mut Vec, text: &str) { + // A quoted string cannot hold CR or LF; send those as a literal so a + // stored value never ends the response line early + if text.as_bytes().iter().any(|ch| matches!(ch, b'\r' | b'\n')) { + literal_string(buf, text.as_bytes()); + return; + } buf.push(b'"'); for &c in text.as_bytes() { if c == b'\\' || c == b'"' { diff --git a/crates/imap/src/op/create.rs b/crates/imap/src/op/create.rs index 8f1d1f14..0f5bfcfb 100644 --- a/crates/imap/src/op/create.rs +++ b/crates/imap/src/op/create.rs @@ -194,6 +194,10 @@ impl SessionData { return Err(trc::ImapEvent::Error .into_err() .details(format!("Invalid folder name '{mailbox_name}'.",))); + } else if email::mailbox::mailbox_name_has_control_chars(name) { + return Err(trc::ImapEvent::Error + .into_err() + .details("Mailbox name cannot contain control characters.")); } // Build path diff --git a/crates/jmap/src/api/query.rs b/crates/jmap/src/api/query.rs index 212e93a5..94f5290a 100644 --- a/crates/jmap/src/api/query.rs +++ b/crates/jmap/src/api/query.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use jmap_proto::{ @@ -20,6 +22,8 @@ pub struct QueryResponseBuilder { pub has_anchor: bool, pub anchor_found: bool, index: i32, + // inbuxa: the request asked for no ids (`limit: 0`) + zero_limit: bool, pub response: QueryResponse, } @@ -51,6 +55,7 @@ impl QueryResponseBuilder { anchor_offset: request.anchor_offset.unwrap_or(0), anchor_found: false, index: 0, + zero_limit: request.limit == Some(0), response: QueryResponse { account_id: request.account_id, query_state, @@ -79,6 +84,19 @@ impl QueryResponseBuilder { pub fn add_id(&mut self, id: Id) -> bool { let id_u64 = id.id(); + // inbuxa: a limit of 0 returns no ids. Internally a limit of 0 means + // "no limit", so it is handled here: only the anchor is still looked + // for, to report its position or that it wasn't found. + if self.zero_limit { + if self.has_anchor && id_u64 == self.anchor { + self.anchor_found = true; + self.position = (self.index + self.anchor_offset).max(0); + return false; + } + self.index += 1; + return self.has_anchor; + } + // Pagination if !self.has_anchor { if self.position >= 0 { @@ -148,6 +166,11 @@ impl QueryResponseBuilder { return Ok(self.response); } + if self.zero_limit { + self.response.position = self.requested_position.max(0); + return Ok(self.response); + } + if self.requested_position >= 0 { self.response.position = if self.position == 0 { self.requested_position @@ -174,3 +197,62 @@ impl QueryResponseBuilder { Ok(self.response) } } + +#[cfg(test)] +mod tests { + use super::*; + use jmap_proto::object::sieve::Sieve; + + fn request( + limit: Option, + position: Option, + anchor: Option, + ) -> QueryRequest { + QueryRequest { + account_id: Id::new(1), + filter: vec![], + sort: None, + position, + anchor: anchor.map(Id::new), + anchor_offset: None, + limit, + calculate_total: Some(true), + arguments: (), + } + } + + fn run(request: &QueryRequest) -> trc::Result { + let mut builder = QueryResponseBuilder::new(10, 100, State::Initial, request); + for id in 0..10 { + if !builder.add_id(Id::new(id)) { + break; + } + } + builder.build() + } + + #[test] + fn limit_zero_returns_no_ids() { + for (position, anchor) in [ + (None, None), + (Some(3), None), + (Some(-3), None), + (None, Some(4)), + ] { + let response = run(&request(Some(0), position, anchor)).unwrap(); + assert_eq!( + response.ids, + Vec::::new(), + "limit 0 with position {position:?}, anchor {anchor:?}" + ); + assert_eq!(response.total, Some(10)); + } + + // An anchor that isn't there is still an error + assert!(run(&request(Some(0), None, Some(42))).is_err()); + + // Without a limit, and with one, ids still come back + assert_eq!(run(&request(None, None, None)).unwrap().ids.len(), 10); + assert_eq!(run(&request(Some(4), None, None)).unwrap().ids.len(), 4); + } +} diff --git a/crates/jmap/src/email/copy.rs b/crates/jmap/src/email/copy.rs index 8971a434..afe292f5 100644 --- a/crates/jmap/src/email/copy.rs +++ b/crates/jmap/src/email/copy.rs @@ -244,6 +244,12 @@ impl JmapEmailCopy for Server { { Ok(email) => { last_change_id = Some(email.change_id); + + // inbuxa: only an original that was copied is destroyed + if on_success_delete { + destroy_ids.push(MaybeInvalid::Value(from_message_id)); + } + if train_spam { self.add_account_spam_sample( &mut train_batch, @@ -275,11 +281,6 @@ impl JmapEmailCopy for Server { ); } } - - // Add to destroy list - if on_success_delete { - destroy_ids.push(MaybeInvalid::Value(from_message_id)); - } } if did_train { diff --git a/crates/jmap/src/email/set.rs b/crates/jmap/src/email/set.rs index bb84aa14..4a9b52aa 100644 --- a/crates/jmap/src/email/set.rs +++ b/crates/jmap/src/email/set.rs @@ -948,12 +948,29 @@ impl EmailSet for Server { let mut train_spam = None; if has_keyword_changes { // Verify permissions on shared accounts - if can_modify_mailbox_ids.as_ref().is_some_and(|ids| { - !new_data - .mailboxes - .iter() - .any(|mb| ids.contains(mb.mailbox_id)) - }) { + // inbuxa: keywords belong to the message, so the right to + // modify them has to hold on every mailbox the message is in + // before and after this update (RFC 8621), not only on one. + // Changing $deleted also needs the right to remove messages. + let mut mailbox_ids = data + .inner + .mailboxes + .iter() + .map(|mb| u32::from(mb.mailbox_id)) + .chain(new_data.mailboxes.iter().map(|mb| mb.mailbox_id)); + let changes_deleted = new_data + .added_keywords(data.inner) + .any(|k| matches!(k, Keyword::Deleted)) + || new_data + .removed_keywords(data.inner) + .any(|k| matches!(k, ArchivedKeyword::Deleted)); + if let (Some(modify_ids), Some(remove_ids)) = + (&can_modify_mailbox_ids, &can_delete_mailbox_ids) + && !mailbox_ids.all(|mailbox_id| { + modify_ids.contains(mailbox_id) + && (!changes_deleted || remove_ids.contains(mailbox_id)) + }) + { response.not_updated.append( id, SetError::forbidden() diff --git a/crates/jmap/src/file/set.rs b/crates/jmap/src/file/set.rs index 9534f0ad..8513f0a3 100644 --- a/crates/jmap/src/file/set.rs +++ b/crates/jmap/src/file/set.rs @@ -197,6 +197,9 @@ impl FileNodeSet for Server { file_node.modified = now() as i64; } + // inbuxa: the node a replace destroys, queued only once the + // create is accepted + let mut replaces = None; let renamed = match find_sibling_collision( None, &file_node, @@ -251,7 +254,7 @@ impl FileNodeSet for Server { continue 'create; } } - implicit_destroys.insert(existing); + replaces = Some(existing); false } OnExists::Newest => unreachable!(), @@ -383,6 +386,9 @@ impl FileNodeSet for Server { &mut batch, ) .caused_by(trc::location!())?; + if let Some(existing) = replaces { + implicit_destroys.insert(existing); + } let create_id = id.clone(); response.created(id, document_id); if renamed && let Some(Value::Object(map)) = response.created.get_mut(&create_id) { @@ -501,6 +507,9 @@ impl FileNodeSet for Server { continue 'update; } + // inbuxa: the node a replace destroys, queued only once the + // update is accepted + let mut replaces = None; let renamed = match find_sibling_collision( Some(document_id), &new_file_node, @@ -555,7 +564,7 @@ impl FileNodeSet for Server { continue 'update; } } - implicit_destroys.insert(existing); + replaces = Some(existing); false } OnExists::Newest => unreachable!(), @@ -689,6 +698,9 @@ impl FileNodeSet for Server { &mut batch, ) .caused_by(trc::location!())?; + if let Some(existing) = replaces { + implicit_destroys.insert(existing); + } let updated_value = if renamed { let mut map = jmap_tools::Map::with_capacity(1); map.insert_unchecked( diff --git a/crates/jmap/src/mailbox/set.rs b/crates/jmap/src/mailbox/set.rs index 3e9c38bc..7d2fa15c 100644 --- a/crates/jmap/src/mailbox/set.rs +++ b/crates/jmap/src/mailbox/set.rs @@ -376,7 +376,15 @@ impl MailboxSet for Server { match (&property, value) { (Key::Property(MailboxProperty::Name), Value::Str(value)) => { let value = value.trim(); - if !value.is_empty() && value.len() < self.core.email.mailbox_name_max_len { + if email::mailbox::mailbox_name_has_control_chars(value) { + return Ok(Err(SetError::invalid_properties() + .with_property(MailboxProperty::Name) + .with_description( + "Mailbox name cannot contain control characters.", + ))); + } else if !value.is_empty() + && value.len() < self.core.email.mailbox_name_max_len + { changes.name = value.into(); } else { return Ok(Err(SetError::invalid_properties() diff --git a/crates/jmap/src/registry/mapping/log.rs b/crates/jmap/src/registry/mapping/log.rs index 299b7554..af1ebd51 100644 --- a/crates/jmap/src/registry/mapping/log.rs +++ b/crates/jmap/src/registry/mapping/log.rs @@ -164,6 +164,11 @@ fn read_log_offsets( anchor: u64, limit: usize, ) -> io::Result> { + // inbuxa: a limit of 0 asks for no entries, not all of them + if limit == 0 { + return Ok(Vec::new()); + } + let mut logs = fs::read_dir(path)?.collect::, _>>()?; logs.sort_by_key(|b| std::cmp::Reverse(b.file_name())); @@ -519,3 +524,26 @@ impl Iterator for RevLines { ) } } + +#[cfg(test)] +mod tests { + use super::read_log_offsets; + + #[test] + fn limit_zero_reads_no_entries() { + let dir = std::env::temp_dir().join(format!("inbuxa-log-limit-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("server.log"), + "2026-11-08T10:00:00Z INFO First (first)\n2026-11-08T10:00:01Z INFO Second (second)\n", + ) + .unwrap(); + + let none = read_log_offsets(&dir, None, 0, 0).unwrap(); + let all = read_log_offsets(&dir, None, 0, 10).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + + assert!(none.is_empty(), "limit 0 returned {none:?}"); + assert_eq!(all.len(), 2); + } +} diff --git a/crates/services/src/task_manager/dns.rs b/crates/services/src/task_manager/dns.rs index 8d61dd33..5f946c60 100644 --- a/crates/services/src/task_manager/dns.rs +++ b/crates/services/src/task_manager/dns.rs @@ -7,7 +7,7 @@ */ use crate::task_manager::TaskResult; -use common::Server; +use common::{Server, network::dns::update::DnsUpdater}; use dns_update::{CAARecord, DnsRecord, DnsRecordType, Error as DnsUpdateError, KeyValue}; use registry::{ schema::{ @@ -141,7 +141,74 @@ async fn dns_management(server: &Server, task: &TaskDnsManagement) -> trc::Resul .push(record.record); } + let (errors, transient) = publish_rrsets(&dns_updater, origin, by_owner).await; + + if errors.is_empty() { + if task.on_success_renew_certificate { + Ok(TaskResult::Success(vec![Task::AcmeRenewal( + TaskDomainManagement { + domain_id: task.domain_id, + status: TaskStatus::now(), + }, + )])) + } else { + Ok(TaskResult::Success(vec![])) + } + } else if transient { + Ok(TaskResult::temporary(errors)) + } else { + Ok(TaskResult::permanent(errors)) + } +} + +/// What the task asks of a DNS provider, a trait so the tests can stand in +/// a provider that fails. +trait RrsetUpdater: Sync { + fn list( + &self, + origin: &str, + name: &str, + record_type: DnsRecordType, + ) -> impl Future>> + Send; + fn replace( + &self, + origin: &str, + name: &str, + record_type: DnsRecordType, + records: Vec, + ) -> impl Future> + Send; +} + +impl RrsetUpdater for DnsUpdater { + fn list( + &self, + origin: &str, + name: &str, + record_type: DnsRecordType, + ) -> impl Future>> + Send { + self.list_rrset(origin, name, record_type) + } + + fn replace( + &self, + origin: &str, + name: &str, + record_type: DnsRecordType, + records: Vec, + ) -> impl Future> + Send { + self.replace_rrset(origin, name, record_type, records) + } +} + +/// Publishes each RRSet. Returns what failed, and whether any of it may pass +/// on its own so the task is worth trying again. +async fn publish_rrsets( + dns_updater: &impl RrsetUpdater, + origin: &str, + by_owner: AHashMap<(String, DnsRecordType), Vec>, +) -> (String, bool) { let mut errors = String::new(); + let mut transient = false; for ((name, record_type), mut recs) in by_owner { let preserve_unrelated = match record_type { DnsRecordType::TXT => !is_owned_txt_name(&name), @@ -149,7 +216,7 @@ async fn dns_management(server: &Server, task: &TaskDnsManagement) -> trc::Resul _ => false, }; if preserve_unrelated { - match dns_updater.list_rrset(origin, &name, record_type).await { + match dns_updater.list(origin, &name, record_type).await { Ok(existing) => { for existing_rec in existing { if !recs.iter().any(|new| same_rrset_family(new, &existing_rec)) { @@ -176,56 +243,98 @@ async fn dns_management(server: &Server, task: &TaskDnsManagement) -> trc::Resul Type = record_type.as_str(), Reason = format!("DNS provider failed to list RRSet: {err}"), ); + // inbuxa: without the list, writing ours would replace + // the other records at this name, so it waits + push_error( + &mut errors, + format_args!( + "Left the DNS RRSet for {name}/{} as it is: listing it failed: {err}", + record_type.as_str() + ), + ); + transient |= is_transient(&err); + continue; } } } // inbuxa: a publish never cuts a domain's MX set down to one host - // (relay spec, RL-25) - if record_type == DnsRecordType::MX - && let Ok(existing) = dns_updater.list_rrset(origin, &name, record_type).await - && let Some(hosts) = shrinks_mx_set(&existing, &recs) - { - if !errors.is_empty() { - errors.push_str("; "); + // (relay spec, RL-25), and doesn't guess when the set can't be read + if record_type == DnsRecordType::MX { + match dns_updater.list(origin, &name, record_type).await { + Ok(existing) => { + if let Some(hosts) = shrinks_mx_set(&existing, &recs) { + push_error( + &mut errors, + format_args!( + "Left the MX records for {name} as they are: publishing would replace their {hosts} hosts with one" + ), + ); + continue; + } + } + Err(DnsUpdateError::Unsupported(_)) => {} + Err(err) => { + push_error( + &mut errors, + format_args!( + "Left the MX records for {name} as they are: listing them failed: {err}" + ), + ); + transient |= is_transient(&err); + continue; + } } - let _ = write!( - &mut errors, - "Left the MX records for {name} as they are: publishing would replace their {hosts} hosts with one" - ); - continue; } - if let Err(err) = dns_updater - .set_rrset(origin, &name, record_type, recs) - .await - { - if !errors.is_empty() { - errors.push_str("; "); - } - let _ = write!( + if let Err(err) = dns_updater.replace(origin, &name, record_type, recs).await { + push_error( &mut errors, - "Failed to set DNS RRSet for {}/{}: {}", - name, - record_type.as_str(), - err + format_args!( + "Failed to set DNS RRSet for {}/{}: {}", + name, + record_type.as_str(), + err + ), ); + transient |= is_transient(&err); } } - if errors.is_empty() { - if task.on_success_renew_certificate { - Ok(TaskResult::Success(vec![Task::AcmeRenewal( - TaskDomainManagement { - domain_id: task.domain_id, - status: TaskStatus::now(), - }, - )])) - } else { - Ok(TaskResult::Success(vec![])) + (errors, transient) +} + +fn push_error(errors: &mut String, error: std::fmt::Arguments<'_>) { + if !errors.is_empty() { + errors.push_str("; "); + } + let _ = errors.write_fmt(error); +} + +/// inbuxa: whether a DNS provider's error may pass on its own, so the task +/// is tried again: the network, a timeout, the provider's server failing or +/// limiting the rate. Refused credentials, a zone the provider doesn't have +/// and a refused request stay failed. +fn is_transient(err: &DnsUpdateError) -> bool { + match err { + // HTTP providers: the request couldn't be sent or read, or the + // status wasn't 401 or 404 + DnsUpdateError::Api(reason) => { + reason.starts_with("Failed to send request") + || reason.starts_with("Failed to read response") + || reason + .strip_prefix("HTTP ") + .is_some_and(|status| status.starts_with('5') || status.starts_with("429")) } - } else { - Ok(TaskResult::permanent(errors)) + // RFC 2136: the connection or a timeout, or SERVFAIL + DnsUpdateError::Client(reason) => { + reason.starts_with("io error") + || reason.contains("timed out") + || reason.starts_with("no connections available") + || reason.starts_with("resource too busy") + } + DnsUpdateError::Response(rcode) => rcode == "Server Failure", + _ => false, } } @@ -348,4 +457,195 @@ mod tests { assert_eq!(shrinks_mx_set(&mx(&["a.test."]), &mx(&["b.test."])), None); assert_eq!(shrinks_mx_set(&[], &mx(&["a.test."])), None); } + + /// A DNS provider holding one zone, whose lookups or writes can be made + /// to fail. + #[derive(Default)] + struct FailingUpdater { + records: std::sync::Mutex>, + list_error: Option DnsUpdateError>, + replace_error: Option DnsUpdateError>, + } + + impl RrsetUpdater for FailingUpdater { + fn list( + &self, + _origin: &str, + name: &str, + record_type: DnsRecordType, + ) -> impl Future>> + Send { + let result = match self.list_error { + Some(error) => Err(error()), + None => Ok(self + .records + .lock() + .unwrap() + .iter() + .filter(|(at, record)| at == name && record.as_type() == record_type) + .map(|(_, record)| record.clone()) + .collect()), + }; + async move { result } + } + + fn replace( + &self, + _origin: &str, + name: &str, + record_type: DnsRecordType, + records: Vec, + ) -> impl Future> + Send { + let result = match self.replace_error { + Some(error) => Err(error()), + None => { + let mut zone = self.records.lock().unwrap(); + zone.retain(|(at, record)| !(at == name && record.as_type() == record_type)); + zone.extend(records.into_iter().map(|record| (name.to_string(), record))); + Ok(()) + } + }; + async move { result } + } + } + + fn txt(value: &str) -> DnsRecord { + DnsRecord::TXT(value.to_string()) + } + + /// Publishes a new SPF record at the apex of a zone that also holds a + /// site verification record. Returns the zone afterwards, the errors and + /// whether the task would be tried again. + async fn publish_spf( + list_error: Option DnsUpdateError>, + replace_error: Option DnsUpdateError>, + ) -> (Vec, String, bool) { + let updater = FailingUpdater { + records: std::sync::Mutex::new(vec![ + ("example.org".to_string(), txt("site-verification=abc")), + ("example.org".to_string(), txt("v=spf1 a -all")), + ]), + list_error, + replace_error, + }; + let by_owner = AHashMap::from_iter([( + ("example.org".to_string(), DnsRecordType::TXT), + vec![txt("v=spf1 mx -all")], + )]); + let (errors, transient) = publish_rrsets(&updater, "example.org", by_owner).await; + let zone = updater + .records + .into_inner() + .unwrap() + .into_iter() + .map(|(_, record)| record) + .collect(); + (zone, errors, transient) + } + + #[tokio::test] + async fn other_records_at_the_name_are_kept() { + let (zone, errors, _) = publish_spf(None, None).await; + assert_eq!(errors, ""); + assert_eq!( + zone, + vec![txt("v=spf1 mx -all"), txt("site-verification=abc")] + ); + } + + #[tokio::test] + async fn a_failed_lookup_leaves_the_name_alone() { + let before = vec![txt("site-verification=abc"), txt("v=spf1 a -all")]; + + // A timeout is tried again + let (zone, errors, transient) = publish_spf( + Some(|| { + DnsUpdateError::Api("Failed to send request to https://dns.test: timed out".into()) + }), + None, + ) + .await; + assert_eq!(zone, before, "a failed lookup replaced the RRSet"); + assert!(errors.contains("timed out"), "{errors}"); + assert!(transient, "a timeout is not tried again: {errors}"); + + // Refused credentials are not + let (zone, errors, transient) = + publish_spf(Some(|| DnsUpdateError::Unauthorized), None).await; + assert_eq!(zone, before, "a failed lookup replaced the RRSet"); + assert!(!transient, "refused credentials are tried again: {errors}"); + + // A provider that can't list at all still gets the record + let (zone, errors, _) = publish_spf( + Some(|| DnsUpdateError::Unsupported("no listing".into())), + None, + ) + .await; + assert_eq!(errors, ""); + assert_eq!(zone, vec![txt("v=spf1 mx -all")]); + } + + #[tokio::test] + async fn a_failed_mx_lookup_leaves_the_mx_set_alone() { + let three = mx(&["mail.example.org.", "mx2.example.org.", "mx3.example.org."]); + let updater = FailingUpdater { + records: std::sync::Mutex::new( + three + .iter() + .map(|record| ("example.org".to_string(), record.clone())) + .collect(), + ), + list_error: Some(|| DnsUpdateError::Client("request timed out".into())), + replace_error: None, + }; + let by_owner = AHashMap::from_iter([( + ("example.org".to_string(), DnsRecordType::MX), + mx(&["mail.example.org."]), + )]); + let (errors, transient) = publish_rrsets(&updater, "example.org", by_owner).await; + let zone: Vec = updater + .records + .into_inner() + .unwrap() + .into_iter() + .map(|(_, record)| record) + .collect(); + assert_eq!(zone, three, "{errors}"); + assert!(transient, "{errors}"); + } + + #[tokio::test] + async fn only_errors_that_may_pass_are_tried_again() { + for (error, expected) in [ + ( + (|| DnsUpdateError::Api("Failed to send request to https://dns.test: reset".into())) + as fn() -> DnsUpdateError, + true, + ), + (|| DnsUpdateError::Api("HTTP 503: unavailable".into()), true), + (|| DnsUpdateError::Api("HTTP 429".into()), true), + (|| DnsUpdateError::Client("request timed out".into()), true), + ( + || DnsUpdateError::Client("io error: connection refused".into()), + true, + ), + (|| DnsUpdateError::Response("Server Failure".into()), true), + (|| DnsUpdateError::Unauthorized, false), + (|| DnsUpdateError::NotFound, false), + (|| DnsUpdateError::BadRequest, false), + (|| DnsUpdateError::Api("HTTP 403: forbidden".into()), false), + ( + || DnsUpdateError::Api("BadRequest invalid content".into()), + false, + ), + (|| DnsUpdateError::Response("Refused".into()), false), + ( + || DnsUpdateError::Client("a.test is not in the DNS zone example.org".into()), + false, + ), + ] { + let (_, errors, transient) = publish_spf(None, Some(error)).await; + assert!(!errors.is_empty()); + assert_eq!(transient, expected, "{errors}"); + } + } } diff --git a/crates/smtp/src/inbound/session.rs b/crates/smtp/src/inbound/session.rs index d8ad4f11..7a982eef 100644 --- a/crates/smtp/src/inbound/session.rs +++ b/crates/smtp/src/inbound/session.rs @@ -97,6 +97,10 @@ impl Session { Limit = self.params.max_message_size, ); + // inbuxa: a refused chunk ends the transaction, so + // chunks pipelined after it can't queue the message + // with this part missing + self.reset(); State::SkipData( DummyDataReceiver::new_bdat(chunk_size), b"552 5.3.4 Message too big for system.\r\n", diff --git a/crates/smtp/src/queue/quota.rs b/crates/smtp/src/queue/quota.rs index 699f1033..63964f23 100644 --- a/crates/smtp/src/queue/quota.rs +++ b/crates/smtp/src/queue/quota.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use super::{Metadata, QueueEnvelope, Status}; @@ -62,8 +64,10 @@ impl HasQueueQuota for Server { } if !self.core.smtp.queue.quota.rcpt_domain.is_empty() { - let mut seen_domains = AHashSet::new(); for quota in &self.core.smtp.queue.quota.rcpt_domain { + // inbuxa: each quota counts every domain once; a set shared + // by all of them left every quota after the first unchecked + let mut seen_domains = AHashSet::new(); for (rcpt_idx, rcpt) in message.message.recipients.iter().enumerate() { if seen_domains.insert(rcpt.address.domain_part()) && !self diff --git a/tests/src/imap/mailbox.rs b/tests/src/imap/mailbox.rs index 18ee995a..58903996 100644 --- a/tests/src/imap/mailbox.rs +++ b/tests/src/imap/mailbox.rs @@ -2,10 +2,13 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use imap::op::list::matches_pattern; use imap_proto::ResponseType; +use serde_json::json; use crate::utils::server::TestServer; @@ -90,6 +93,38 @@ pub async fn test( imap.send("ENABLE IMAP4rev2").await; imap.assert_read(Type::Tagged, ResponseType::Ok).await; + // A mailbox name with CR/LF never ends a LIST line early + let injected_name = "x\r\n* 1 EXPUNGE"; + let response = test + .account("jdoe@example.com") + .jmap_create( + "Mailbox", + [json!({ "name": injected_name })], + Vec::<(&str, &str)>::new(), + ) + .await; + imap.send("LIST \"\" \"*\"").await; + let lines = imap.assert_read(Type::Tagged, ResponseType::Ok).await; + assert!( + !lines.iter().any(|line| line.starts_with("* 1 EXPUNGE")), + "A mailbox name injected an IMAP response: {lines:?}" + ); + response.not_created(0); + + // Control characters are refused by CREATE and RENAME too + imap.send(&format!( + "CREATE {{{}+}}\r\n{injected_name}", + injected_name.len() + )) + .await; + imap.assert_read(Type::Tagged, ResponseType::No).await; + imap.send(&format!( + "RENAME \"Tofu\" {{{}+}}\r\n{injected_name}", + injected_name.len() + )) + .await; + imap.assert_read(Type::Tagged, ResponseType::No).await; + // Create and delete using IMAP4rev2 imap.send("CREATE \"L&APg-bende opgaver\"").await; imap.assert_read(Type::Tagged, ResponseType::Ok).await; diff --git a/tests/src/jmap/files/node.rs b/tests/src/jmap/files/node.rs index e2accdfa..f8a8a4cd 100644 --- a/tests/src/jmap/files/node.rs +++ b/tests/src/jmap/files/node.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use crate::utils::{ @@ -447,6 +449,75 @@ pub async fn test(test: &TestServer) { .destroyed() .for_each(drop); + // inbuxa: onExists=replace leaves the existing node alone when the create + // or update is refused by a later check (here, sharing with an account + // that doesn't exist) + let response = account + .jmap_create( + MethodObject::FileNode, + [ + json!({"name": "keep-a.txt"}), + json!({"name": "keep-b.txt"}), + json!({"name": "move-me.txt"}), + ], + Vec::<(&str, &str)>::new(), + ) + .await; + let keep_a = response.created(0).id().to_string(); + let keep_b = response.created(1).id().to_string(); + let move_me = response.created(2).id().to_string(); + let nobody = types::id::Id::new(999_999).to_string(); + account + .jmap_create( + MethodObject::FileNode, + [json!({ + "name": "keep-a.txt", + "shareWith": { &nobody: { "mayRead": true } } + })], + [("onExists", "replace")], + ) + .await + .not_created(0); + account + .jmap_update( + MethodObject::FileNode, + [( + &move_me, + json!({ + "name": "keep-b.txt", + "shareWith": { &nobody: { "mayRead": true } } + }), + )], + [("onExists", "replace")], + ) + .await + .not_updated(&move_me); + let response = account + .jmap_get( + MethodObject::FileNode, + [FileNodeProperty::Id], + [&keep_a, &keep_b], + ) + .await; + let found = response + .list() + .iter() + .map(|node| node.id().to_string()) + .collect::>(); + assert!( + found.contains(&keep_a) && found.contains(&keep_b), + "a refused replace destroyed the existing node: found {found:?} of {keep_a} (create), {keep_b} (update)" + ); + account + .jmap_destroy( + MethodObject::FileNode, + [&keep_a, &keep_b, &move_me], + [("onDestroyRemoveChildren", true)], + ) + .await + .destroyed() + .for_each(drop); + // compareCaseInsensitively should treat sibling names as case-insensitive let response = account .jmap_create( diff --git a/tests/src/jmap/mail/acl.rs b/tests/src/jmap/mail/acl.rs index c4c09e7a..6614744c 100644 --- a/tests/src/jmap/mail/acl.rs +++ b/tests/src/jmap/mail/acl.rs @@ -403,6 +403,44 @@ pub async fn test(test: &TestServer) { .await .unwrap(); + // inbuxa: keywords belong to the message, so changing them needs the + // right on every mailbox the message is in, not only one of them + jane_client + .email_set_mailbox(&email_id_2, &trash_id, true) + .await + .unwrap(); + assert_forbidden( + john_client + .set_default_account_id(jane.id_string()) + .email_set_keyword(&email_id_2, "$flagged", true) + .await, + ); + jane_client + .email_set_mailbox(&email_id_2, &trash_id, false) + .await + .unwrap(); + + // inbuxa: $deleted also needs the right to remove messages + jane_client + .mailbox_update_acl( + &inbox_id, + john.id_string(), + [ACL::ReadItems, ACL::AddItems, ACL::SetKeywords], + ) + .await + .unwrap(); + assert_forbidden( + john_client + .set_default_account_id(jane.id_string()) + .email_set_keyword(&email_id_2, "$deleted", true) + .await, + ); + john_client + .set_default_account_id(jane.id_string()) + .email_set_keyword(&email_id_2, "$flagged", true) + .await + .unwrap(); + // Try to create a child assert_forbidden( john_client diff --git a/tests/src/jmap/mail/copy.rs b/tests/src/jmap/mail/copy.rs index 93799906..d5946395 100644 --- a/tests/src/jmap/mail/copy.rs +++ b/tests/src/jmap/mail/copy.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use crate::utils::server::TestServer; @@ -95,6 +97,60 @@ pub async fn test(test: &TestServer) { .is_none() ); + // inbuxa: a copy that fails leaves its original in place, even with + // onSuccessDestroyOriginal + let duplicate = concat!( + "From: bill@example.com\r\n", + "To: jdoe@example.com\r\n", + "Message-ID: \r\n", + "Subject: Already there\r\n", + "\r\n", + "This one is in both accounts." + ) + .as_bytes() + .to_vec(); + client + .set_default_account_id(Id::new(2).to_string()) + .email_import( + duplicate.clone(), + [&ac2_mailbox_id], + None::>, + None, + ) + .await + .unwrap(); + let ac1_dupe_id = client + .set_default_account_id(Id::new(1).to_string()) + .email_import(duplicate, [&ac1_mailbox_id], None::>, None) + .await + .unwrap() + .take_id(); + let mut request = client.build(); + request + .copy_email(Id::new(1).to_string()) + .account_id(Id::new(2).to_string()) + .on_success_destroy_original(true) + .create(&ac1_dupe_id) + .mailbox_id(&ac2_mailbox_id, true); + let mut response = request.send().await.unwrap(); + let mut copy = response + .method_response_by_pos(0) + .unwrap_copy_email() + .unwrap(); + assert!( + copy.created(&ac1_dupe_id).is_err(), + "the duplicate should not have been copied" + ); + assert!( + client + .set_default_account_id(Id::new(1).to_string()) + .email_get(&ac1_dupe_id, None::>) + .await + .unwrap() + .is_some(), + "a failed copy destroyed its original" + ); + // Empty store account.destroy_all_mailboxes_for_account(1).await; account.destroy_all_mailboxes_for_account(2).await; diff --git a/tests/src/smtp/inbound/data.rs b/tests/src/smtp/inbound/data.rs index 350359a7..cda24990 100644 --- a/tests/src/smtp/inbound/data.rs +++ b/tests/src/smtp/inbound/data.rs @@ -52,6 +52,7 @@ async fn data() { "Mike Foobar", &[], ), + ("sam@quota.net", "p4ssw0rd + extra safety", "Sam Quota", &[]), ] { admin .create_user_account(name, secret, description, aliases, vec![]) @@ -184,6 +185,19 @@ async fn data() { size: Some(450), }) .await; + admin + .registry_create_object(MtaQueueQuota { + description: None, + enable: true, + key: Map::new(vec![MtaQueueQuotaKey::RcptDomain]), + match_: Expression { + else_: "rcpt_domain = 'quota.net'".into(), + ..Default::default() + }, + messages: Some(1), + size: None, + }) + .await; admin .registry_create_object(MtaQueueQuota { description: None, @@ -243,6 +257,24 @@ async fn data() { size_session.response().assert_code("552 5.3.4"); size_session.rset().await; + // A chunk refused as too big ends the transaction: a pipelined last + // chunk after it is refused too, and nothing is queued + size_session.mail_from("bill@doe.org", "250").await; + size_session.rcpt_to("mike@test.com", "250").await; + let mut chunk = b"BDAT 10\r\n0123456789BDAT 200\r\n".to_vec(); + chunk.extend_from_slice(&[b'A'; 200]); + let last = b"Subject: rest\r\n\r\nrest\r\n"; + chunk.extend_from_slice(format!("BDAT {} LAST\r\n", last.len()).as_bytes()); + chunk.extend_from_slice(last); + size_session.ingest(&chunk).await.unwrap(); + size_session + .response() + .assert_count("250 2.6.0", 1) + .assert_count("552 5.3.4", 1) + .assert_code("503 5.5.1"); + test.assert_no_events(); + size_session.rset().await; + // A maximum message size of zero disables the limit size_session.data.remote_ip_str = "10.0.0.5".into(); size_session.eval_session_params().await; @@ -397,6 +429,20 @@ async fn data() { ) .await; + // Every recipient domain quota applies, not only the first one: + // one message is allowed in the queue to domain quota.net + session + .send_message("jane@foobar.org", &["sam@quota.net"], "test:no_dkim", "250") + .await; + session + .send_message( + "jane@foobar.org", + &["sam@quota.net"], + "test:no_dkim", + "452 4.3.1", + ) + .await; + // Make sure store is empty test.clear_queue().await; let admin = test.account("admin"); diff --git a/tests/src/system/oidc.rs b/tests/src/system/oidc.rs index 38f3f0f8..1dfd011d 100644 --- a/tests/src/system/oidc.rs +++ b/tests/src/system/oidc.rs @@ -543,18 +543,73 @@ pub async fn test(test: &mut TestServer) { assert_eq!(access_introspect.token_type.unwrap(), "bearer"); assert!(access_introspect.client_id.is_none()); assert!(access_introspect.active); + // inbuxa: only an access token is active (RFC 7662); a refresh token + // can't be presented as a bearer token let refresh_introspect = post_with_auth::( &metadata.introspection_endpoint, token.as_str().into(), &AHashMap::from_iter([("token".to_string(), refresh_token.unwrap())]), ) .await; - assert_eq!(refresh_introspect.username.unwrap(), "user@example.org"); - assert!(refresh_introspect.client_id.is_none()); - assert!(refresh_introspect.active); + assert_eq!(refresh_introspect, OAuthIntrospect::default()); + + // inbuxa: introspection names the token's owner, not whoever asks + let other = test + .create_user_account( + "admin@example.org", + "other@example.org", + "another very strong password", + &[], + "other@example.org", + ) + .await; + let other_code = http + .post::( + "/api/auth", + &LoginRequest::AuthCode { + account_name: "other@example.org".to_string(), + account_secret: "another very strong password".to_string(), + mfa_token: None, + client_id: client_id.to_string(), + redirect_uri: "com.example.app:/cb".to_string().into(), + nonce: None, + scope: Some(PROFILE_SCOPE.to_string()), + code_challenge: Some(PKCE_CHALLENGE.to_string()), + code_challenge_method: Some("S256".to_string()), + state: None, + resource: vec![], + }, + ) + .await + .unwrap() + .unwrap_code(); + let (other_token, _, _) = unwrap_token_response( + post( + &metadata.token_endpoint, + &AHashMap::from_iter([ + ("client_id".to_string(), client_id.to_string()), + ( + "redirect_uri".to_string(), + "com.example.app:/cb".to_string(), + ), + ("grant_type".to_string(), "authorization_code".to_string()), + ("code".to_string(), other_code), + ("code_verifier".to_string(), PKCE_VERIFIER.to_string()), + ]), + ) + .await, + ); + let owner_introspect = post_with_auth::( + &metadata.introspection_endpoint, + other_token.as_str().into(), + &AHashMap::from_iter([("token".to_string(), token.to_string())]), + ) + .await; + assert!(owner_introspect.active); assert_eq!( - refresh_introspect.iat.unwrap(), - access_introspect.iat.unwrap() + owner_introspect.username.as_deref(), + Some("user@example.org"), + "introspection named the caller instead of the token's owner" ); // Try SMTP OAUTHBEARER auth @@ -1006,6 +1061,7 @@ pub async fn test(test: &mut TestServer) { // Clean up admin.registry_destroy_all(ObjectType::OAuthClient).await; admin.destroy_account(user).await; + admin.destroy_account(other).await; test.cleanup().await; } diff --git a/tests/src/webdav/cal_privacy.rs b/tests/src/webdav/cal_privacy.rs new file mode 100644 index 00000000..a4645f3e --- /dev/null +++ b/tests/src/webdav/cal_privacy.rs @@ -0,0 +1,437 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! A sharee of a calendar reads over CalDAV what JMAP shows it: the time only +//! of a private or confidential event, and only the owners and itself among +//! the attendees of an event that hides them. + +use crate::utils::{account::Account, jmap::JmapUtils, server::TestServer}; +use groupware::DavResourceName; +use hyper::StatusCode; +use jmap_proto::{object::calendar::CalendarProperty, request::method::MethodObject}; +use serde_json::json; + +pub async fn test(test: &TestServer) { + println!("Running CalDAV sharee privacy tests..."); + let bill = test.account("bill@example.com"); + let owner_client = bill.webdav_client(); + let sharee_client = test.account("john@example.com").webdav_client(); + let cal_base = DavResourceName::Cal.base_path(); + let sharee_principal = format!( + "{}/john%40example.com/", + DavResourceName::Principal.base_path() + ); + let owner_calendar = format!("{cal_base}/bill%40example.com/privacy-shared/"); + let sharee_calendar = format!("{cal_base}/john%40example.com/default/"); + let private_href = format!("{owner_calendar}private.ics"); + let confidential_href = format!("{owner_calendar}confidential.ics"); + let hidden_href = format!("{owner_calendar}hidden.ics"); + + owner_client + .mkcol( + "MKCALENDAR", + &owner_calendar, + [], + [("D:displayname", "Privacy shared")], + ) + .await + .with_status(StatusCode::CREATED); + for (href, ics) in [ + (&private_href, PRIVATE_ICS), + (&confidential_href, CONFIDENTIAL_ICS), + (&hidden_href, HIDDEN_ICS), + ] { + owner_client + .request("PUT", href, ics.replace('\n', "\r\n")) + .await + .with_status(StatusCode::CREATED); + } + + // The attendees of the third event are hidden (a JMAP-only setting) + let response = bill + .jmap_get( + MethodObject::CalendarEvent, + ["id", "uid"], + Vec::<&str>::new(), + ) + .await; + let hidden_id = response + .list() + .iter() + .find(|event| event.text_field("uid") == "privacy-hidden@example.com") + .expect("hidden attendees event") + .id() + .to_string(); + bill.jmap_update( + MethodObject::CalendarEvent, + [(&hidden_id, json!({"hideAttendees": true}))], + Vec::<(&str, &str)>::new(), + ) + .await + .updated(&hidden_id); + + // The owner sees everything + for (href, expect) in [ + (&private_href, "Dentist appointment"), + (&confidential_href, "Performance review"), + (&hidden_href, "guest@remote.org"), + ] { + let body = owner_client + .request("GET", href, "") + .await + .with_status(StatusCode::OK) + .expect_body() + .to_string(); + assert!(body.contains(expect), "owner lost {expect}: {body}"); + } + + // Share the calendar for reading + owner_client + .acl(&owner_calendar, sharee_principal.as_str(), ["read"]) + .await + .with_status(StatusCode::OK); + + // Every way calendar data reaches the sharee: GET, multiget, a + // calendar-query, a PROPFIND and a sync-collection + let mut bodies = Vec::new(); + for href in [&private_href, &confidential_href, &hidden_href] { + bodies.push(( + format!("GET {href}"), + sharee_client + .request("GET", href, "") + .await + .with_status(StatusCode::OK) + .expect_body() + .to_string(), + )); + } + bodies.push(( + "calendar-multiget".to_string(), + sharee_client + .request( + "REPORT", + &owner_calendar, + MULTIGET.replace( + "$HREFS", + &[&private_href, &confidential_href, &hidden_href] + .iter() + .map(|href| format!("{href}")) + .collect::(), + ), + ) + .await + .with_status(StatusCode::MULTI_STATUS) + .expect_body() + .to_string(), + )); + bodies.push(( + "calendar-query".to_string(), + sharee_client + .request("REPORT", &owner_calendar, QUERY_ANY_VEVENT) + .await + .with_status(StatusCode::MULTI_STATUS) + .with_href_count(3) + .expect_body() + .to_string(), + )); + bodies.push(( + "PROPFIND".to_string(), + sharee_client + .request_with_headers( + "PROPFIND", + &owner_calendar, + [("depth", "1")], + PROPFIND_CALENDAR_DATA, + ) + .await + .with_status(StatusCode::MULTI_STATUS) + .expect_body() + .to_string(), + )); + bodies.push(( + "sync-collection".to_string(), + sharee_client + .request("REPORT", &owner_calendar, SYNC_CALENDAR_DATA) + .await + .with_status(StatusCode::MULTI_STATUS) + .expect_body() + .to_string(), + )); + for (source, body) in &bodies { + for hidden in [ + "Dentist appointment", + "Room 4", + "Main street clinic", + "Reminder text", + "VALARM", + "Performance review", + "guest@remote.org", + ] { + assert!( + !body.contains(hidden), + "{source} showed the sharee {hidden:?}: {body}" + ); + } + } + for (source, body) in &bodies[..3] { + assert!( + body.contains("DTSTART:20200203T100000Z"), + "{source} lost the event's time: {body}" + ); + } + let body = &bodies[2].1; + assert!( + body.contains("Board meeting") && body.contains("jdoe@example.com"), + "the sharee lost the visible parts of the hidden attendees event: {body}" + ); + + // Matching on what the sharee can't see finds nothing + let body = sharee_client + .request("REPORT", &owner_calendar, QUERY_SUMMARY_DENTIST) + .await + .with_status(StatusCode::MULTI_STATUS) + .expect_body() + .to_string(); + assert!( + !body.contains("private.ics"), + "a sharee matched a private event's title: {body}" + ); + + // A private event can't be copied out; a copy of the hidden attendees + // event keeps them hidden, and so does a copy of the whole calendar + sharee_client + .request_with_headers( + "COPY", + &private_href, + [( + "destination", + format!("{sharee_calendar}private-copy.ics").as_str(), + )], + "", + ) + .await + .with_status(StatusCode::FORBIDDEN); + let hidden_copy = format!("{sharee_calendar}hidden-copy.ics"); + sharee_client + .request_with_headers( + "COPY", + &hidden_href, + [("destination", hidden_copy.as_str())], + "", + ) + .await + .with_status(StatusCode::CREATED); + let body = sharee_client + .request("GET", &hidden_copy, "") + .await + .with_status(StatusCode::OK) + .expect_body() + .to_string(); + assert!( + !body.contains("guest@remote.org") && body.contains("Board meeting"), + "a copy showed the sharee a hidden attendee: {body}" + ); + sharee_client + .request("DELETE", &hidden_copy, "") + .await + .with_status(StatusCode::NO_CONTENT); + // A copy of a calendar skips events whose calendar's id is the new + // calendar's (a separate bug), so it is copied over one of the sharee's + // with another id + let shared_calendar_id = calendar_id(bill, "Privacy shared").await; + let john = test.account("john@example.com"); + let mut sharee_copies = Vec::new(); + let copy_target = loop { + let name = format!("privacy-copy-{}", sharee_copies.len()); + let href = format!("{cal_base}/john%40example.com/{name}/"); + sharee_client + .mkcol("MKCALENDAR", &href, [], [("D:displayname", name.as_str())]) + .await + .with_status(StatusCode::CREATED); + sharee_copies.push(href.clone()); + if calendar_id(john, &name).await != shared_calendar_id { + break href; + } + }; + sharee_client + .request_with_headers( + "COPY", + &owner_calendar, + [("destination", copy_target.as_str()), ("overwrite", "T")], + "", + ) + .await + .with_status(StatusCode::FORBIDDEN); + for href in &sharee_copies { + sharee_client + .request("DELETE", href, "") + .await + .with_status(StatusCode::NO_CONTENT); + } + + // A sharee that may change the events sees every attendee, but still the + // time only of a private event, and can't write that back over it + owner_client + .acl( + &owner_calendar, + sharee_principal.as_str(), + ["read", "write-content"], + ) + .await + .with_status(StatusCode::OK); + let body = sharee_client + .request("GET", &hidden_href, "") + .await + .with_status(StatusCode::OK) + .expect_body() + .to_string(); + assert!( + body.contains("guest@remote.org"), + "a sharee that may change the event lost its attendees: {body}" + ); + let redacted = sharee_client + .request("GET", &private_href, "") + .await + .with_status(StatusCode::OK) + .expect_body() + .to_string(); + assert!( + !redacted.contains("Dentist appointment"), + "a writer saw a private event's title: {redacted}" + ); + sharee_client + .request("PUT", &private_href, &redacted) + .await + .with_status(StatusCode::FORBIDDEN); + let body = owner_client + .request("GET", &private_href, "") + .await + .with_status(StatusCode::OK) + .expect_body() + .to_string(); + assert!( + body.contains("Dentist appointment") && body.contains("Room 4"), + "a sharee's write wiped a private event: {body}" + ); + + owner_client + .request("DELETE", &owner_calendar, "") + .await + .with_status(StatusCode::NO_CONTENT); + sharee_client.delete_default_containers().await; + owner_client.delete_default_containers().await; + test.assert_is_empty().await; +} + +async fn calendar_id(account: &Account, name: &str) -> String { + account + .jmap_get( + MethodObject::Calendar, + [CalendarProperty::Id, CalendarProperty::Name], + Vec::<&str>::new(), + ) + .await + .list() + .iter() + .find(|calendar| calendar.text_field("name") == name) + .unwrap_or_else(|| panic!("calendar {name}")) + .id() + .to_string() +} + +const PRIVATE_ICS: &str = "BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//Test//Privacy//EN +BEGIN:VEVENT +UID:privacy-private@example.com +DTSTAMP:20200101T000000Z +DTSTART:20200203T100000Z +DTEND:20200203T110000Z +SUMMARY:Dentist appointment +DESCRIPTION:Room 4, bring the files +LOCATION:Main street clinic +CLASS:PRIVATE +BEGIN:VALARM +ACTION:DISPLAY +DESCRIPTION:Reminder text +TRIGGER:-PT15M +END:VALARM +END:VEVENT +END:VCALENDAR +"; + +const CONFIDENTIAL_ICS: &str = "BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//Test//Privacy//EN +BEGIN:VEVENT +UID:privacy-confidential@example.com +DTSTAMP:20200101T000000Z +DTSTART:20200203T100000Z +DTEND:20200203T110000Z +SUMMARY:Performance review +CLASS:CONFIDENTIAL +END:VEVENT +END:VCALENDAR +"; + +const HIDDEN_ICS: &str = "BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//Test//Privacy//EN +BEGIN:VEVENT +UID:privacy-hidden@example.com +DTSTAMP:20200101T000000Z +DTSTART:20200203T100000Z +DTEND:20200203T110000Z +SUMMARY:Board meeting +ORGANIZER:mailto:organizer@remote.org +ATTENDEE;PARTSTAT=ACCEPTED:mailto:organizer@remote.org +ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:jdoe@example.com +ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:guest@remote.org +END:VEVENT +END:VCALENDAR +"; + +const MULTIGET: &str = r#" + + + $HREFS +"#; + +const QUERY_ANY_VEVENT: &str = r#" + + + + + + + +"#; + +const QUERY_SUMMARY_DENTIST: &str = r#" + + + + + + + Dentist + + + + +"#; + +const PROPFIND_CALENDAR_DATA: &str = r#" + + +"#; + +const SYNC_CALENDAR_DATA: &str = r#" + + + 1 + +"#; diff --git a/tests/src/webdav/mod.rs b/tests/src/webdav/mod.rs index dfd0903a..5c35d66a 100644 --- a/tests/src/webdav/mod.rs +++ b/tests/src/webdav/mod.rs @@ -30,6 +30,7 @@ pub mod acl; pub mod basic; pub mod cal_alarm; pub mod cal_itip; +pub mod cal_privacy; // inbuxa: sharees read events as JMAP shows them pub mod cal_query; pub mod cal_scheduling; pub mod card_query; @@ -195,6 +196,7 @@ pub async fn webdav_tests() { lock::test(&test).await; principals::test(&test, assisted_discovery).await; acl::test(&test).await; + cal_privacy::test(&test).await; card_query::test(&test).await; cal_query::test(&test).await; cal_alarm::test(&test).await; diff --git a/tests/src/webdav/principals.rs b/tests/src/webdav/principals.rs index 02bedbad..195255a1 100644 --- a/tests/src/webdav/principals.rs +++ b/tests/src/webdav/principals.rs @@ -11,7 +11,11 @@ use crate::webdav::prop::ALL_DAV_PROPERTIES; use dav_proto::schema::property::{DavProperty, PrincipalProperty, WebDavProperty}; use groupware::DavResourceName; use hyper::StatusCode; -use registry::schema::{prelude::Property, structs::Sharing}; +use registry::schema::{ + enums::Permission, + prelude::{ObjectType, Property}, + structs::{CertificateManagement, DkimManagement, DnsManagement, Domain, Sharing, Tenant}, +}; pub async fn test(test: &TestServer, assisted_discovery: bool) { println!("Running principals tests..."); @@ -564,6 +568,107 @@ pub async fn test(test: &TestServer, assisted_discovery: bool) { .with_hrefs([principal_href("support").as_str()]); set_directory_queries(true).await; + // inbuxa: Test 8: with directory queries on, a tenant's user reads the + // principals of its own tenant but not those of another tenant + let mut tenant_ids = Vec::new(); + let mut domain_ids = Vec::new(); + for (tenant, domain) in [("Tenant T", "t.example.org"), ("Tenant U", "u.example.org")] { + let tenant_id = admin + .registry_create_object(Tenant { + name: tenant.to_string(), + ..Default::default() + }) + .await; + domain_ids.push( + admin + .registry_create_object(Domain { + name: domain.to_string(), + is_enabled: true, + member_tenant_id: Some(tenant_id), + certificate_management: CertificateManagement::Manual, + dns_management: DnsManagement::Manual, + dkim_management: DkimManagement::Manual, + ..Default::default() + }) + .await, + ); + tenant_ids.push(tenant_id); + } + let mut tenant_users = Vec::new(); + for (name, secret, addresses) in [ + ( + "tuser@t.example.org", + "tenant t user passphrase", + &["tuser@t.example.org"], + ), + ( + "tpeer@t.example.org", + "tenant t peer passphrase", + &["tpeer@t.example.org"], + ), + ( + "uuser@u.example.org", + "tenant u user passphrase", + &["uuser@u.example.org"], + ), + ] { + tenant_users.push( + admin + .create_user_account( + name, + secret, + name, + addresses, + vec![Permission::DavPrincipalList], + ) + .await, + ); + } + let tenant_principal = |name: &str| { + format!( + "{}/{}/", + DavResourceName::Principal.base_path(), + name.replace('@', "%40") + ) + }; + let t_client = tenant_users[0].webdav_client(); + t_client + .request( + "PROPFIND", + &tenant_principal("tpeer@t.example.org"), + PRINCIPAL_DISPLAYNAME_QUERY, + ) + .await + .with_status(StatusCode::MULTI_STATUS) + .into_propfind_response(None) + .properties(&tenant_principal("tpeer@t.example.org")) + .get(DavProperty::WebDav(WebDavProperty::DisplayName)) + .with_values(["tpeer@t.example.org"]) + .with_status(StatusCode::OK); + t_client + .request( + "PROPFIND", + &tenant_principal("uuser@u.example.org"), + PRINCIPAL_DISPLAYNAME_QUERY, + ) + .await + .with_status(StatusCode::MULTI_STATUS) + .with_value( + "D:multistatus.D:response.D:status", + "HTTP/1.1 403 Forbidden", + ); + for account in tenant_users { + admin.destroy_account(account).await; + } + admin + .registry_destroy(ObjectType::Domain, domain_ids.iter().copied()) + .await + .assert_destroyed(&domain_ids); + admin + .registry_destroy(ObjectType::Tenant, tenant_ids.iter().copied()) + .await + .assert_destroyed(&tenant_ids); + client.delete_default_containers().await; client .delete_default_containers_by_account("support@example.com") @@ -584,6 +689,9 @@ const PRINCIPAL_MATCH_QUERY: &str = r#" "#; +const PRINCIPAL_DISPLAYNAME_QUERY: &str = r#" +"#; + const PRINCIPAL_SEARCH_PROPERTY_SET_QUERY: &str = r#""#;