Shared mailboxes: full members manage the filters, sorting only (#643) #646

Merged
jcoffey-dev merged 1 commits from fix/643-shared-mailbox-filters into main 2026-11-25 21:03:19 +00:00
13 changed files with 1076 additions and 13 deletions

No files matched your search

+17
View File
@@ -1100,6 +1100,23 @@ impl AccessToken {
.is_some_and(|d| d.access != inbuxa_features::lock::Access::Read)
}
/// inbuxa: #643: a member of the shared mailbox `account_id` at the
/// full level, who manages its filters (sorting only, unless they are
/// also an administrator).
pub fn is_full_shared_mailbox_delegate(&self, account_id: u32) -> bool {
self.delegation(account_id).is_some_and(|d| {
d.kind == inbuxa_features::lock::Kind::SharedMailbox
&& d.access == inbuxa_features::lock::Access::Full
})
}
/// inbuxa: #643: may read and change the Sieve scripts of `account_id`:
/// its owner, a group member, an `Impersonate` holder, or a full member
/// of a shared mailbox.
pub fn manages_sieve(&self, account_id: u32) -> bool {
self.is_member(account_id) || self.is_full_shared_mailbox_delegate(account_id)
}
pub fn delegation(&self, account_id: u32) -> Option<&super::Delegation> {
let now = now();
self.inner
@@ -301,6 +301,66 @@ mod tests {
}
}
// inbuxa: #643: what a shared mailbox's member may save is read from
// the compiled instructions, not from what the script requires
#[test]
fn sieve_sends_mail_reads_the_instructions() {
let sends = |script: &str| {
sieve::Compiler::new()
.compile(script.as_bytes())
.unwrap_or_else(|err| panic!("{script}: {err}"))
.sends_mail()
};
for script in [
"redirect \"[email protected]\";",
"require \"copy\";\nredirect :copy \"[email protected]\";",
"require \"vacation\";\nvacation \"Away.\";",
"require \"enotify\";\nnotify \"mailto:[email protected]\";",
"require \"reject\";\nreject \"Not here.\";",
"require \"ereject\";\nereject \"Not here.\";",
// Behind a test, and in a branch that may never run
"require [\"fileinto\", \"vacation\"];\nif header :contains \"subject\" \"x\" {\n fileinto \"X\";\n} else {\n vacation \"Away.\";\n}",
] {
assert!(sends(script), "{script}");
}
for script in [
"keep;",
"discard;",
"require \"fileinto\";\nif header :contains \"subject\" \"invoice\" { fileinto \"Billing\"; stop; }",
"require [\"imap4flags\", \"fileinto\"];\naddflag \"\\\\Seen\";\nfileinto :flags \"\\\\Flagged\" \"Done\";",
// Required, never used
"require [\"vacation\", \"enotify\", \"reject\", \"copy\"];\nkeep;",
] {
assert!(!sends(script), "{script}");
}
// The same actions compare equal across other edits; a changed
// argument doesn't
let actions = |script: &str| {
sieve::Compiler::new()
.compile(script.as_bytes())
.unwrap_or_else(|err| panic!("{script}: {err}"))
.sending_actions()
};
let forward = "require [\"fileinto\", \"copy\", \"vacation\"];\nredirect :copy \"[email protected]\";\nvacation :days 3 \"Away.\";\n";
let base = actions(forward);
assert_eq!(base.len(), 3, "{base:?}");
assert_eq!(
actions(&format!(
"{forward}if header :contains \"subject\" \"x\" {{ fileinto \"X\"; }}\n"
)),
base
);
for changed in [
forward.replace("[email protected]", "[email protected]"),
forward.replace(":copy ", ""),
forward.replace(":days 3", ":days 4"),
forward.replace("Away.", "Gone."),
] {
assert_ne!(actions(&changed), base, "{changed}");
}
}
// inbuxa: a :regex key compiles to at most 1 MiB; it could take ten
#[test]
fn sieve_regexes_are_size_limited() {
+10
View File
@@ -23,6 +23,8 @@ pub trait JmapAuthorization {
fn assert_is_member(&self, account_id: Id) -> trc::Result<&Self>;
/// inbuxa: AL-8: the account's own, or a delegate allowed to send as it.
fn assert_can_send(&self, account_id: Id) -> trc::Result<&Self>;
/// inbuxa: #643: a member, or a full member of a shared mailbox.
fn assert_manages_sieve(&self, account_id: Id) -> trc::Result<&Self>;
fn assert_has_jmap_permission(
&self,
request: &RequestMethod,
@@ -44,6 +46,14 @@ impl JmapAuthorization for AccessToken {
}
}
fn assert_manages_sieve(&self, account_id: Id) -> trc::Result<&Self> {
if self.manages_sieve(account_id.document_id()) {
Ok(self)
} else {
self.assert_is_member(account_id)
}
}
fn assert_is_member(&self, account_id: Id) -> trc::Result<&Self> {
if self.is_member(account_id.document_id()) {
Ok(self)
+12 -9
View File
@@ -39,10 +39,7 @@ use crate::{
share_notification::{
get::ShareNotificationGet, query::ShareNotificationQuery, set::ShareNotificationSet,
},
sieve::{
get::SieveScriptGet, query::SieveScriptQuery, set::SieveScriptSet,
validate::SieveScriptValidate,
},
sieve::{get::SieveScriptGet, query::SieveScriptQuery, validate::SieveScriptValidate},
submission::{get::EmailSubmissionGet, query::EmailSubmissionQuery, set::EmailSubmissionSet},
thread::get::ThreadGet,
vacation::{get::VacationResponseGet, set::VacationResponseSet},
@@ -484,7 +481,8 @@ impl RequestHandler for Server {
}
GetRequestMethod::Sieve(mut req) => {
resolve_account_id(&mut req.account_id, method_name.obj, access_token)?;
access_token.assert_is_member(req.account_id)?;
// inbuxa: #643: a shared mailbox's full members too
access_token.assert_manages_sieve(req.account_id)?;
self.sieve_script_get(*req).await?.into()
}
@@ -823,7 +821,8 @@ impl RequestHandler for Server {
}
QueryRequestMethod::Sieve(mut req) => {
resolve_account_id(&mut req.account_id, method_name.obj, access_token)?;
access_token.assert_is_member(req.account_id)?;
// inbuxa: #643: a shared mailbox's full members too
access_token.assert_manages_sieve(req.account_id)?;
self.sieve_script_query(*req).await?.into()
}
@@ -949,9 +948,12 @@ impl RequestHandler for Server {
}
SetRequestMethod::Sieve(mut req) => {
resolve_account_id(&mut req.account_id, method_name.obj, access_token)?;
access_token.assert_is_member(req.account_id)?;
// inbuxa: #643: a shared mailbox's full members too,
// sorting only, and every change to its scripts is
// recorded (AU-3)
access_token.assert_manages_sieve(req.account_id)?;
self.sieve_script_set(*req, access_token, session)
crate::inbuxa::shared_filters::set(self, access_token, session, *req)
.await?
.into()
}
@@ -1738,7 +1740,8 @@ impl RequestHandler for Server {
}
RequestMethod::ValidateScript(mut req) => {
resolve_account_id(&mut req.account_id, method_name.obj, access_token)?;
access_token.assert_is_member(req.account_id)?;
// inbuxa: #643: a shared mailbox's full members too
access_token.assert_manages_sieve(req.account_id)?;
self.sieve_script_validate(*req, access_token).await?.into()
}
+8
View File
@@ -158,6 +158,14 @@ impl SessionHandler for Server {
account_capabilities: VecMap::with_capacity(account_capabilities.len()),
};
for capability in access_token.account_capabilities() {
// inbuxa: #643: filters only where they can be managed: a
// member's or an administrator's, or a shared mailbox's
// full members'
if capability == Capability::Sieve
&& !access_token.manages_sieve(account_id.document_id())
{
continue;
}
account.account_capabilities.append(
capability,
account_capabilities
+10 -1
View File
@@ -156,11 +156,20 @@ impl BlobDownload for Server {
EVENT_VIEW_PRIVATE | EVENT_VIEW_HIDE_ATTENDEES,
)
.contains(*document_id),
// inbuxa: #643: a shared mailbox's full
// members read its filters
Collection::SieveScript => {
access_token.is_full_shared_mailbox_delegate(*account_id)
}
_ => false,
}
}
}
BlobClass::Reserved { account_id, .. } => access_token.is_member(*account_id),
// inbuxa: #643: and what a shared mailbox's full
// members upload to it
BlobClass::Reserved { account_id, .. } => {
access_token.manages_sieve(*account_id)
}
}))
}
}
+3 -2
View File
@@ -208,8 +208,9 @@ impl BlobUpload for Server {
// inbuxa: an upload is stored under, and charged to, the account in the
// path, so only that account's owner, a member or an impersonator may
// use it (the same rule as Blob/upload). Checked before anything is
// counted.
if !access_token.is_member(account_id.document_id()) {
// counted. #643: a shared mailbox's full members upload its filters
// there too.
if !access_token.manages_sieve(account_id.document_id()) {
return Err(trc::SecurityEvent::Unauthorized
.into_err()
.ctx(trc::Key::AccountId, access_token.account_id())
+1
View File
@@ -41,6 +41,7 @@ pub mod relay_message; // inbuxa: a relay's queues
pub mod scheduled_reports; // inbuxa: scheduled reports and the weekly digest
pub mod security_acceptance;
pub mod seed; // inbuxa: K-S8: a new store's setup from a file (--seed)
pub mod shared_filters; // inbuxa: #643: a shared mailbox's filters
pub mod sharing_policy;
pub mod store_check; // inbuxa: checking the store's blobs
pub mod store_snapshot; // inbuxa: a snapshot of the store
+253
View File
@@ -0,0 +1,253 @@
/*
* SPDX-FileCopyrightText: 2026 Coffey Labs LLC
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
//! A shared mailbox's filters (#643, multi-account spec MA-S). Its full
//! members manage them as its owner would, sorting only: forwarding and
//! automatic replies are added, changed and turned on by an administrator,
//! and a member may keep or remove them (`SORT_ONLY` and
//! `ACTIVATE_ADMIN_ONLY` in `sieve/set.rs`). Every change to them made by anyone but the account
//! itself is in the audit log (AU-3): a create, update or destroy as
//! `recorded` writes it, and an activation or deactivation as one more
//! record, with the actor and the shared mailbox. Each is written before
//! the change, and if it can't be, nothing is changed.
use crate::sieve::set::SieveScriptSet;
use common::{Server, auth::AccessToken};
use email::sieve::{SieveScript, ingest::SieveScriptIngest};
use http_proto::HttpSessionData;
use inbuxa_features::audit::{Action, Change, EntryId, Outcome, Record, Target};
use jmap_proto::{
method::set::{SetRequest, SetResponse},
object::sieve::Sieve,
request::reference::MaybeIdReference,
};
use serde_json::Value;
use store::{
ValueKey,
write::{AlignedBytes, Archive},
};
use trc::AddContext;
use types::{collection::Collection, id::Id};
/// The kind the records name.
const KIND: &str = "SieveScript";
/// SieveScript/set, recorded when it changes a shared mailbox's scripts
/// and the caller isn't the shared mailbox itself.
pub async fn set(
server: &Server,
access_token: &AccessToken,
session: &HttpSessionData,
request: SetRequest<'_, Sieve>,
) -> trc::Result<SetResponse<Sieve>> {
let account_id = request.account_id.document_id();
if !is_recorded(server, access_token, account_id).await? {
return Box::pin(server.sieve_script_set(request, access_token, session)).await;
}
let activation = Box::pin(activation_before(server, access_token, session, &request)).await?;
let result = crate::inbuxa::audit::recorded(
server,
access_token,
session,
KIND,
None,
None,
request,
|request| Box::pin(server.sieve_script_set(request, access_token, session)),
)
.await;
if let Some((entry, expected)) = activation {
let outcome = match &result {
Err(err) => Outcome::refused(
"serverFail",
err.value_as_str(trc::Key::Details).map(str::to_string),
),
Ok(response) => expected.outcome(response),
};
// The change is done: a failure here is reported, and the record
// stays pending, which verify counts (AU-6)
let _ = server.audit_finish(entry, outcome).await;
}
result
}
/// Whether a change to `account_id`'s scripts is recorded: the account is
/// a shared mailbox and the caller isn't the account itself (a full
/// member, or an administrator reaching it).
async fn is_recorded(
server: &Server,
access_token: &AccessToken,
account_id: u32,
) -> trc::Result<bool> {
if access_token.is_account_id(account_id) {
Ok(false)
} else if access_token.delegated_shared_mailbox(account_id) {
Ok(true)
} else {
Ok(inbuxa_features::lock::get(server.store(), account_id)
.await
.caused_by(trc::location!())?
.is_some_and(|lock| lock.kind == inbuxa_features::lock::Kind::SharedMailbox))
}
}
/// What a recorded activation expects to see in the response.
enum Expected {
/// A script created in this call, by its creation id.
ActivatedCreated(String),
Activated(Id),
Deactivated(Id),
}
impl Expected {
/// Done, refused with the script's own error, or not done because
/// something else in the call was refused.
fn outcome(&self, response: &SetResponse<Sieve>) -> Outcome {
let response = serde_json::to_value(response).unwrap_or_default();
let (done, refused, is_active) = match self {
Expected::ActivatedCreated(id) => {
(format!("/created/{id}"), format!("/notCreated/{id}"), true)
}
Expected::Activated(id) => {
(format!("/updated/{id}"), format!("/notUpdated/{id}"), true)
}
Expected::Deactivated(id) => {
(format!("/updated/{id}"), format!("/notUpdated/{id}"), false)
}
};
if let Some(error) = response.pointer(&refused) {
Outcome::refused(
error["type"].as_str().unwrap_or("forbidden"),
error["description"].as_str().map(str::to_string),
)
} else if response
.pointer(&format!("{done}/isActive"))
.and_then(Value::as_bool)
== Some(is_active)
{
Outcome::success()
} else {
Outcome::refused("notProcessed", None)
}
}
}
/// The pending record for `onSuccessActivateScript` or
/// `onSuccessDeactivateScript`, if the call asks for either. An `isActive`
/// set on a create or update is in that item's own record.
async fn activation_before(
server: &Server,
access_token: &AccessToken,
session: &HttpSessionData,
request: &SetRequest<'_, Sieve>,
) -> trc::Result<Option<(EntryId, Expected)>> {
let account_id = request.account_id.document_id();
let (expected, target_id, name, details, before, after) =
match &request.arguments.on_success_activate_script {
Some(MaybeIdReference::Id(id)) => (
Expected::Activated(*id),
id.to_string(),
script_name(server, account_id, id.document_id()).await?,
"Activated",
false,
true,
),
Some(MaybeIdReference::Reference(reference)) => (
Expected::ActivatedCreated(reference.clone()),
format!("#{reference}"),
request
.create
.as_ref()
.and_then(|create| create.get(reference))
.and_then(|value| serde_json::to_value(value).ok())
.and_then(|value| value.get("name")?.as_str().map(str::to_string)),
"Activated",
false,
true,
),
Some(MaybeIdReference::Invalid(_)) => return Ok(None),
None if request.arguments.on_success_deactivate_script == Some(true) => {
let Some(active_id) = server
.sieve_script_get_active_id(account_id)
.await
.caused_by(trc::location!())?
else {
return Ok(None);
};
let id = Id::from(active_id);
(
Expected::Deactivated(id),
id.to_string(),
script_name(server, account_id, active_id).await?,
"Deactivated",
true,
false,
)
}
None => return Ok(None),
};
let record = Record {
at: ms(),
actor: server.audit_actor(access_token).await,
via: access_token.origin().cloned(),
remote_ip: Some(session.remote_ip),
action: Action::Update,
target: Target {
kind: KIND.to_string(),
id: Some(target_id),
name,
account_id: Some(account_id),
tenant_id: access_token.tenant_id(),
},
changes: vec![Change::new(
"isActive",
Some(before.into()),
Some(after.into()),
)],
details: Some(details.to_string()),
reason: None,
outcome: Outcome::Pending,
};
match server.audit_append(&record).await {
Ok(entry) => Ok(Some((entry, expected))),
Err(err) => Err(err.details("The audit log couldn't be written, so nothing was changed.")),
}
}
async fn script_name(
server: &Server,
account_id: u32,
document_id: u32,
) -> trc::Result<Option<String>> {
let Some(archive) = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
account_id,
Collection::SieveScript,
document_id,
))
.await
.caused_by(trc::location!())?
else {
return Ok(None);
};
Ok(Some(
archive
.to_unarchived::<SieveScript>()
.caused_by(trc::location!())?
.inner
.name
.to_string(),
))
}
fn ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as u64)
}
+180 -1
View File
@@ -47,8 +47,20 @@ pub struct SetContext<'x> {
access_token: &'x AccessToken,
account_cache: &'x AccountCache,
response: SetResponse<Sieve>,
/// inbuxa: #643: saved by a shared mailbox's member who isn't an
/// administrator, who may only sort
sort_only: bool,
}
/// inbuxa: #643: why a shared mailbox's member can't add or change an
/// action that sends or answers mail.
pub const SORT_ONLY: &str =
"Forwarding and automatic replies on a shared mailbox can only be saved by an administrator.";
/// inbuxa: #643: why a shared mailbox's member can't turn on a script that
/// sends or answers mail.
pub const ACTIVATE_ADMIN_ONLY: &str = "Filters that forward or answer mail on a shared mailbox can only be turned on by an administrator.";
pub trait SieveScriptSet: Sync + Send {
fn sieve_script_set(
&self,
@@ -83,6 +95,7 @@ impl SieveScriptSet for Server {
account_id,
access_token,
account_cache: &account,
sort_only: !access_token.is_member(account_id),
response: SetResponse::from_request(&request, self.core.jmap.set_max_objects)?
.with_state(
self.assert_state(
@@ -103,6 +116,11 @@ impl SieveScriptSet for Server {
request.arguments.on_success_activate_script = None;
}
// inbuxa: #643: a member may keep a script that sends mail active,
// and may not turn one on
let active_script_id = self.sieve_script_get_active_id(account_id).await?;
let mut compiled_sends = Vec::new();
// Process creates
let mut batch = BatchBuilder::new();
let mut activations = Vec::new();
@@ -244,6 +262,29 @@ impl SieveScriptSet for Server {
.await?
{
Ok(mut result) => {
// inbuxa: #643: isActive on a script that sends mail
if ctx.sort_only
&& result.set_item == Some(true)
&& active_script_id != Some(document_id)
&& match result.sends_mail {
Some(sends_mail) => sends_mail,
None => !stored_sending_actions(self, account_id, document_id)
.await?
.is_empty(),
}
{
ctx.response.not_updated.append(
id,
SetError::forbidden()
.with_property(SieveProperty::IsActive)
.with_description(ACTIVATE_ADMIN_ONLY),
);
continue 'update;
}
if let Some(sends_mail) = result.sends_mail {
compiled_sends.push((document_id, sends_mail));
}
// Prepare write batch
batch
.with_account_id(account_id)
@@ -321,7 +362,6 @@ impl SieveScriptSet for Server {
}
// Process deletions
let active_script_id = self.sieve_script_get_active_id(account_id).await?;
for id in will_destroy {
let document_id = id.document_id();
if sieve_ids.contains(document_id) {
@@ -364,6 +404,30 @@ impl SieveScriptSet for Server {
}
}
// inbuxa: #643: a member doesn't turn on a script that sends mail;
// an administrator does
if ctx.sort_only
&& let Some(MaybeIdReference::Id(id)) = &request.arguments.on_success_activate_script
{
let id = *id;
let document_id = id.document_id();
if active_script_id != Some(document_id)
&& sieve_ids.contains(document_id)
&& match compiled_sends.iter().find(|(d, _)| *d == document_id) {
Some((_, sends_mail)) => *sends_mail,
None => !stored_sending_actions(self, account_id, document_id)
.await?
.is_empty(),
}
{
ctx.response.not_updated.append(
id,
SetError::forbidden().with_description(ACTIVATE_ADMIN_ONLY),
);
request.arguments.on_success_activate_script = None;
}
}
// Activate / deactivate scripts
let mut activated = None;
let mut deactivated = None;
@@ -555,6 +619,7 @@ impl SieveScriptSet for Server {
}
}
let mut sends_mail = None;
let blob_update = if let Some(blob_id) = blob_id {
if update.as_ref().is_none_or( |(document_id, _)| {
!matches!(blob_id.class, BlobClass::Linked { account_id, collection, document_id: d } if account_id == ctx.account_id && collection == u8::from(Collection::SieveScript) && *document_id == d)
@@ -582,6 +647,32 @@ impl SieveScriptSet for Server {
// Compile script
match self.core.sieve.untrusted_compiler.compile(&bytes) {
Ok(script) => {
// inbuxa: #643: a member may keep or remove the
// actions that send mail an administrator saved
// in this script, never add or change one. Read
// from what the script does, not what it requires
sends_mail = Some(script.sends_mail());
if ctx.sort_only
&& sends_mail == Some(true)
&& !is_sub_multiset(
&script.sending_actions(),
&match &update {
Some((document_id, _)) => {
stored_sending_actions(
self,
ctx.account_id,
*document_id,
)
.await?
}
None => Vec::new(),
},
)
{
return Ok(Err(SetError::forbidden()
.with_property(SieveProperty::BlobId)
.with_description(SORT_ONLY)));
}
changes.size = bytes.len() as u32;
bytes.extend(Archiver::new(script).untrusted().serialize().caused_by(trc::location!())?);
bytes.into()
@@ -620,6 +711,7 @@ impl SieveScriptSet for Server {
.with_current_opt(update.map(|(_, current)| current)),
blob_update,
set_item,
sends_mail,
}))
}
}
@@ -628,4 +720,91 @@ pub struct SetItemResponse<'x> {
builder: ObjectIndexBuilder<&'x ArchivedSieveScript, SieveScript>,
blob_update: Option<Vec<u8>>,
set_item: Option<bool>,
/// inbuxa: #643: whether a new script sends mail, when one was compiled
sends_mail: Option<bool>,
}
/// inbuxa: #643: the actions that send mail in a stored script, compiled
/// from its text. A script that no longer compiles has none, so nothing it
/// held counts as kept.
async fn stored_sending_actions(
server: &Server,
account_id: u32,
document_id: u32,
) -> trc::Result<Vec<String>> {
let Some(archive) = server
.store()
.get_value::<Archive<AlignedBytes>>(ValueKey::archive(
account_id,
Collection::SieveScript,
document_id,
))
.await
.caused_by(trc::location!())?
else {
return Ok(Vec::new());
};
let script = archive
.unarchive::<SieveScript>()
.caused_by(trc::location!())?;
let size = u32::from(script.size) as usize;
Ok(server
.blob_store()
.get_blob(script.blob_hash.0.as_ref(), 0..usize::MAX)
.await
.caused_by(trc::location!())?
.and_then(|bytes| {
server
.core
.sieve
.untrusted_compiler
.compile(bytes.get(..size)?)
.ok()
})
.map(|script| script.sending_actions())
.unwrap_or_default())
}
/// inbuxa: #643: every item of `new` is in `old`, as often or less; both
/// sorted.
fn is_sub_multiset(new: &[String], old: &[String]) -> bool {
let mut old = old.iter();
'new: for item in new {
for candidate in old.by_ref() {
match candidate.cmp(item) {
std::cmp::Ordering::Less => continue,
std::cmp::Ordering::Equal => continue 'new,
std::cmp::Ordering::Greater => return false,
}
}
return false;
}
true
}
#[cfg(test)]
mod tests {
#[test]
fn sending_actions_may_be_kept_or_removed() {
let list = |items: &[&str]| items.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let old = list(&["redirect a", "redirect a", "vacation"]);
for kept in [
&[][..],
&["redirect a"],
&["redirect a", "redirect a"],
&["redirect a", "vacation"],
&["redirect a", "redirect a", "vacation"],
] {
assert!(super::is_sub_multiset(&list(kept), &old), "{kept:?}");
}
for changed in [
&["redirect b"][..],
&["redirect a", "redirect a", "redirect a"],
&["notify", "redirect a"],
&["redirect a", "redirect a", "vacation", "vacation"],
&["zzz"],
] {
assert!(!super::is_sub_multiset(&list(changed), &old), "{changed:?}");
}
}
}
+475
View File
@@ -500,6 +500,7 @@ pub async fn test(test: &mut TestServer) {
);
shared_mailbox(test, admin, &mut smtp_rx, &mut lmtp).await;
shared_mailbox_filters(admin, &mut smtp_rx, &mut lmtp).await;
}
/// AL-12: a lock reaches only an account whose every permission the caller
@@ -883,6 +884,480 @@ async fn shared_mailbox(
);
}
/// #643 (MA-S): a shared mailbox's full members manage its filters, which
/// may only sort unless an administrator saves them; read and organize
/// members can't, the session says so, and every change is recorded.
async fn shared_mailbox_filters(
admin: &Account,
smtp_rx: &mut tokio::sync::mpsc::Receiver<crate::jmap::mail::submission::MockMessage>,
lmtp: &mut SmtpConnection,
) {
println!("Running shared mailbox filter tests...");
let helpdesk = admin
.create_user_account(
"[email protected]",
"frontdesk-secret-6613",
"Help desk",
&[],
vec![],
)
.await;
let mut members = Vec::new();
for (name, access) in [
("[email protected]", "full"),
("[email protected]", "organize"),
("[email protected]", "read"),
] {
let member = admin
.create_user_account(name, "member-secret-2290", "Member", &[], vec![])
.await;
members.push((member, access));
}
let helpdesk_id = helpdesk.id_string().to_string();
// A folder to sort into, made while it could still sign in
let billing_id = helpdesk
.jmap_client()
.await
.mailbox_create("Billing", None::<String>, jmap_client::mailbox::Role::None)
.await
.unwrap()
.take_id();
let response = admin
.lock_set(
json!({"create": {"h": {"accountId": helpdesk_id, "kind": "sharedMailbox",
"delegates": members.iter().map(|(member, access)|
json!({"accountId": member.id_string(), "access": access})).collect::<Vec<_>>()}}}),
)
.await;
assert_eq!(
response["created"]["h"]["id"],
helpdesk_id.as_str(),
"#643: {response}"
);
let (filer, _) = &members[0];
// Session honesty: filters are offered to the full member only
for (member, access) in &members {
let session = member.jmap_session_object().await.0;
let offered = session["accounts"][helpdesk_id.as_str()]["accountCapabilities"]
.get(SIEVE)
.is_some();
assert_eq!(
offered,
*access == "full",
"#643: {access} member's session: {session}"
);
}
// Read and organize members get Forbidden, as before
for (member, access) in &members[1..] {
for (method, arguments) in [
(
"SieveScript/get",
json!({"accountId": helpdesk_id, "ids": null}),
),
("SieveScript/query", json!({"accountId": helpdesk_id})),
(
"SieveScript/set",
json!({"accountId": helpdesk_id, "destroy": ["a"]}),
),
] {
let response = sieve_call(member, method, arguments).await;
assert_eq!(
(response[0].as_str(), response[1]["type"].as_str()),
(Some("error"), Some("forbidden")),
"#643: {access} member, {method}: {response}"
);
}
let response = member
.http_post_raw(
&format!("{}/jmap/upload/{}/", member.base_url(), helpdesk_id),
"application/sieve",
b"keep;".to_vec(),
)
.await;
assert_ne!(response.status, 200, "#643: {access} member uploaded");
}
// The full member saves and activates a sorting script
let sorting = "require [\"fileinto\", \"imap4flags\"];\r\n\
if header :contains \"subject\" \"Invoice\" {\r\n \
fileinto :flags \"\\\\Flagged\" \"Billing\";\r\n stop;\r\n}\r\n";
let blob_id = sieve_upload(filer, &helpdesk_id, sorting).await;
let response = sieve_call(
filer,
"SieveScript/validate",
json!({"accountId": helpdesk_id, "blobId": blob_id}),
)
.await;
assert_eq!(response[0], "SieveScript/validate", "#643: {response}");
assert!(response[1]["error"].is_null(), "#643: {response}");
let response = sieve_call(
filer,
"SieveScript/set",
json!({"accountId": helpdesk_id,
"create": {"s": {"name": "Sort", "blobId": blob_id}},
"onSuccessActivateScript": "#s"}),
)
.await;
assert_eq!(
response[1]["created"]["s"]["isActive"], true,
"#643: the full member's sorting script: {response}"
);
let sort_id = response[1]["created"]["s"]["id"]
.as_str()
.unwrap()
.to_string();
let sort_blob = response[1]["created"]["s"]["blobId"]
.as_str()
.unwrap()
.to_string();
// It reads the script back, and its text
let response = sieve_call(
filer,
"SieveScript/get",
json!({"accountId": helpdesk_id, "ids": null}),
)
.await;
assert_eq!(
response[1]["list"][0]["id"],
sort_id.as_str(),
"#643: {response}"
);
let download = filer
.http_get_raw(
&format!(
"{}/jmap/download/{}/{}/sort.sieve",
filer.base_url(),
helpdesk_id,
sort_blob
),
None,
)
.await;
assert_eq!(
download.body,
sorting.as_bytes(),
"#643: download {}",
download.status
);
// Mail to the shared address is sorted by it
lmtp.ingest(
"[email protected]",
&["[email protected]"],
"From: [email protected]\r\nTo: [email protected]\r\nSubject: Invoice 3141\r\n\r\nPlease pay.\r\n",
)
.await;
let response = sieve_call(
filer,
"Email/query",
json!({"accountId": helpdesk_id, "filter": {"inMailbox": billing_id}}),
)
.await;
assert_eq!(
response[1]["ids"].as_array().map(Vec::len),
Some(1),
"#643: the invoice wasn't filed: {response}"
);
// Sort only: forwarding and automatic replies are refused, whatever
// the require line says, and the active script stays as it was
for script in [
"redirect \"[email protected]\";",
"require \"copy\";\r\nredirect :copy \"[email protected]\";",
"require \"vacation\";\r\nvacation \"We're closed.\";",
"require \"enotify\";\r\nnotify \"mailto:[email protected]\";",
"require \"reject\";\r\nreject \"Not here.\";",
"require [\"fileinto\", \"ereject\"];\r\nif false { ereject \"No.\"; }\r\nfileinto \"Billing\";",
] {
let blob_id = sieve_upload(filer, &helpdesk_id, script).await;
let response = sieve_call(
filer,
"SieveScript/set",
json!({"accountId": helpdesk_id,
"create": {"f": {"name": "Forward", "blobId": blob_id}},
"update": {sort_id.as_str(): {"blobId": blob_id}},
"onSuccessActivateScript": "#f"}),
)
.await;
for error in [
&response[1]["notCreated"]["f"],
&response[1]["notUpdated"][sort_id.as_str()],
] {
assert_eq!(error["type"], "forbidden", "#643: {script}: {response}");
assert_eq!(
error["description"],
"Forwarding and automatic replies on a shared mailbox can only be saved by an administrator.",
"#643: {script}: {response}"
);
}
}
let response = sieve_call(
filer,
"SieveScript/get",
json!({"accountId": helpdesk_id, "ids": null}),
)
.await;
let list = response[1]["list"].as_array().unwrap();
assert_eq!(list.len(), 1, "#643: {response}");
assert_eq!(list[0]["isActive"], true, "#643: {response}");
assert_eq!(list[0]["blobId"], sort_blob.as_str(), "#643: {response}");
expect_nothing(smtp_rx).await;
// An administrator adds a forward to the active script. Its member may
// then edit the other rules and remove the forward, but not change it
let require = "require [\"fileinto\", \"imap4flags\", \"copy\"];\r\n";
let invoices = "if header :contains \"subject\" \"Invoice\" {\r\n \
fileinto :flags \"\\\\Flagged\" \"Billing\";\r\n stop;\r\n}\r\n";
let receipts = "if header :contains \"subject\" \"Receipt\" { fileinto \"Billing\"; }\r\n";
let forward = |to: &str| format!("redirect :copy \"{to}\";\r\n");
let response = sieve_save(
admin,
&helpdesk_id,
&sort_id,
format!("{require}{}{invoices}", forward("[email protected]")),
)
.await;
assert!(
response[1]["updated"].get(sort_id.as_str()).is_some(),
"#643: the administrator's forward: {response}"
);
let response = sieve_save(
filer,
&helpdesk_id,
&sort_id,
format!(
"{require}{}{receipts}{invoices}",
forward("[email protected]")
),
)
.await;
let kept_blob = response[1]["updated"][sort_id.as_str()]["blobId"]
.as_str()
.unwrap_or_else(|| panic!("#643: another rule, the forward kept: {response}"))
.to_string();
let response = sieve_save(
filer,
&helpdesk_id,
&sort_id,
format!(
"{require}{}{receipts}{invoices}",
forward("[email protected]")
),
)
.await;
assert_eq!(
response[1]["notUpdated"][sort_id.as_str()]["description"],
"Forwarding and automatic replies on a shared mailbox can only be saved by an administrator.",
"#643: the forward's address changed: {response}"
);
let response = sieve_call(
filer,
"SieveScript/get",
json!({"accountId": helpdesk_id, "ids": [sort_id]}),
)
.await;
assert_eq!(
response[1]["list"][0]["blobId"],
kept_blob.as_str(),
"#643: {response}"
);
let response = sieve_save(
filer,
&helpdesk_id,
&sort_id,
format!("{require}{receipts}{invoices}"),
)
.await;
assert!(
response[1]["updated"].get(sort_id.as_str()).is_some(),
"#643: the forward removed: {response}"
);
// A member doesn't turn on a script that forwards; an administrator
// does, and the member may turn it off and delete it
let blob_id = sieve_upload(admin, &helpdesk_id, "redirect \"[email protected]\";").await;
let response = sieve_call(
admin,
"SieveScript/set",
json!({"accountId": helpdesk_id,
"create": {"a": {"name": "Forward to the old desk", "blobId": blob_id}}}),
)
.await;
let forward_id = response[1]["created"]["a"]["id"]
.as_str()
.unwrap_or_else(|| panic!("#643: the administrator's script: {response}"))
.to_string();
for arguments in [
json!({"accountId": helpdesk_id, "onSuccessActivateScript": forward_id}),
json!({"accountId": helpdesk_id, "update": {forward_id.as_str(): {"isActive": true}}}),
] {
let response = sieve_call(filer, "SieveScript/set", arguments).await;
let error = &response[1]["notUpdated"][forward_id.as_str()];
assert_eq!(error["type"], "forbidden", "#643: {response}");
assert_eq!(
error["description"],
"Filters that forward or answer mail on a shared mailbox can only be turned on by an administrator.",
"#643: {response}"
);
}
let response = sieve_call(
filer,
"SieveScript/get",
json!({"accountId": helpdesk_id, "ids": [sort_id, forward_id]}),
)
.await;
assert_eq!(
response[1]["list"]
.as_array()
.unwrap()
.iter()
.map(|s| (s["id"].as_str().unwrap().to_string(), s["isActive"] == true))
.collect::<Vec<_>>(),
[(sort_id.clone(), true), (forward_id.clone(), false)],
"#643: {response}"
);
let response = sieve_call(
admin,
"SieveScript/set",
json!({"accountId": helpdesk_id, "onSuccessActivateScript": forward_id}),
)
.await;
assert_eq!(
response[1]["updated"][forward_id.as_str()]["isActive"],
true,
"#643: {response}"
);
let response = sieve_call(
filer,
"SieveScript/set",
json!({"accountId": helpdesk_id, "onSuccessDeactivateScript": true}),
)
.await;
assert_eq!(
response[1]["updated"][forward_id.as_str()]["isActive"],
false,
"#643: {response}"
);
let response = sieve_call(
filer,
"SieveScript/set",
json!({"accountId": helpdesk_id, "destroy": [forward_id]}),
)
.await;
assert_eq!(
response[1]["destroyed"][0],
forward_id.as_str(),
"#643: {response}"
);
// Every change is in the audit log, with who made it and where
let records = sieve_records(admin, filer, &helpdesk_id).await;
let seen = |action: &str, details: Option<&str>, status: &str| {
records.iter().any(|r| {
r["action"] == action
&& details.is_none_or(|d| r["details"] == d)
&& r["outcome"]["status"] == status
&& r["target"]["accountId"] == helpdesk_id.as_str()
&& r["actor"]["accountId"] == filer.id_string()
})
};
for (action, details, status) in [
("create", None, "success"),
("update", Some("Activated"), "success"),
("update", Some("Deactivated"), "success"),
("destroy", None, "success"),
// The refused forwarding scripts and the activations asked for
("create", None, "refused"),
("update", None, "refused"),
("update", Some("Activated"), "refused"),
] {
assert!(
seen(action, details, status),
"#643: no {action} {details:?} {status} record: {records:?}"
);
}
assert!(
sieve_records(admin, admin, &helpdesk_id)
.await
.iter()
.any(|r| r["action"] == "create" && r["outcome"]["status"] == "success"),
"#643: the administrator's script wasn't recorded"
);
let response = admin.lock_set(json!({"destroy": [helpdesk_id]})).await;
assert_eq!(
response["destroyed"][0],
helpdesk_id.as_str(),
"#643: {response}"
);
}
const SIEVE: &str = "urn:ietf:params:jmap:sieve";
async fn sieve_call(account: &Account, method: &str, arguments: Value) -> Value {
let using = [USING, &[SIEVE]].concat();
let response = account
.jmap_request(&using, json!([[method, arguments, "0"]]))
.await
.0;
response
.pointer("/methodResponses/0")
.cloned()
.unwrap_or_else(|| panic!("{method}: {response}"))
}
/// Replaces a script's text.
async fn sieve_save(account: &Account, account_id: &str, script_id: &str, script: String) -> Value {
let blob_id = sieve_upload(account, account_id, &script).await;
sieve_call(
account,
"SieveScript/set",
json!({"accountId": account_id, "update": {script_id: {"blobId": blob_id}}}),
)
.await
}
async fn sieve_upload(account: &Account, account_id: &str, script: &str) -> String {
let response = account
.http_post_raw(
&format!("{}/jmap/upload/{account_id}/", account.base_url()),
"application/sieve",
script.as_bytes().to_vec(),
)
.await;
assert_eq!(
response.status,
200,
"#643: upload: {}",
String::from_utf8_lossy(&response.body)
);
serde_json::from_slice::<Value>(&response.body).unwrap()["blobId"]
.as_str()
.unwrap()
.to_string()
}
/// The audit records of `actor`'s changes to `account_id`'s scripts.
async fn sieve_records(admin: &Account, actor: &Account, account_id: &str) -> Vec<Value> {
let (_, query) = admin
.call(
"inbuxa:AuditEvent/query",
json!({"accountId": admin.id_string(), "filter": {"actorId": actor.id_string(),
"accountId": account_id, "targetKind": "SieveScript"}}),
)
.await;
let (_, records) = admin
.call(
"inbuxa:AuditEvent/get",
json!({"accountId": admin.id_string(), "ids": query["ids"]}),
)
.await;
records["list"].as_array().cloned().unwrap_or_default()
}
/// Runs these tests alone: `cargo test -p tests account_lock_tests -- --ignored`.
#[ignore]
#[tokio::test(flavor = "multi_thread")]
+7
View File
@@ -131,6 +131,13 @@ Every changed file carries the AGPL 5(a) notice in its header.
redirects to an account that sends the mail back. The
`enclose_hop_tests` in `action_mime.rs` cover it (run like
`scan_limit_tests`).
- `src/lib.rs`: `Sieve::sends_mail()` says whether a compiled script holds
`redirect`, `vacation`, `notify` or `reject`/`ereject`, read from its
instructions, and `Sieve::sending_actions()` lists each of them with its
arguments, sorted. The server uses them to keep a shared mailbox's member
who isn't an administrator from adding or changing those actions (#643).
The `sieve_sends_mail_reads_the_instructions` test in `crates/common`
covers both.
- `Cargo.toml`: the example target is dropped, with the top-level
`examples/` and `tests/`, which the server never builds. (`src/` keeps its
own `tests` modules: the crate declares them.)
+40
View File
@@ -40,6 +40,46 @@ pub struct Sieve {
num_match_vars: u32,
}
impl Sieve {
/// inbuxa: whether the compiled script holds an action that sends or
/// answers mail: `redirect` (with or without `:copy`), `vacation`,
/// `notify` (enotify) or `reject`/`ereject`. Read from the instructions,
/// not the `require` line, so a capability required and never used
/// doesn't count and one used without being required (with the
/// capability check off) does.
pub fn sends_mail(&self) -> bool {
self.instructions.iter().any(is_sending)
}
/// inbuxa: each of those actions with its arguments (the address, the
/// reply and its `:days`, `:addresses` and `:handle`, the method, the
/// reason), as text that is equal only for the same action written the
/// same way. Sorted, so two scripts' lists compare as multisets.
pub fn sending_actions(&self) -> Vec<String> {
let mut actions = self
.instructions
.iter()
.filter(|instruction| is_sending(instruction))
.map(|instruction| format!("{instruction:?}"))
.collect::<Vec<_>>();
actions.sort_unstable();
actions
}
}
/// inbuxa: an action that sends or answers mail, or the test that holds a
/// vacation reply's period, addresses and handle.
fn is_sending(instruction: &Instruction) -> bool {
matches!(
instruction,
Instruction::Redirect(_)
| Instruction::Vacation(_)
| Instruction::Notify(_)
| Instruction::Reject(_)
| Instruction::Test(compiler::grammar::test::Test::Vacation(_))
)
}
#[derive(Clone)]
pub struct Compiler {
// Settings