Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(calendar): judge Add guests by each copy's own inbox and provider (#8556)

gbirmanfedb889f969f
diff --git a/.sqlx/query-1e940847546512da10cc8270591d9eb83caba353443c96fcfab9f37f9d33b0aa.json b/.sqlx/query-1e940847546512da10cc8270591d9eb83caba353443c96fcfab9f37f9d33b0aa.json
new file mode 100644
index 0000000000..0ee045d44c
--- /dev/null
+++ b/.sqlx/query-1e940847546512da10cc8270591d9eb83caba353443c96fcfab9f37f9d33b0aa.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id AS link_id,\n email_address::text AS \"email_address!\",\n provider::text AS \"provider!\"\n FROM email_links\n WHERE macro_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "email_address!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "provider!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "1e940847546512da10cc8270591d9eb83caba353443c96fcfab9f37f9d33b0aa"
+}
diff --git a/.sqlx/query-4bc9261979cc9d7efd0c2caa7a09cbb0748f5386de237ae04df72e73e594995a.json b/.sqlx/query-4bc9261979cc9d7efd0c2caa7a09cbb0748f5386de237ae04df72e73e594995a.json
deleted file mode 100644
index 950101d168..0000000000
--- a/.sqlx/query-4bc9261979cc9d7efd0c2caa7a09cbb0748f5386de237ae04df72e73e594995a.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT email_address::text AS \"email_address!\"\n FROM email_links\n WHERE macro_id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "email_address!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "4bc9261979cc9d7efd0c2caa7a09cbb0748f5386de237ae04df72e73e594995a"
-}
diff --git a/apps/docs/AI/mcp/tools/update-calendar-event.mdx b/apps/docs/AI/mcp/tools/update-calendar-event.mdx
index 5931a6b5b1..b25082af15 100644
--- a/apps/docs/AI/mcp/tools/update-calendar-event.mdx
+++ b/apps/docs/AI/mcp/tools/update-calendar-event.mdx
@@ -10,7 +10,7 @@ Update an existing calendar event. Only the supplied fields change; omitted fiel
`scope` picks how much of a recurring series changes and is always required: "this_event" edits one occurrence (pass the occurrence's `recurrenceId` from ListCalendarEvents) and leaves the rest of the series alone; "all" edits the series itself — with `time` that MOVES EVERY OCCURRENCE, so never use "all" to reschedule a single occurrence. Non-recurring events use "all". There is no this-and-following update: end the series with DeleteCalendarEvent's "this_and_following" and create a new event instead.
-Passing `attendees` replaces the full attendee list — include everyone who should remain, not just additions. That holds when `viewerCan.removeGuests` from ListCalendarEvents is true (the user organizes the event, or the organizer lets guests modify it). When it is false, the list may only grow: pass the current attendees plus the additions; the additions are invited without touching anyone else, and dropping any guest fails. Adding guests then needs `viewerCan.inviteGuests`; otherwise the organizer doesn't let guests invite others or hides the guest list. An empty string for `description` or `location` clears it. Fails on events from calendars the user cannot edit.
+Passing `attendees` replaces the full attendee list — include everyone who should remain, not just additions. That holds when `viewerCan.removeGuests` from ListCalendarEvents is true (the user organizes the event, or the organizer lets guests modify it). When it is false, the list may only grow: pass the current attendees plus the additions; the additions are invited without touching anyone else, and dropping any guest fails. Adding guests then needs `viewerCan.inviteGuests`; otherwise the organizer doesn't let guests invite others or hides the guest list, or the event is an Outlook meeting the user doesn't organize. An empty string for `description` or `location` clears it. Fails on events from calendars the user cannot edit.
`rsvp` sets the user's own response to an invitation and is independent of the field edits — it can be the only thing this call changes. It applies at the same `scope` as the rest of the call, and only works on events the user is actually an attendee of.
diff --git a/apps/web/src/lib/service-clients/service-calendar/openapi.json b/apps/web/src/lib/service-clients/service-calendar/openapi.json
index 72cae5ccce..ae100ebc0f 100644
--- a/apps/web/src/lib/service-clients/service-calendar/openapi.json
+++ b/apps/web/src/lib/service-clients/service-calendar/openapi.json
@@ -404,7 +404,7 @@
"description": "Authentication required"
},
"403": {
- "description": "Calendar is read-only, the organizer doesn't let guests invite others, or the calendar needs reauthorization",
+ "description": "Calendar is read-only, only the organizer can invite guests, or the calendar needs reauthorization",
"content": {
"application/json": {
"schema": {
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 685104c710..4e4f16e1e1 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -14821,7 +14821,7 @@ export interface UpdateBookingSettings {
*
* `scope` picks how much of a recurring series changes and is always required: "this_event" edits one occurrence (pass the occurrence's `recurrenceId` from ListCalendarEvents) and leaves the rest of the series alone; "all" edits the series itself — with `time` that MOVES EVERY OCCURRENCE, so never use "all" to reschedule a single occurrence. Non-recurring events use "all". There is no this-and-following update: end the series with DeleteCalendarEvent's "this_and_following" and create a new event instead.
*
- * Passing `attendees` replaces the full attendee list — include everyone who should remain, not just additions. That holds when `viewerCan.removeGuests` from ListCalendarEvents is true (the user organizes the event, or the organizer lets guests modify it). When it is false, the list may only grow: pass the current attendees plus the additions; the additions are invited without touching anyone else, and dropping any guest fails. Adding guests then needs `viewerCan.inviteGuests`; otherwise the organizer doesn't let guests invite others or hides the guest list. An empty string for `description` or `location` clears it. Fails on events from calendars the user cannot edit.
+ * Passing `attendees` replaces the full attendee list — include everyone who should remain, not just additions. That holds when `viewerCan.removeGuests` from ListCalendarEvents is true (the user organizes the event, or the organizer lets guests modify it). When it is false, the list may only grow: pass the current attendees plus the additions; the additions are invited without touching anyone else, and dropping any guest fails. Adding guests then needs `viewerCan.inviteGuests`; otherwise the organizer doesn't let guests invite others or hides the guest list, or the event is an Outlook meeting the user doesn't organize. An empty string for `description` or `location` clears it. Fails on events from calendars the user cannot edit.
*
* `rsvp` sets the user's own response to an invitation and is independent of the field edits — it can be the only thing this call changes. It applies at the same `scope` as the rest of the call, and only works on events the user is actually an attendee of.
*/
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.md
index 2deb89bf2a..24b0fe891d 100644
--- a/crates/calendar_events/AGENTS.md
+++ b/crates/calendar_events/AGENTS.md
@@ -65,12 +65,20 @@ reminder dispatch, team availability, and provider/Postgres persistence.
`attendeesOmitted` mode (`omittedAttendeesSpecified`), so the invite writes
the whole list Google returned plus the new guests, and a guest is refused
(`guest_list_hidden`) while the organizer hides the guest list, since their
- copy lacks the guests it would drop.
+ copy lacks the guests it would drop. Microsoft Graph has no attendee-side
+ write either: an Outlook organizer adds guests with the same full-list write
+ (`email_api_client`'s `outlook/calendar/invite.rs`), and an Outlook guest may
+ only answer (`guests_cannot_invite`).
- `viewer_can` is viewer-relative, like an attendee's `is_self`: resolve it with
- `ActorInboxes::mark_event` wherever a read path marks the viewer, and never
- store it. `guest_policy` is stored on the entity row (the canonical copy's
- values) and in each source's projection, omitted there while it holds Google's
- default. Event responses always carry both; `StoredSourceProjection` strips
+ `ActorInboxes::mark_event` and the copy's source link wherever a read path
+ marks the viewer, and never store it. Each connected inbox gets its own copy
+ (entity) of an event, written through that inbox's grant, so the viewer
+ organizes or attends a copy only as its inbox: another of their inboxes on
+ the same event lends it nothing, and only that inbox's row is `is_self`.
+ Mutations act as `CalendarEventMutationTarget::copy_inbox`. A delegate owns
+ no copy inbox and gets nothing beyond the no-attendees rule. `guest_policy` is
+ stored on the entity row (the canonical copy's values) and in each source's
+ projection, omitted there while it holds Google's default. Event responses always carry both; `StoredSourceProjection` strips
them so unchanged events keep comparing equal.
- Preserve the conservative OOO refresh hint on write outcomes and sync reports;
its contract is in [team sharing](../../docs/design/calendar-team-sharing.md).
diff --git a/crates/calendar_events/src/domain/acting.rs b/crates/calendar_events/src/domain/acting.rs
index 685fa150f9..c5524a63d1 100644
--- a/crates/calendar_events/src/domain/acting.rs
+++ b/crates/calendar_events/src/domain/acting.rs
@@ -1,79 +1,130 @@
//! The clicker's owned inboxes.
-use super::models::{CalendarAttendee, CalendarEvent, ViewerCapabilities};
+use uuid::Uuid;
-/// The clicker's own connected-inbox addresses.
+use super::models::{CalendarAttendee, CalendarEvent, CalendarProvider, ViewerCapabilities};
+
+/// One connected inbox the clicker owns.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct OwnedInbox {
+ /// The inbox's email link. Every copy of an event synced through the
+ /// inbox carries it as its source link.
+ pub link_id: Uuid,
+ /// The inbox's address.
+ pub email: String,
+ /// The provider the inbox's calendar syncs from.
+ pub provider: CalendarProvider,
+}
+
+impl OwnedInbox {
+ /// Whether an attendee address is this inbox's.
+ pub fn matches(&self, email: &str) -> bool {
+ self.email.eq_ignore_ascii_case(email)
+ }
+}
+
+/// The clicker's own connected inboxes.
///
-/// These are the attendee rows the user may RSVP as, and the rows a viewer
-/// sees marked as `(you)`. The set is non-empty, lowercased, and
-/// deduplicated. Constructors only accept addresses from inboxes the
-/// requester owns (`email_links.macro_id = requester`), so a calendar
-/// owner's address cannot enter this type unless the clicker owns that
-/// inbox too.
+/// These are the addresses the user may RSVP as. Each copy of an event syncs
+/// through one inbox, and the clicker relates to that copy only through it:
+/// its attendee row is the one a viewer sees marked `(you)`, and whether it
+/// organizes or attends decides what the clicker may do with the copy. The
+/// set is non-empty, lowercased, and deduplicated. Constructors only accept
+/// inboxes the requester owns (`email_links.macro_id = requester`), so a
+/// calendar owner's address cannot enter this type unless the clicker owns
+/// that inbox too.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ActorInboxes {
- emails: Vec<String>,
+ inboxes: Vec<OwnedInbox>,
}
impl ActorInboxes {
- /// Normalize the requester's owned inbox addresses.
+ /// Normalize the requester's owned inboxes.
///
/// Returns `None` when the requester owns no connected inbox. RSVP
/// treats that as [`super::ports::CalendarMutationError::NotAttendee`].
/// Display leaves provider `is_self` flags untouched.
- pub(crate) fn from_owned(owned_inbox_emails: Vec<String>) -> Option<Self> {
- let mut emails: Vec<String> = owned_inbox_emails
+ pub(crate) fn from_owned(owned_inboxes: Vec<OwnedInbox>) -> Option<Self> {
+ let mut inboxes: Vec<OwnedInbox> = owned_inboxes
.into_iter()
- .map(|email| email.to_ascii_lowercase())
- .filter(|email| !email.is_empty())
+ .map(|inbox| OwnedInbox {
+ email: inbox.email.to_ascii_lowercase(),
+ ..inbox
+ })
+ .filter(|inbox| !inbox.email.is_empty())
.collect();
- emails.sort();
- emails.dedup();
- if emails.is_empty() {
+ inboxes
+ .sort_by(|left, right| (&left.email, left.link_id).cmp(&(&right.email, right.link_id)));
+ inboxes.dedup_by_key(|inbox| inbox.link_id);
+ if inboxes.is_empty() {
None
} else {
- Some(Self { emails })
+ Some(Self { inboxes })
}
}
- /// A single-address actor for fixtures.
+ /// A single Google inbox for fixtures.
#[cfg(test)]
pub(crate) fn sole(email: impl Into<String>) -> Self {
Self {
- emails: vec![email.into().to_ascii_lowercase()],
+ inboxes: vec![OwnedInbox {
+ link_id: Uuid::nil(),
+ email: email.into().to_ascii_lowercase(),
+ provider: CalendarProvider::Google,
+ }],
}
}
/// Whether an attendee address belongs to the actor.
pub fn matches(&self, email: &str) -> bool {
- let email = email.to_ascii_lowercase();
- self.emails.iter().any(|existing| existing == &email)
+ self.inboxes.iter().any(|inbox| inbox.matches(email))
}
/// Restrict a response to one address already verified as owned by the requester.
pub(crate) fn select(&self, email: &str) -> Option<Self> {
- self.matches(email).then(|| Self {
- emails: vec![email.to_ascii_lowercase()],
+ let inboxes: Vec<OwnedInbox> = self
+ .inboxes
+ .iter()
+ .filter(|inbox| inbox.matches(email))
+ .cloned()
+ .collect();
+ (!inboxes.is_empty()).then_some(Self { inboxes })
+ }
+
+ /// The actor's inbox a copy syncs through, by the copy's source link.
+ /// `None` when the actor does not own it, as for a delegate looking at
+ /// the inbox they were granted.
+ pub fn inbox(&self, link_id: Uuid) -> Option<&OwnedInbox> {
+ self.inboxes.iter().find(|inbox| inbox.link_id == link_id)
+ }
+
+ /// The actor acting through the inbox a copy syncs through; see
+ /// [`Self::inbox`].
+ pub(crate) fn through(&self, link_id: Uuid) -> Option<Self> {
+ self.inbox(link_id).map(|inbox| Self {
+ inboxes: vec![inbox.clone()],
})
}
- /// Set `is_self` on the actor's rows and clear it on every other row.
- pub fn mark_attendees(&self, attendees: &mut [CalendarAttendee]) {
+ /// Set `is_self` on the rows of the inbox the copy synced through
+ /// `link_id` belongs to and clear it on every other row.
+ pub fn mark_attendees(&self, attendees: &mut [CalendarAttendee], link_id: Uuid) {
+ let inbox = self.inbox(link_id);
for attendee in attendees {
- attendee.is_self = self.matches(&attendee.email);
+ attendee.is_self = inbox.is_some_and(|inbox| inbox.matches(&attendee.email));
}
}
- /// Mark the actor's attendee rows on an event and resolve what the actor
- /// may do with it.
- pub fn mark_event(&self, event: &mut CalendarEvent) {
- self.mark_attendees(&mut event.attendees);
- event.viewer_can = ViewerCapabilities::for_event(event, self);
+ /// Mark the actor's attendee rows on the copy of an event synced through
+ /// `link_id` and resolve what the actor may do with it.
+ pub fn mark_event(&self, event: &mut CalendarEvent, link_id: Uuid) {
+ self.mark_attendees(&mut event.attendees, link_id);
+ event.viewer_can = ViewerCapabilities::for_event(event, self.inbox(link_id));
}
/// Iterate the normalized addresses.
pub fn iter(&self) -> impl Iterator<Item = &str> {
- self.emails.iter().map(String::as_str)
+ self.inboxes.iter().map(|inbox| inbox.email.as_str())
}
}
diff --git a/crates/calendar_events/src/domain/acting/test.rs b/crates/calendar_events/src/domain/acting/test.rs
index c5f09eb01c..c375e3789c 100644
--- a/crates/calendar_events/src/domain/acting/test.rs
+++ b/crates/calendar_events/src/domain/acting/test.rs
@@ -13,6 +13,14 @@ fn attendee(email: &str, is_self: bool) -> CalendarAttendee {
}
}
+fn inbox(link_id: u128, email: &str) -> OwnedInbox {
+ OwnedInbox {
+ link_id: Uuid::from_u128(link_id),
+ email: email.to_string(),
+ provider: CalendarProvider::Google,
+ }
+}
+
#[test]
fn from_owned_empty_is_none() {
assert!(ActorInboxes::from_owned(Vec::new()).is_none());
@@ -20,7 +28,7 @@ fn from_owned_empty_is_none() {
#[test]
fn from_owned_does_not_add_addresses_that_were_not_supplied() {
- let actor = ActorInboxes::from_owned(vec!["[email protected]".to_string()])
+ let actor = ActorInboxes::from_owned(vec![inbox(1, "[email protected]")])
.expect("owned addresses remain after normalize");
assert!(actor.matches("[email protected]"));
assert!(!actor.matches("[email protected]"));
@@ -29,9 +37,9 @@ fn from_owned_does_not_add_addresses_that_were_not_supplied() {
#[test]
fn actor_inboxes_dedupe_and_match_case_insensitively() {
let actor = ActorInboxes::from_owned(vec![
- "[email protected]".to_string(),
- "[email protected]".to_string(),
- "[email protected]".to_string(),
+ inbox(1, "[email protected]"),
+ inbox(1, "[email protected]"),
+ inbox(1, "[email protected]"),
])
.expect("owned addresses remain after normalize");
assert!(actor.matches("[email protected]"));
@@ -39,14 +47,31 @@ fn actor_inboxes_dedupe_and_match_case_insensitively() {
}
#[test]
-fn mark_attendees_marks_owned_rows_and_clears_others() {
- let actor = ActorInboxes::from_owned(vec!["[email protected]".to_string()])
- .expect("owned addresses remain after normalize");
+fn mark_attendees_marks_only_the_copys_inbox() {
+ let actor = ActorInboxes::from_owned(vec![
+ inbox(1, "[email protected]"),
+ inbox(2, "[email protected]"),
+ ])
+ .expect("owned addresses remain after normalize");
let mut attendees = vec![
attendee("[email protected]", true),
attendee("[email protected]", false),
+ attendee("[email protected]", true),
];
- actor.mark_attendees(&mut attendees);
- assert!(!attendees[0].is_self);
+ actor.mark_attendees(&mut attendees, Uuid::from_u128(1));
+ assert!(
+ !attendees[0].is_self,
+ "another owned inbox is not this copy's"
+ );
assert!(attendees[1].is_self);
+ assert!(!attendees[2].is_self);
+}
+
+#[test]
+fn a_copy_of_an_inbox_the_actor_does_not_own_marks_nobody() {
+ let actor = ActorInboxes::from_owned(vec![inbox(1, "[email protected]")])
+ .expect("owned addresses remain after normalize");
+ let mut attendees = vec![attendee("[email protected]", true)];
+ actor.mark_attendees(&mut attendees, Uuid::from_u128(9));
+ assert!(!attendees[0].is_self);
}
diff --git a/crates/calendar_events/src/domain/capabilities.rs b/crates/calendar_events/src/domain/capabilities.rs
index 277d06697d..30c36d3778 100644
--- a/crates/calendar_events/src/domain/capabilities.rs
+++ b/crates/calendar_events/src/domain/capabilities.rs
@@ -1,8 +1,10 @@
-//! What a viewer may do with an event, following Google's guest permissions.
+//! What a viewer may do with an event, following the organizer's guest
+//! permissions and what the provider of the viewer's copy allows.
use serde::{Deserialize, Serialize};
-use super::models::{ActorInboxes, CalendarAttendee, CalendarEvent, EventStatus};
+use super::acting::OwnedInbox;
+use super::models::{CalendarAttendee, CalendarEvent, CalendarProvider, EventStatus};
/// The switches an organizer sets on an event to bound what its guests may
/// do. Google omits a switch from the payload while it holds its default.
@@ -86,20 +88,29 @@ impl ViewerCapabilities {
*self == Self::NONE
}
- /// Resolve what `actor` may do with `event`.
+ /// Resolve what the owner of `inbox`, the inbox this copy of `event`
+ /// syncs through, may do with it.
///
/// A read-only or cancelled event allows nothing. The organizer may do
/// everything, and so may anyone on a writable event without attendees,
- /// which is treated as the actor's own. A guest's rights follow the
- /// event's [`GuestPolicy`]: modify allows everything except changing the
- /// policy, invite allows adding guests, and every guest may answer. A
- /// guest may change the guest list only while it is visible: Google takes
- /// guest additions as a whole new list, and a guest's copy of a hidden
- /// list holds only themselves and the organizer.
- /// Anyone else, including a teammate or channel member looking at someone
- /// else's projection, may do nothing. Answering always needs the actor's
- /// own attendee row, since that is the row the answer is written to.
- pub fn for_event(event: &CalendarEvent, actor: &ActorInboxes) -> Self {
+ /// which is treated as the actor's own. A guest of a Google copy follows
+ /// the event's [`GuestPolicy`]: modify allows everything except changing
+ /// the policy, invite allows adding guests, and every guest may answer.
+ /// A guest may change the guest list only while it is visible: Google
+ /// takes guest additions as a whole new list, and a guest's copy of a
+ /// hidden list holds only themselves and the organizer. Outlook gives
+ /// attendees no way to change the organizer's meeting, so a guest of an
+ /// Outlook copy may only answer.
+ ///
+ /// Only the copy's own inbox counts: another of the actor's inboxes
+ /// organizing or attending the event makes them nothing on this copy,
+ /// which is written through this inbox's grant. `None` is an actor who
+ /// does not own the copy's inbox, such as a delegate, or a teammate or
+ /// channel member looking at someone else's projection; they may do
+ /// nothing beyond the event-without-attendees rule. Answering always
+ /// needs the inbox's own attendee row, since that is the row the answer
+ /// is written to.
+ pub fn for_event(event: &CalendarEvent, inbox: Option<&OwnedInbox>) -> Self {
if event.status == EventStatus::Cancelled {
return Self::NONE;
}
@@ -110,27 +121,31 @@ impl ViewerCapabilities {
attendees: &event.attendees,
guest_policy: event.guest_policy,
},
- actor,
+ inbox,
)
}
- /// Resolve what `actor` may do with a live copy of an event; see
- /// [`Self::for_event`].
- pub fn for_access(access: EventAccess<'_>, actor: &ActorInboxes) -> Self {
+ /// Resolve what the owner of `inbox` may do with a live copy of an
+ /// event; see [`Self::for_event`].
+ pub fn for_access(access: EventAccess<'_>, inbox: Option<&OwnedInbox>) -> Self {
if access.is_read_only {
return Self::NONE;
}
- let is_guest = access
- .attendees
- .iter()
- .any(|attendee| actor.matches(&attendee.email));
- let is_organizer = access
- .organizer_email
- .is_some_and(|email| actor.matches(email))
- || access
+ let is_guest = inbox.is_some_and(|inbox| {
+ access
.attendees
.iter()
- .any(|attendee| attendee.is_organizer && actor.matches(&attendee.email));
+ .any(|attendee| inbox.matches(&attendee.email))
+ });
+ let is_organizer = inbox.is_some_and(|inbox| {
+ access
+ .organizer_email
+ .is_some_and(|email| inbox.matches(email))
+ || access
+ .attendees
+ .iter()
+ .any(|attendee| attendee.is_organizer && inbox.matches(&attendee.email))
+ });
if is_organizer || access.attendees.is_empty() {
return Self {
edit_details: true,
@@ -140,17 +155,26 @@ impl ViewerCapabilities {
rsvp: is_guest,
};
}
- if !is_guest {
- return Self::NONE;
+ match inbox {
+ Some(inbox) if is_guest => Self::for_guest(inbox.provider, access.guest_policy),
+ _ => Self::NONE,
}
- let policy = access.guest_policy;
- Self {
- edit_details: policy.can_modify,
- invite_guests: policy.can_see_other_guests
- && (policy.can_modify || policy.can_invite_others),
- remove_guests: policy.can_see_other_guests && policy.can_modify,
- set_guest_policy: false,
- rsvp: true,
+ }
+
+ fn for_guest(provider: CalendarProvider, policy: GuestPolicy) -> Self {
+ match provider {
+ CalendarProvider::Google => Self {
+ edit_details: policy.can_modify,
+ invite_guests: policy.can_see_other_guests
+ && (policy.can_modify || policy.can_invite_others),
+ remove_guests: policy.can_see_other_guests && policy.can_modify,
+ set_guest_policy: false,
+ rsvp: true,
+ },
+ CalendarProvider::Outlook => Self {
+ rsvp: true,
+ ..Self::NONE
+ },
}
}
}
diff --git a/crates/calendar_events/src/domain/capabilities/test.rs b/crates/calendar_events/src/domain/capabilities/test.rs
index a3f5562b12..b9edd9227d 100644
--- a/crates/calendar_events/src/domain/capabilities/test.rs
+++ b/crates/calendar_events/src/domain/capabilities/test.rs
@@ -3,13 +3,21 @@ use uuid::Uuid;
use super::*;
use crate::domain::models::{
- AttendeeResponseStatus, CalendarAttendee, EventReminders, EventTime, EventTransparency,
- EventType, EventVisibility,
+ ActorInboxes, AttendeeResponseStatus, CalendarAttendee, EventReminders, EventTime,
+ EventTransparency, EventType, EventVisibility,
};
const ORGANIZER: &str = "[email protected]";
const GUEST: &str = "[email protected]";
+fn google(email: &str) -> OwnedInbox {
+ OwnedInbox {
+ link_id: Uuid::from_u128(1),
+ email: email.to_string(),
+ provider: CalendarProvider::Google,
+ }
+}
+
fn attendee(email: &str, is_organizer: bool) -> CalendarAttendee {
CalendarAttendee {
email: email.to_string(),
@@ -82,10 +90,8 @@ const LOCKED_DOWN: GuestPolicy = GuestPolicy {
#[test]
fn the_organizer_may_do_everything() {
- let capabilities = ViewerCapabilities::for_event(
- &meeting(LOCKED_DOWN),
- &ActorInboxes::sole("[email protected]"),
- );
+ let capabilities =
+ ViewerCapabilities::for_event(&meeting(LOCKED_DOWN), Some(&google("[email protected]")));
assert_eq!(capabilities, EVERYTHING);
}
@@ -95,7 +101,7 @@ fn an_organizer_attendee_row_counts_without_the_organizer_email() {
let mut event = meeting(LOCKED_DOWN);
event.organizer_email = None;
- let capabilities = ViewerCapabilities::for_event(&event, &ActorInboxes::sole(ORGANIZER));
+ let capabilities = ViewerCapabilities::for_event(&event, Some(&google(ORGANIZER)));
assert_eq!(capabilities, EVERYTHING);
}
@@ -104,7 +110,7 @@ fn an_organizer_attendee_row_counts_without_the_organizer_email() {
fn an_organizer_without_an_attendee_row_cannot_answer() {
let event = event(vec![attendee(GUEST, false)], LOCKED_DOWN);
- let capabilities = ViewerCapabilities::for_event(&event, &ActorInboxes::sole(ORGANIZER));
+ let capabilities = ViewerCapabilities::for_event(&event, Some(&google(ORGANIZER)));
assert_eq!(
capabilities,
@@ -119,7 +125,7 @@ fn an_organizer_without_an_attendee_row_cannot_answer() {
fn a_writable_event_without_attendees_is_the_actors_own() {
let event = event(Vec::new(), LOCKED_DOWN);
- let capabilities = ViewerCapabilities::for_event(&event, &ActorInboxes::sole(GUEST));
+ let capabilities = ViewerCapabilities::for_event(&event, Some(&google(GUEST)));
assert_eq!(
capabilities,
@@ -138,7 +144,7 @@ fn a_guest_who_may_modify_may_do_everything_but_set_the_policy() {
can_see_other_guests: true,
};
- let capabilities = ViewerCapabilities::for_event(&meeting(policy), &ActorInboxes::sole(GUEST));
+ let capabilities = ViewerCapabilities::for_event(&meeting(policy), Some(&google(GUEST)));
assert_eq!(
capabilities,
@@ -152,7 +158,7 @@ fn a_guest_who_may_modify_may_do_everything_but_set_the_policy() {
#[test]
fn a_guest_who_may_invite_may_add_guests_and_answer() {
let capabilities =
- ViewerCapabilities::for_event(&meeting(GuestPolicy::default()), &ActorInboxes::sole(GUEST));
+ ViewerCapabilities::for_event(&meeting(GuestPolicy::default()), Some(&google(GUEST)));
assert_eq!(
capabilities,
@@ -172,7 +178,7 @@ fn a_guest_cannot_change_a_hidden_guest_list_even_with_permission() {
can_invite_others: true,
can_see_other_guests: false,
}),
- &ActorInboxes::sole(GUEST),
+ Some(&google(GUEST)),
);
assert_eq!(
@@ -189,8 +195,7 @@ fn a_guest_cannot_change_a_hidden_guest_list_even_with_permission() {
#[test]
fn a_guest_without_permissions_may_only_answer() {
- let capabilities =
- ViewerCapabilities::for_event(&meeting(LOCKED_DOWN), &ActorInboxes::sole(GUEST));
+ let capabilities = ViewerCapabilities::for_event(&meeting(LOCKED_DOWN), Some(&google(GUEST)));
assert_eq!(
capabilities,
@@ -206,8 +211,8 @@ fn a_read_only_event_allows_nothing_even_to_its_organizer() {
let mut event = meeting(GuestPolicy::default());
event.is_read_only = true;
- assert!(ViewerCapabilities::for_event(&event, &ActorInboxes::sole(ORGANIZER)).is_none());
- assert!(ViewerCapabilities::for_event(&event, &ActorInboxes::sole(GUEST)).is_none());
+ assert!(ViewerCapabilities::for_event(&event, Some(&google(ORGANIZER))).is_none());
+ assert!(ViewerCapabilities::for_event(&event, Some(&google(GUEST))).is_none());
}
#[test]
@@ -215,8 +220,8 @@ fn a_cancelled_event_allows_nothing() {
let mut event = meeting(GuestPolicy::default());
event.status = EventStatus::Cancelled;
- assert!(ViewerCapabilities::for_event(&event, &ActorInboxes::sole(ORGANIZER)).is_none());
- assert!(ViewerCapabilities::for_event(&event, &ActorInboxes::sole(GUEST)).is_none());
+ assert!(ViewerCapabilities::for_event(&event, Some(&google(ORGANIZER))).is_none());
+ assert!(ViewerCapabilities::for_event(&event, Some(&google(GUEST))).is_none());
}
#[test]
@@ -227,8 +232,145 @@ fn someone_neither_organizing_nor_invited_may_do_nothing() {
can_invite_others: true,
can_see_other_guests: true,
}),
- &ActorInboxes::sole("[email protected]"),
+ Some(&google("[email protected]")),
);
assert!(capabilities.is_none());
}
+
+#[test]
+fn a_delegate_may_do_nothing_with_a_meeting_on_the_inbox_they_were_granted() {
+ let capabilities = ViewerCapabilities::for_event(&meeting(GuestPolicy::default()), None);
+
+ assert!(capabilities.is_none());
+}
+
+#[test]
+fn a_delegate_may_change_a_writable_event_without_attendees() {
+ let capabilities = ViewerCapabilities::for_event(&event(Vec::new(), LOCKED_DOWN), None);
+
+ assert_eq!(
+ capabilities,
+ ViewerCapabilities {
+ rsvp: false,
+ ..EVERYTHING
+ }
+ );
+}
+
+const ORGANIZER_LINK: Uuid = Uuid::from_u128(11);
+const GUEST_LINK: Uuid = Uuid::from_u128(12);
+const OUTLOOK_LINK: Uuid = Uuid::from_u128(13);
+const OUTLOOK: &str = "[email protected]";
+
+/// Jacob, who connected the organizer's Google inbox, his own Google inbox,
+/// and an Outlook inbox.
+fn three_inboxes() -> ActorInboxes {
+ ActorInboxes::from_owned(vec![
+ OwnedInbox {
+ link_id: ORGANIZER_LINK,
+ email: ORGANIZER.to_string(),
+ provider: CalendarProvider::Google,
+ },
+ OwnedInbox {
+ link_id: GUEST_LINK,
+ email: GUEST.to_string(),
+ provider: CalendarProvider::Google,
+ },
+ OwnedInbox {
+ link_id: OUTLOOK_LINK,
+ email: OUTLOOK.to_string(),
+ provider: CalendarProvider::Outlook,
+ },
+ ])
+ .expect("the actor owns inboxes")
+}
+
+/// Olivia's meeting with both of Jacob's other inboxes invited.
+fn meeting_with_every_inbox(guest_policy: GuestPolicy) -> CalendarEvent {
+ event(
+ vec![
+ attendee(ORGANIZER, true),
+ attendee(GUEST, false),
+ attendee(OUTLOOK, false),
+ ],
+ guest_policy,
+ )
+}
+
+#[test]
+fn the_organizers_google_copy_may_do_everything() {
+ let mut copy = meeting_with_every_inbox(LOCKED_DOWN);
+
+ three_inboxes().mark_event(&mut copy, ORGANIZER_LINK);
+
+ assert_eq!(copy.viewer_can, EVERYTHING);
+ let own_rows: Vec<&str> = copy
+ .attendees
+ .iter()
+ .filter(|attendee| attendee.is_self)
+ .map(|attendee| attendee.email.as_str())
+ .collect();
+ assert_eq!(own_rows, [ORGANIZER]);
+}
+
+#[test]
+fn a_google_guest_copy_follows_the_policy_although_another_inbox_organizes() {
+ let mut copy = meeting_with_every_inbox(NO_INVITES);
+
+ three_inboxes().mark_event(&mut copy, GUEST_LINK);
+
+ assert_eq!(
+ copy.viewer_can,
+ ViewerCapabilities {
+ rsvp: true,
+ ..ViewerCapabilities::NONE
+ },
+ "the copy is written through the guest's grant, so the organizing inbox lends it nothing"
+ );
+ let own_rows: Vec<&str> = copy
+ .attendees
+ .iter()
+ .filter(|attendee| attendee.is_self)
+ .map(|attendee| attendee.email.as_str())
+ .collect();
+ assert_eq!(own_rows, [GUEST]);
+}
+
+#[test]
+fn an_outlook_guest_copy_of_a_google_meeting_may_only_answer() {
+ let mut copy = meeting_with_every_inbox(GuestPolicy {
+ can_modify: true,
+ can_invite_others: true,
+ can_see_other_guests: true,
+ });
+
+ three_inboxes().mark_event(&mut copy, OUTLOOK_LINK);
+
+ assert_eq!(
+ copy.viewer_can,
+ ViewerCapabilities {
+ rsvp: true,
+ ..ViewerCapabilities::NONE
+ }
+ );
+}
+
+#[test]
+fn an_outlook_organizer_copy_may_do_everything() {
+ let mut copy = event(
+ vec![attendee(OUTLOOK, true), attendee(GUEST, false)],
+ GuestPolicy::default(),
+ );
+ copy.organizer_email = Some(OUTLOOK.to_string());
+
+ three_inboxes().mark_event(&mut copy, OUTLOOK_LINK);
+
+ assert_eq!(copy.viewer_can, EVERYTHING);
+}
+
+const NO_INVITES: GuestPolicy = GuestPolicy {
+ can_modify: false,
+ can_invite_others: false,
+ can_see_other_guests: true,
+};
diff --git a/crates/calendar_events/src/domain/changes.rs b/crates/calendar_events/src/domain/changes.rs
index de44913600..0fbbf5a149 100644
--- a/crates/calendar_events/src/domain/changes.rs
+++ b/crates/calendar_events/src/domain/changes.rs
@@ -17,7 +17,8 @@ use rootcause::Report;
use uuid::Uuid;
use super::models::{
- ActorInboxes, CalendarEvent, CalendarOccurrence, OccurrenceException, VisibleCalendar,
+ ActorInboxes, CalendarEvent, CalendarOccurrence, OccurrenceException, OwnedInbox,
+ VisibleCalendar,
};
#[cfg(test)]
@@ -207,11 +208,11 @@ pub trait CalendarChangeRepository: Send + Sync + 'static {
calendar_ids: &[Uuid],
) -> impl Future<Output = Result<Vec<VisibleCalendar>, Report>> + Send;
- /// Addresses of every connected inbox the viewer owns.
- fn owned_inbox_emails(
+ /// Every connected inbox the viewer owns.
+ fn owned_inboxes(
&self,
viewer: &str,
- ) -> impl Future<Output = Result<Vec<String>, Report>> + Send;
+ ) -> impl Future<Output = Result<Vec<OwnedInbox>, Report>> + Send;
}
/// Persistence port for change-log retention.
@@ -346,8 +347,7 @@ impl<R: CalendarChangeRepository> CalendarChangeService<R> {
CalendarChangeOp::DeleteCalendar(id) => page.deleted_calendar_ids.push(id),
}
}
- if let Some(viewer) =
- ActorInboxes::from_owned(self.repository.owned_inbox_emails(viewer).await?)
+ if let Some(viewer) = ActorInboxes::from_owned(self.repository.owned_inboxes(viewer).await?)
{
for change in &mut page.events {
mark_viewer(&viewer, change);
@@ -373,8 +373,7 @@ impl<R: CalendarChangeRepository> CalendarChangeService<R> {
else {
return Ok(None);
};
- if let Some(viewer) =
- ActorInboxes::from_owned(self.repository.owned_inbox_emails(viewer).await?)
+ if let Some(viewer) = ActorInboxes::from_owned(self.repository.owned_inboxes(viewer).await?)
{
mark_viewer(&viewer, &mut change);
}
@@ -383,10 +382,10 @@ impl<R: CalendarChangeRepository> CalendarChangeService<R> {
}
fn mark_viewer(viewer: &ActorInboxes, change: &mut CalendarEventChange) {
- viewer.mark_event(&mut change.event);
+ viewer.mark_event(&mut change.event, change.link_id);
for instance in &mut change.occurrences {
if let Some(attendees) = &mut instance.exception.attendees {
- viewer.mark_attendees(attendees);
+ viewer.mark_attendees(attendees, change.link_id);
}
}
}
diff --git a/crates/calendar_events/src/domain/changes/test.rs b/crates/calendar_events/src/domain/changes/test.rs
index 00ff8b464c..a44d79a7b4 100644
--- a/crates/calendar_events/src/domain/changes/test.rs
+++ b/crates/calendar_events/src/domain/changes/test.rs
@@ -19,7 +19,7 @@ struct FakeChanges {
events: HashMap<Uuid, CalendarEventChange>,
calendars: Vec<VisibleCalendar>,
occurrence_cap_events: Option<usize>,
- owned_inboxes: Vec<String>,
+ owned_inboxes: Vec<OwnedInbox>,
loads: Mutex<Vec<Vec<Uuid>>>,
}
@@ -91,7 +91,7 @@ impl CalendarChangeRepository for FakeChanges {
.collect())
}
- async fn owned_inbox_emails(&self, _viewer: &str) -> Result<Vec<String>, Report> {
+ async fn owned_inboxes(&self, _viewer: &str) -> Result<Vec<OwnedInbox>, Report> {
Ok(self.owned_inboxes.clone())
}
}
@@ -460,7 +460,11 @@ async fn attendee_self_flags_follow_the_viewers_inboxes() {
let service = CalendarChangeService::new(FakeChanges {
logs: vec![log(LINK_A, 0, vec![CalendarChangeOp::UpsertEvent(id(1))])],
events: HashMap::from([(id(1), change)]),
- owned_inboxes: vec!["[email protected]".to_owned()],
+ owned_inboxes: vec![OwnedInbox {
+ link_id: LINK_A,
+ email: "[email protected]".to_owned(),
+ provider: CalendarProvider::Google,
+ }],
..Default::default()
});
@@ -493,7 +497,11 @@ async fn nothing_is_hydrated_when_no_event_was_upserted() {
async fn one_event_is_read_with_the_viewers_attendee_flags() {
let service = CalendarChangeService::new(FakeChanges {
events: HashMap::from([(id(1), event_change(id(1), LINK_A, 2))]),
- owned_inboxes: vec!["[email protected]".to_owned()],
+ owned_inboxes: vec![OwnedInbox {
+ link_id: LINK_A,
+ email: "[email protected]".to_owned(),
+ provider: CalendarProvider::Google,
+ }],
..Default::default()
});
diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rs
index 2dec4f2faa..c38bcac2c3 100644
--- a/crates/calendar_events/src/domain/models.rs
+++ b/crates/calendar_events/src/domain/models.rs
@@ -6,7 +6,7 @@ use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-pub use super::acting::ActorInboxes;
+pub use super::acting::{ActorInboxes, OwnedInbox};
pub use super::capabilities::{GuestPolicy, ViewerCapabilities};
/// Read and write events on every calendar the user can access. Covers the
@@ -1387,6 +1387,14 @@ pub struct CalendarEventMutationTarget {
}
impl CalendarEventMutationTarget {
+ /// The actor's inbox the addressed copy syncs through: every write to the
+ /// copy goes out through its grant, so the actor organizes or attends the
+ /// copy only as this inbox. `None` when the actor does not own it, as for
+ /// a delegate.
+ pub fn copy_inbox(&self) -> Option<&OwnedInbox> {
+ self.actor.as_ref()?.inbox(self.email_link_id)
+ }
+
/// Provider identifier the mutation must address: the recurring master
/// when the stored source is an expanded instance acting as canonical.
pub fn master_provider_event_id(&self) -> &str {
diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rs
index 876d802fea..39370a2ae0 100644
--- a/crates/calendar_events/src/domain/mutations.rs
+++ b/crates/calendar_events/src/domain/mutations.rs
@@ -230,7 +230,7 @@ where
.await;
}
if let Some(viewer) = viewer {
- viewer.mark_event(&mut event);
+ viewer.mark_event(&mut event, email_link_id);
}
Ok(event)
}
@@ -338,9 +338,9 @@ where
patch.attendees = Some(attendees);
} else {
// A guest who may not remove guests only adds, through the
- // invite path, which keeps every guest Google already holds.
+ // invite path, which keeps every guest the provider holds.
let additions =
- invite::guest_list_additions(attendees, &stored, target.actor.as_ref())?;
+ invite::guest_list_additions(attendees, &stored, target.copy_inbox())?;
if !additions.is_empty() {
let invited = self
.invite_guests(
@@ -557,7 +557,7 @@ where
self.retire_gone_source(&target).await;
event.id = target.event_id;
if let Some(actor) = &target.actor {
- actor.mark_event(&mut event);
+ actor.mark_event(&mut event, target.email_link_id);
}
Ok(*event)
}
@@ -579,6 +579,7 @@ where
CalendarUpdateScope::All => "all",
CalendarUpdateScope::ThisEvent { .. } => "this_event",
},
+ provider = tracing::field::Empty,
outcome = tracing::field::Empty,
),
err
diff --git a/crates/calendar_events/src/domain/mutations/invite.rs b/crates/calendar_events/src/domain/mutations/invite.rs
index 18715d20b7..4ae9d360a9 100644
--- a/crates/calendar_events/src/domain/mutations/invite.rs
+++ b/crates/calendar_events/src/domain/mutations/invite.rs
@@ -1,9 +1,12 @@
//! Adding guests with a full attendee write, for organizers and for guests
-//! the organizer lets invite others while the guest list is visible.
+//! of a Google event the organizer lets invite others while the guest list
+//! is visible. The actor acts only as the inbox the addressed copy syncs
+//! through.
use std::collections::HashSet;
use super::*;
use crate::domain::capabilities::{EventAccess, GuestPolicy, ViewerCapabilities};
+use crate::domain::models::{CalendarProvider, OwnedInbox};
impl<R, G, T, B, N> CalendarMutationServiceImpl<R, G, T, B, N>
where
@@ -53,17 +56,29 @@ where
let target = self
.resolve_mutation_target(requester_id, event_id, calendar_id)
.await?;
+ tracing::Span::current().record(
+ "provider",
+ tracing::field::debug(target.token_identity.provider),
+ );
if target.is_read_only {
return Err(CalendarMutationError::ReadOnly);
}
self.require_provider_writes(target.token_identity.provider)?;
- let Some(actor) = target.actor.as_ref() else {
+ let Some(actor) = target
+ .actor
+ .as_ref()
+ .and_then(|actor| actor.through(target.email_link_id))
+ else {
return Err(CalendarMutationError::NotAttendee);
};
let stored = self.stored_attendees(event_id, &scope).await?;
let capabilities = copy_capabilities(&target, &stored);
if !capabilities.invite_guests {
- return Err(invite_refusal(capabilities, target.guest_policy));
+ return Err(invite_refusal(
+ capabilities,
+ target.guest_policy,
+ target.token_identity.provider,
+ ));
}
let guests = uninvited_guests(guests, &stored);
let access_token = self.fetch_token(&target.token_identity).await?;
@@ -73,7 +88,7 @@ where
&access_token,
&target.provider_target(OccurrenceRange::maintenance_horizon(Utc::now())),
target.master_provider_event_id(),
- actor,
+ &actor,
&guests,
&scope,
)
@@ -81,16 +96,16 @@ where
.map_err(provider_error)?;
match outcome {
ProviderInviteOutcome::Applied(upsert) => match &scope {
- CalendarUpdateScope::All => self.persist_echo(Some(actor), *upsert).await,
+ CalendarUpdateScope::All => self.persist_echo(Some(&actor), *upsert).await,
CalendarUpdateScope::ThisEvent { recurrence_id } => {
- self.persist_occurrence_echo(Some(actor), *upsert, recurrence_id)
+ self.persist_occurrence_echo(Some(&actor), *upsert, recurrence_id)
.await
}
},
ProviderInviteOutcome::OccurrenceGone(upsert) => {
// Nothing was written, but the provider's view of the series
// is fresher than whatever listed this occurrence.
- self.persist_echo(Some(actor), *upsert)
+ self.persist_echo(Some(&actor), *upsert)
.await
.inspect_err(|error| {
tracing::warn!(
@@ -157,37 +172,42 @@ where
}
/// Why an actor without `invite_guests` may not add guests. Every guest may
-/// answer, so a seat on the event shows as `rsvp`.
-fn invite_refusal(capabilities: ViewerCapabilities, policy: GuestPolicy) -> CalendarMutationError {
+/// answer, so a seat on the event shows as `rsvp`. Outlook lets only the
+/// organizer change a meeting, so its guests may never invite.
+fn invite_refusal(
+ capabilities: ViewerCapabilities,
+ policy: GuestPolicy,
+ provider: CalendarProvider,
+) -> CalendarMutationError {
if !capabilities.rsvp {
CalendarMutationError::NotAttendee
- } else if !(policy.can_modify || policy.can_invite_others) {
+ } else if provider == CalendarProvider::Outlook
+ || !(policy.can_modify || policy.can_invite_others)
+ {
CalendarMutationError::GuestsCannotInvite
} else {
CalendarMutationError::GuestListHidden
}
}
-/// What the actor may do with the addressed copy, judged against its stored
-/// guest list.
+/// What the actor may do with the addressed copy through its inbox, judged
+/// against its stored guest list.
pub(super) fn copy_capabilities(
target: &CalendarEventMutationTarget,
stored: &[CalendarAttendee],
) -> ViewerCapabilities {
- target
- .actor
- .as_ref()
- .map_or(ViewerCapabilities::NONE, |actor| {
- ViewerCapabilities::for_access(
- EventAccess {
- is_read_only: target.is_read_only,
- organizer_email: target.organizer_email.as_deref(),
- attendees: stored,
- guest_policy: target.guest_policy,
- },
- actor,
- )
- })
+ if target.actor.is_none() {
+ return ViewerCapabilities::NONE;
+ }
+ ViewerCapabilities::for_access(
+ EventAccess {
+ is_read_only: target.is_read_only,
+ organizer_email: target.organizer_email.as_deref(),
+ attendees: stored,
+ guest_policy: target.guest_policy,
+ },
+ target.copy_inbox(),
+ )
}
/// The requested guests not already on the stored list, each once.
@@ -207,14 +227,15 @@ fn uninvited_guests(
/// Split the guest list a caller without the right to remove guests
/// submitted into the guests it adds. Any stored guest missing from it is a
-/// removal and is refused. The actor's own row is exempt: the editor leaves
-/// the viewer out of the list it submits, and leaving an event is a decline,
-/// not an edit. A changed optional flag on an existing guest is a
-/// modification such a caller cannot make, so it is ignored.
+/// removal and is refused. The row of the copy's inbox, the actor's own, is
+/// exempt: the editor leaves the viewer out of the list it submits, and
+/// leaving an event is a decline, not an edit. A changed optional flag on an
+/// existing guest is a modification such a caller cannot make, so it is
+/// ignored.
pub(super) fn guest_list_additions(
submitted: Vec<CalendarAttendeeInput>,
stored: &[CalendarAttendee],
- actor: Option<&ActorInboxes>,
+ inbox: Option<&OwnedInbox>,
) -> Result<Vec<CalendarAttendeeInput>, CalendarMutationError> {
let submitted_emails: HashSet<String> = submitted
.iter()
@@ -222,7 +243,7 @@ pub(super) fn guest_list_additions(
.collect();
let removes_a_guest = stored.iter().any(|attendee| {
!submitted_emails.contains(&attendee.email.to_lowercase())
- && !actor.is_some_and(|actor| actor.matches(&attendee.email))
+ && !inbox.is_some_and(|inbox| inbox.matches(&attendee.email))
});
if removes_a_guest {
return Err(CalendarMutationError::InvalidInput(
diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rs
index 514a03db2e..d2acc0fd10 100644
--- a/crates/calendar_events/src/domain/mutations/test.rs
+++ b/crates/calendar_events/src/domain/mutations/test.rs
@@ -5,13 +5,26 @@ use crate::domain::models::{
CalendarLinkTokenIdentity, CalendarOccurrenceCursor, CalendarSyncStatus, CalendarWatchRelease,
ConferenceChange, DisconnectedCalendar, EventStart, EventStatus, EventTransparency, EventType,
EventVisibility, GoogleCalendarSyncSnapshot, GoogleWatchChannel, GuestPolicy,
- OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, ProviderCalendar, ProviderCalendarTarget,
- ProviderEventSource, StoredGoogleCalendar, ViewerCapabilities, VisibleCalendar,
+ OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, OwnedInbox, ProviderCalendar,
+ ProviderCalendarTarget, ProviderEventSource, StoredGoogleCalendar, ViewerCapabilities,
+ VisibleCalendar,
};
use crate::domain::ports::RetiredCalendarEvent;
use chrono::{Duration, TimeZone};
use std::sync::{Arc, Mutex};
+/// The inbox the fixture targets sync through: the link
+/// [`ActorInboxes::sole`] gives its inbox.
+const SELF_LINK: Uuid = Uuid::nil();
+
+fn owned(link_id: Uuid, email: &str) -> OwnedInbox {
+ OwnedInbox {
+ link_id,
+ email: email.to_string(),
+ provider: super::super::models::CalendarProvider::Google,
+ }
+}
+
fn token_identity() -> CalendarLinkTokenIdentity {
CalendarLinkTokenIdentity {
binding: None,
@@ -29,7 +42,7 @@ fn mutation_target(is_read_only: bool) -> CalendarEventMutationTarget {
provider_event_id: "instance-id".to_string(),
provider_recurring_event_id: Some("master-id".to_string()),
owner_id: "macro|[email protected]".to_string(),
- email_link_id: Uuid::now_v7(),
+ email_link_id: SELF_LINK,
account_id: Uuid::now_v7(),
calendar_id: Uuid::now_v7(),
provider_calendar_id: "primary".to_string(),
@@ -56,7 +69,7 @@ fn creation_target(is_read_only: bool) -> CalendarCreationTarget {
CalendarCreationTarget {
observed_access_role: Some(if is_read_only { "reader" } else { "owner" }.to_owned()),
owner_id: "macro|[email protected]".to_string(),
- email_link_id: Uuid::now_v7(),
+ email_link_id: SELF_LINK,
account_id: Uuid::now_v7(),
calendar_id: Uuid::now_v7(),
provider_calendar_id: "primary".to_string(),
@@ -426,10 +439,10 @@ impl CalendarRepository for FakeRepo {
Ok(None)
}
- async fn owned_inbox_emails(
+ async fn owned_inboxes(
&self,
_requester_id: &str,
- ) -> Result<Vec<String>, rootcause::Report> {
+ ) -> Result<Vec<OwnedInbox>, rootcause::Report> {
if self.fail_owned_inboxes {
return Err(rootcause::report!("owned inboxes unavailable"));
}
@@ -473,6 +486,7 @@ struct FakeProvider {
created_drafts: Arc<Mutex<Vec<CalendarEventDraft>>>,
updated_patches: Arc<Mutex<Vec<CalendarEventPatch>>>,
invited_guests: Arc<Mutex<Vec<Vec<CalendarAttendeeInput>>>>,
+ invited_as: Arc<Mutex<Vec<Vec<String>>>>,
}
impl FakeProvider {
@@ -487,11 +501,13 @@ impl FakeProvider {
created_drafts: Arc::new(Mutex::new(Vec::new())),
updated_patches: Arc::new(Mutex::new(Vec::new())),
invited_guests: Arc::new(Mutex::new(Vec::new())),
+ invited_as: Arc::new(Mutex::new(Vec::new())),
}
}
- fn echo(&self, owner_id: &str) -> CalendarEventUpsert {
- let mut upsert = echo_upsert(owner_id);
+ fn echo(&self, target: &ProviderCalendarTarget) -> CalendarEventUpsert {
+ let mut upsert = echo_upsert(&target.owner_id);
+ upsert.source.details_mut().email_link_id = target.email_link_id;
upsert.event.attendees = self.echo_attendees.clone();
upsert.overrides = self.echo_overrides.clone();
if let Some(time) = &self.echo_time {
@@ -525,7 +541,7 @@ impl CalendarMutationProvider for FakeProvider {
if let Some(error) = self.fail() {
return Err(error);
}
- Ok(self.echo(&target.owner_id))
+ Ok(self.echo(target))
}
async fn update_event(
@@ -546,7 +562,7 @@ impl CalendarMutationProvider for FakeProvider {
if matches!(self.behavior, FakeProviderBehavior::Gone) {
return Ok(None);
}
- Ok(Some(self.echo(&target.owner_id)))
+ Ok(Some(self.echo(target)))
}
async fn update_event_instance(
@@ -567,9 +583,9 @@ impl CalendarMutationProvider for FakeProvider {
Ok(match self.behavior {
FakeProviderBehavior::Gone => ProviderInstanceUpdateOutcome::SeriesGone,
FakeProviderBehavior::OccurrenceGone => {
- ProviderInstanceUpdateOutcome::OccurrenceGone(Box::new(self.echo(&target.owner_id)))
+ ProviderInstanceUpdateOutcome::OccurrenceGone(Box::new(self.echo(target)))
}
- _ => ProviderInstanceUpdateOutcome::Applied(Box::new(self.echo(&target.owner_id))),
+ _ => ProviderInstanceUpdateOutcome::Applied(Box::new(self.echo(target))),
})
}
@@ -594,10 +610,14 @@ impl CalendarMutationProvider for FakeProvider {
_access_token: &str,
target: &ProviderCalendarTarget,
master_provider_event_id: &str,
- _actor: &ActorInboxes,
+ actor: &ActorInboxes,
guests: &[CalendarAttendeeInput],
scope: &CalendarUpdateScope,
) -> Result<ProviderInviteOutcome, CalendarProviderError> {
+ self.invited_as
+ .lock()
+ .unwrap()
+ .push(actor.iter().map(str::to_string).collect());
let scope = match scope {
CalendarUpdateScope::All => "all".to_string(),
CalendarUpdateScope::ThisEvent { recurrence_id } => format!("this:{recurrence_id}"),
@@ -613,14 +633,14 @@ impl CalendarMutationProvider for FakeProvider {
Ok(match self.behavior {
FakeProviderBehavior::Gone => ProviderInviteOutcome::Gone,
FakeProviderBehavior::OccurrenceGone => {
- ProviderInviteOutcome::OccurrenceGone(Box::new(self.echo(&target.owner_id)))
+ ProviderInviteOutcome::OccurrenceGone(Box::new(self.echo(target)))
}
FakeProviderBehavior::NotAttendee => ProviderInviteOutcome::NotAttendee,
FakeProviderBehavior::Forbidden(policy) => ProviderInviteOutcome::Forbidden(policy),
FakeProviderBehavior::GuestListHidden(policy) => {
ProviderInviteOutcome::GuestListHidden(policy)
}
- _ => ProviderInviteOutcome::Applied(Box::new(self.echo(&target.owner_id))),
+ _ => ProviderInviteOutcome::Applied(Box::new(self.echo(target))),
})
}
@@ -656,7 +676,7 @@ impl CalendarMutationProvider for FakeProvider {
}
Ok(match self.behavior {
FakeProviderBehavior::Gone => ProviderSeriesMutationOutcome::Gone,
- _ => ProviderSeriesMutationOutcome::Applied(Box::new(self.echo(&target.owner_id))),
+ _ => ProviderSeriesMutationOutcome::Applied(Box::new(self.echo(target))),
})
}
@@ -675,7 +695,7 @@ impl CalendarMutationProvider for FakeProvider {
}
Ok(match self.behavior {
FakeProviderBehavior::Gone => ProviderSeriesMutationOutcome::SeriesDeleted,
- _ => ProviderSeriesMutationOutcome::Applied(Box::new(self.echo(&target.owner_id))),
+ _ => ProviderSeriesMutationOutcome::Applied(Box::new(self.echo(target))),
})
}
@@ -706,7 +726,7 @@ impl CalendarMutationProvider for FakeProvider {
Ok(match self.behavior {
FakeProviderBehavior::Gone => ProviderRsvpOutcome::Gone,
FakeProviderBehavior::NotAttendee => ProviderRsvpOutcome::NotAttendee,
- _ => ProviderRsvpOutcome::Applied(Box::new(self.echo(&target.owner_id))),
+ _ => ProviderRsvpOutcome::Applied(Box::new(self.echo(target))),
})
}
}
@@ -925,7 +945,7 @@ async fn create_does_not_write_when_inbox_lookup_fails() {
}
#[tokio::test]
-async fn create_returned_echo_marks_requester_inboxes_as_self() {
+async fn create_returned_echo_marks_the_copys_inbox_as_self() {
let mut provider = FakeProvider::new(FakeProviderBehavior::Echo);
provider.echo_attendees = vec![
echo_attendee("[email protected]", true),
@@ -934,7 +954,7 @@ async fn create_returned_echo_marks_requester_inboxes_as_self() {
let created = service(
FakeRepo {
creation_target: Some(CalendarCreationTarget {
- actor: ActorInboxes::from_owned(vec!["[email protected]".to_string()]),
+ actor: ActorInboxes::from_owned(vec![owned(SELF_LINK, "[email protected]")]),
..creation_target(false)
}),
..FakeRepo::default()
@@ -2201,7 +2221,7 @@ async fn rsvp_addresses_the_requester_inbox_not_the_source_calendar() {
let provider = FakeProvider::new(FakeProviderBehavior::Echo);
let emails = provider.rsvp_self_emails.clone();
let mut target = mutation_target(false);
- target.actor = ActorInboxes::from_owned(vec!["[email protected]".to_string()]);
+ target.actor = ActorInboxes::from_owned(vec![owned(Uuid::now_v7(), "[email protected]")]);
service(
FakeRepo {
mutation_target: Some(target),
@@ -2238,7 +2258,7 @@ async fn rsvp_through_a_delegated_inbox_never_hands_the_subject_email_to_the_pro
email_address: "[email protected]".to_string(),
provider: super::super::models::CalendarProvider::Google,
};
- target.actor = ActorInboxes::from_owned(vec!["[email protected]".to_string()]);
+ target.actor = ActorInboxes::from_owned(vec![owned(Uuid::now_v7(), "[email protected]")]);
service(
FakeRepo {
mutation_target: Some(target),
@@ -2702,8 +2722,8 @@ async fn rsvp_uses_only_the_selected_owned_address_for_both_scopes() {
let emails = provider.rsvp_self_emails.clone();
let mut target = mutation_target(false);
target.actor = ActorInboxes::from_owned(vec![
- "[email protected]".into(),
- "[email protected]".into(),
+ owned(SELF_LINK, "[email protected]"),
+ owned(Uuid::now_v7(), "[email protected]"),
]);
service(
FakeRepo {
diff --git a/crates/calendar_events/src/domain/mutations/test/invite.rs b/crates/calendar_events/src/domain/mutations/test/invite.rs
index b4731799f0..b0767f165b 100644
--- a/crates/calendar_events/src/domain/mutations/test/invite.rs
+++ b/crates/calendar_events/src/domain/mutations/test/invite.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::domain::models::CalendarProvider;
const ORGANIZER: &str = "[email protected]";
@@ -372,3 +373,119 @@ async fn an_occurrence_with_its_own_guest_list_is_judged_by_that_list() {
"re-inviting Bo to this occurrence is an addition, not a no-op"
);
}
+
+const OTHER_LINK: Uuid = Uuid::from_u128(0x0e);
+
+#[tokio::test]
+async fn a_guest_copy_is_judged_as_its_own_inbox_while_another_inbox_organizes() {
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let calls = provider.calls.clone();
+ let mut repo = guest_repo(NO_INVITES);
+ // The actor also connected Olivia's inbox, which organizes the meeting.
+ repo.mutation_target.as_mut().unwrap().actor = ActorInboxes::from_owned(vec![
+ owned(SELF_LINK, "[email protected]"),
+ owned(OTHER_LINK, ORGANIZER),
+ ]);
+
+ let error = service(repo, provider, FakeTokens::ok())
+ .invite_guests(
+ "macro|user",
+ Uuid::now_v7(),
+ None,
+ vec![guest("[email protected]")],
+ CalendarUpdateScope::All,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, CalendarMutationError::GuestsCannotInvite));
+ assert!(
+ calls.lock().unwrap().is_empty(),
+ "this copy is written through the guest's grant, which the organizer's inbox does not lend rights to"
+ );
+}
+
+#[tokio::test]
+async fn the_provider_hears_only_the_copys_inbox() {
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let invited_as = provider.invited_as.clone();
+ let mut repo = guest_repo(GuestPolicy::default());
+ repo.mutation_target.as_mut().unwrap().actor = ActorInboxes::from_owned(vec![
+ owned(SELF_LINK, "[email protected]"),
+ owned(OTHER_LINK, ORGANIZER),
+ ]);
+
+ service(repo, provider, FakeTokens::ok())
+ .invite_guests(
+ "macro|user",
+ Uuid::now_v7(),
+ None,
+ vec![guest("[email protected]")],
+ CalendarUpdateScope::All,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ invited_as.lock().unwrap().as_slice(),
+ [vec!["[email protected]".to_string()]]
+ );
+}
+
+fn outlook_repo(organizer: &str) -> FakeRepo {
+ let mut repo = guest_repo(GuestPolicy::default());
+ let target = repo.mutation_target.as_mut().unwrap();
+ target.organizer_email = Some(organizer.to_string());
+ target.token_identity.provider = CalendarProvider::Outlook;
+ target.actor = ActorInboxes::from_owned(vec![OwnedInbox {
+ link_id: SELF_LINK,
+ email: "[email protected]".to_string(),
+ provider: CalendarProvider::Outlook,
+ }]);
+ repo
+}
+
+#[tokio::test]
+async fn an_outlook_guest_is_refused_before_the_provider() {
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let calls = provider.calls.clone();
+
+ let error = service(outlook_repo(ORGANIZER), provider, FakeTokens::ok())
+ .invite_guests(
+ "macro|user",
+ Uuid::now_v7(),
+ None,
+ vec![guest("[email protected]")],
+ CalendarUpdateScope::All,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(
+ matches!(error, CalendarMutationError::GuestsCannotInvite),
+ "{error:?}"
+ );
+ assert!(calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn an_outlook_organizer_adds_guests_through_the_provider() {
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let invited = provider.invited_guests.clone();
+
+ service(outlook_repo("[email protected]"), provider, FakeTokens::ok())
+ .invite_guests(
+ "macro|user",
+ Uuid::now_v7(),
+ None,
+ vec![guest("[email protected]")],
+ CalendarUpdateScope::All,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ invited.lock().unwrap().as_slice(),
+ [vec![guest("[email protected]")]]
+ );
+}
diff --git a/crates/calendar_events/src/domain/mutations/test/replacement.rs b/crates/calendar_events/src/domain/mutations/test/replacement.rs
index 2f1113964b..a7039094b6 100644
--- a/crates/calendar_events/src/domain/mutations/test/replacement.rs
+++ b/crates/calendar_events/src/domain/mutations/test/replacement.rs
@@ -186,7 +186,7 @@ impl CalendarReplacementProvider for FakeProvider {
target: &ProviderCalendarTarget,
_: &str,
) -> Result<Option<CalendarEventUpsert>, CalendarProviderError> {
- Ok(Some(self.echo(&target.owner_id)))
+ Ok(Some(self.echo(target)))
}
}
fn fixture(behavior: FakeProviderBehavior) -> (TestMutationService, FakeRepo, FakeProvider, Uuid) {
diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rs
index cab32c814b..d8552c47c9 100644
--- a/crates/calendar_events/src/domain/ports.rs
+++ b/crates/calendar_events/src/domain/ports.rs
@@ -20,8 +20,8 @@ use super::models::{
CalendarReminderDispatchMessage, CalendarReminderFiring, CalendarReminderSweepSummary,
CalendarSyncStatus, DisconnectedCalendar, DueCalendarReminder, GoogleCalendarSyncSnapshot,
GoogleEventSyncBatch, GoogleScopeSet, GoogleSyncPlan, GoogleWatchChannel, GoogleWatchConfig,
- GuestPolicy, OccurrenceListing, OccurrenceRange, ProviderCalendar, ProviderCalendarTarget,
- StoredGoogleCalendar, TeamOutOfOffice, VisibleCalendar,
+ GuestPolicy, OccurrenceListing, OccurrenceRange, OwnedInbox, ProviderCalendar,
+ ProviderCalendarTarget, StoredGoogleCalendar, TeamOutOfOffice, VisibleCalendar,
};
/// Classification supplied by provider adapters to backfill policy.
@@ -233,12 +233,15 @@ pub trait CalendarMutationProvider: Send + Sync + 'static {
/// already invited with their answer, notify the new guests, and refresh
/// the series.
///
- /// The provider event is read first: a vanished event surfaces as
+ /// `actor` is the inbox the addressed copy syncs through. The provider
+ /// event is read first: a vanished event surfaces as
/// [`ProviderInviteOutcome::Gone`], an actor who neither organizes nor
/// attends it as [`ProviderInviteOutcome::NotAttendee`], and a guest the
/// event's live policy refuses as [`ProviderInviteOutcome::Forbidden`] or
- /// [`ProviderInviteOutcome::GuestListHidden`]. Guests already on the
- /// event are dropped, and nothing is written when none remain.
+ /// [`ProviderInviteOutcome::GuestListHidden`]. Outlook takes guests only
+ /// from the organizer, so it refuses anyone else with a permanent
+ /// provider error. Guests already on the event are dropped, and nothing
+ /// is written when none remain.
fn add_attendees(
&self,
access_token: &str,
@@ -713,13 +716,13 @@ pub trait CalendarRepository: Send + Sync + 'static {
requester_id: &str,
) -> impl Future<Output = Result<Option<String>, Report>> + Send;
- /// Addresses of every connected inbox the requester owns
+ /// Every connected inbox the requester owns
/// (`email_links.macro_id = requester`). Raw and unnormalized;
/// [`ActorInboxes::from_owned`] is the single normalization point.
- fn owned_inbox_emails(
+ fn owned_inboxes(
&self,
requester_id: &str,
- ) -> impl Future<Output = Result<Vec<String>, Report>> + Send;
+ ) -> impl Future<Output = Result<Vec<OwnedInbox>, Report>> + Send;
/// Retire a Google source the provider confirmed deleted (a recurring
/// master also retires its expanded instances), restoring the best
@@ -924,8 +927,10 @@ pub enum CalendarMutationError {
/// The connected account is not an attendee of the event.
#[error("the connected account is not an attendee of this event")]
NotAttendee,
- /// The organizer does not let guests invite others.
- #[error("the organizer doesn't let guests invite others")]
+ /// Only the organizer may invite guests: the organizer does not let
+ /// guests invite others, or the event is an Outlook meeting, which
+ /// gives its attendees no way to change it.
+ #[error("only the organizer can invite guests to this event")]
GuestsCannotInvite,
/// The organizer hides the guest list, so a guest's copy cannot hold the
/// whole list a guest addition must write.
diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rs
index abf7be030c..0c8d9c6e30 100644
--- a/crates/calendar_events/src/domain/service.rs
+++ b/crates/calendar_events/src/domain/service.rs
@@ -107,12 +107,12 @@ where
.list_occurrences(requester_id, range, cursor, limit)
.await?;
if let Some(viewer) =
- ActorInboxes::from_owned(self.repository.owned_inbox_emails(requester_id).await?)
+ ActorInboxes::from_owned(self.repository.owned_inboxes(requester_id).await?)
{
for listing in &mut rows {
- viewer.mark_event(&mut listing.event);
+ viewer.mark_event(&mut listing.event, listing.link_id);
if let Some(attendees) = &mut listing.exception.attendees {
- viewer.mark_attendees(attendees);
+ viewer.mark_attendees(attendees, listing.link_id);
}
}
}
diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rs
index 93f31e28e6..90db45c6a7 100644
--- a/crates/calendar_events/src/domain/service/test.rs
+++ b/crates/calendar_events/src/domain/service/test.rs
@@ -171,7 +171,10 @@ impl CalendarRepository for FakeRepo {
Ok(None)
}
- async fn owned_inbox_emails(&self, _requester_id: &str) -> Result<Vec<String>, Report> {
+ async fn owned_inboxes(
+ &self,
+ _requester_id: &str,
+ ) -> Result<Vec<crate::domain::models::OwnedInbox>, Report> {
Ok(Vec::new())
}
diff --git a/crates/calendar_events/src/inbound/mutation_router.rs b/crates/calendar_events/src/inbound/mutation_router.rs
index ba14593646..ae795cfaad 100644
--- a/crates/calendar_events/src/inbound/mutation_router.rs
+++ b/crates/calendar_events/src/inbound/mutation_router.rs
@@ -354,7 +354,8 @@ pub enum CalendarMutationErrorCode {
NoWritableCalendar,
/// The connected account is not an attendee of the event.
NotAttendee,
- /// The organizer does not let guests invite others.
+ /// Only the organizer may invite guests: the organizer does not let
+ /// guests invite others, or the event is an Outlook meeting.
GuestsCannotInvite,
/// The organizer hides the guest list, so a guest cannot add guests.
GuestListHidden,
@@ -430,7 +431,7 @@ impl From<CalendarMutationError> for CalendarMutationApiError {
CalendarMutationError::GuestsCannotInvite => (
StatusCode::FORBIDDEN,
CalendarMutationErrorCode::GuestsCannotInvite,
- "The organizer doesn't let guests invite others.".to_string(),
+ "Only the organizer can invite guests to this event.".to_string(),
),
CalendarMutationError::GuestListHidden => (
StatusCode::FORBIDDEN,
@@ -813,7 +814,7 @@ where
(status = 200, description = "The updated calendar event", body = CalendarEvent),
(status = 400, description = "Invalid guests or scope", body = CalendarMutationApiError),
(status = 401, description = "Authentication required"),
- (status = 403, description = "Calendar is read-only, the organizer doesn't let guests invite others, or the calendar needs reauthorization", body = CalendarMutationApiError),
+ (status = 403, description = "Calendar is read-only, only the organizer can invite guests, or the calendar needs reauthorization", body = CalendarMutationApiError),
(status = 404, description = "Event or occurrence not found", body = CalendarMutationApiError),
(status = 409, description = "The connected account neither organizes nor attends the event", body = CalendarMutationApiError),
(status = 503, description = "Transient provider failure", body = CalendarMutationApiError),
diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rs
index f3156855f8..da5df3ab63 100644
--- a/crates/calendar_events/src/inbound/toolset.rs
+++ b/crates/calendar_events/src/inbound/toolset.rs
@@ -477,8 +477,9 @@ fn mutation_tool_error(action: &str, error: CalendarMutationError) -> ToolCallEr
"The user's connected account is not an attendee of this event.".to_string()
}
CalendarMutationError::GuestsCannotInvite => {
- "The organizer doesn't let guests invite others, so the user cannot add guests to \
- this event. Suggest asking the organizer to add them."
+ "Only the organizer can invite guests to this event: the organizer doesn't let \
+ guests invite others, or it is an Outlook meeting, where guests cannot add anyone. \
+ Suggest asking the organizer to add them."
.to_string()
}
CalendarMutationError::GuestListHidden => {
diff --git a/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs
index 40cc47f0ea..9a9ed82af2 100644
--- a/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs
+++ b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs
@@ -103,7 +103,7 @@ true (the user organizes the event, or the organizer lets guests modify it). Whe
false, the list may only grow: pass the current attendees plus the additions; the additions \
are invited without touching anyone else, and dropping any guest fails. Adding guests then \
needs `viewerCan.inviteGuests`; otherwise the organizer doesn't let guests invite others \
-or hides the guest list. \
+or hides the guest list, or the event is an Outlook meeting the user doesn't organize. \
An empty string for `description` or `location` clears it. Fails on events from calendars \
the user cannot edit.\n\
\n\
diff --git a/crates/calendar_events/src/outbound/google/test.rs b/crates/calendar_events/src/outbound/google/test.rs
index f5ca4acab5..ffd13d8272 100644
--- a/crates/calendar_events/src/outbound/google/test.rs
+++ b/crates/calendar_events/src/outbound/google/test.rs
@@ -1112,8 +1112,7 @@ fn rsvp_patches_the_actor_row_not_the_google_self_flag() {
google_attendee("[email protected]", true),
google_attendee("[email protected]", false),
];
- let actor = ActorInboxes::from_owned(vec!["[email protected]".to_string()])
- .expect("owned addresses remain after normalize");
+ let actor = ActorInboxes::sole("[email protected]");
let found = find_actor_attendee(&attendees, &actor);
assert_eq!(
found.and_then(|attendee| attendee.email.as_deref()),
@@ -1124,8 +1123,7 @@ fn rsvp_patches_the_actor_row_not_the_google_self_flag() {
#[test]
fn rsvp_does_not_patch_another_attendee_when_the_requester_is_absent() {
let attendees = vec![google_attendee("[email protected]", true)];
- let actor = ActorInboxes::from_owned(vec!["[email protected]".to_string()])
- .expect("owned addresses remain after normalize");
+ let actor = ActorInboxes::sole("[email protected]");
assert!(find_actor_attendee(&attendees, &actor).is_none());
}
diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rs
index a04d571706..e53bd2c750 100644
--- a/crates/calendar_events/src/outbound/pg.rs
+++ b/crates/calendar_events/src/outbound/pg.rs
@@ -35,9 +35,9 @@ use crate::domain::{
DisconnectedCalendar, DueCalendarReminder, EventReminderOverride, EventReminders,
EventStart, EventStatus, EventTime, EventTransparency, EventType, EventVisibility,
GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleScopeSet, GoogleWatchChannel,
- GuestPolicy, OccurrenceException, OccurrenceListing, OccurrenceRange, ProviderCalendar,
- StoredGoogleCalendar, TeamOutOfOffice, ViewerCapabilities, VisibleCalendar,
- is_system_calendar,
+ GuestPolicy, OccurrenceException, OccurrenceListing, OccurrenceRange, OwnedInbox,
+ ProviderCalendar, StoredGoogleCalendar, TeamOutOfOffice, ViewerCapabilities,
+ VisibleCalendar, is_system_calendar,
},
ports::{
CalendarBackfillRepository, CalendarEventChange, CalendarEventWrite,
@@ -2110,7 +2110,7 @@ impl CalendarRepository for PgCalendarRepository {
let Some(row) = row else {
return Ok(None);
};
- let actor = ActorInboxes::from_owned(self.owned_inbox_emails(requester_id).await?);
+ let actor = ActorInboxes::from_owned(self.owned_inboxes(requester_id).await?);
let token_identity = CalendarLinkTokenIdentity {
binding: Some(CalendarGrantBinding {
link_id: row.email_link_id,
@@ -2261,7 +2261,7 @@ impl CalendarRepository for PgCalendarRepository {
let Some(row) = row else {
return Ok(None);
};
- let actor = ActorInboxes::from_owned(self.owned_inbox_emails(requester_id).await?);
+ let actor = ActorInboxes::from_owned(self.owned_inboxes(requester_id).await?);
let token_identity = CalendarLinkTokenIdentity {
binding: Some(CalendarGrantBinding {
link_id: row.email_link_id,
@@ -2374,10 +2374,13 @@ impl CalendarRepository for PgCalendarRepository {
}
#[tracing::instrument(skip(self, requester_id), err)]
- async fn owned_inbox_emails(&self, requester_id: &str) -> Result<Vec<String>, Report> {
- sqlx::query_scalar!(
+ async fn owned_inboxes(&self, requester_id: &str) -> Result<Vec<OwnedInbox>, Report> {
+ sqlx::query!(
r#"
- SELECT email_address::text AS "email_address!"
+ SELECT
+ id AS link_id,
+ email_address::text AS "email_address!",
+ provider::text AS "provider!"
FROM email_links
WHERE macro_id = $1
"#,
@@ -2385,7 +2388,17 @@ impl CalendarRepository for PgCalendarRepository {
)
.fetch_all(&self.pool)
.await
- .map_err(report)
+ .map_err(report)?
+ .into_iter()
+ .map(|row| {
+ Ok(OwnedInbox {
+ link_id: row.link_id,
+ email: row.email_address,
+ provider: CalendarProvider::from_link(&row.provider)
+ .ok_or_else(|| rootcause::report!("unsupported calendar provider"))?,
+ })
+ })
+ .collect()
}
#[tracing::instrument(skip(self), err)]
diff --git a/crates/calendar_events/src/outbound/pg/changes.rs b/crates/calendar_events/src/outbound/pg/changes.rs
index 1e00fdb2d0..c08f1c21f0 100644
--- a/crates/calendar_events/src/outbound/pg/changes.rs
+++ b/crates/calendar_events/src/outbound/pg/changes.rs
@@ -16,7 +16,7 @@ use crate::domain::{
CalendarChange, CalendarChangeRepository, CalendarEventChange, CalendarLinkLog,
CalendarLinkWatermark, CalendarWatermark, EventChangeLoad, EventOccurrence,
},
- models::VisibleCalendar,
+ models::{OwnedInbox, VisibleCalendar},
ports::CalendarRepository,
};
@@ -355,7 +355,7 @@ impl CalendarChangeRepository for PgCalendarRepository {
Ok(rows.into_iter().map(visible_calendar).collect())
}
- async fn owned_inbox_emails(&self, viewer: &str) -> Result<Vec<String>, Report> {
- CalendarRepository::owned_inbox_emails(self, viewer).await
+ async fn owned_inboxes(&self, viewer: &str) -> Result<Vec<OwnedInbox>, Report> {
+ CalendarRepository::owned_inboxes(self, viewer).await
}
}
diff --git a/crates/email_api_client/src/outbound/outlook/calendar.rs b/crates/email_api_client/src/outbound/outlook/calendar.rs
index a12eb42969..4d86373123 100644
--- a/crates/email_api_client/src/outbound/outlook/calendar.rs
+++ b/crates/email_api_client/src/outbound/outlook/calendar.rs
@@ -1,6 +1,7 @@
//! Microsoft Graph calendar adapter using the same transport and admission as mail.
mod automatic_decline;
mod conference_body;
+mod invite;
mod normalize;
mod recurrence;
mod replacement;
@@ -889,17 +890,22 @@ impl CalendarMutationProvider for OutlookApiClientRepository {
}
async fn add_attendees(
&self,
- _token: &str,
- _target: &ProviderCalendarTarget,
- _master: &str,
+ token: &str,
+ target: &ProviderCalendarTarget,
+ id: &str,
_actor: &ActorInboxes,
- _guests: &[CalendarAttendeeInput],
- _scope: &CalendarUpdateScope,
+ guests: &[CalendarAttendeeInput],
+ scope: &CalendarUpdateScope,
) -> Result<ProviderInviteOutcome, CalendarProviderError> {
- Err(unsupported(
- "Microsoft Graph has no partial attendee write; an Outlook organizer adds guests by \
- updating the attendee list",
- ))
+ self.calendar_scope(target)?
+ .add_calendar_guests(
+ &AccessToken::new(token.to_owned()),
+ target,
+ id,
+ guests,
+ scope,
+ )
+ .await
}
async fn stop_watch_channel(
&self,
diff --git a/crates/email_api_client/src/outbound/outlook/calendar/invite.rs b/crates/email_api_client/src/outbound/outlook/calendar/invite.rs
new file mode 100644
index 0000000000..7aae7ec83b
--- /dev/null
+++ b/crates/email_api_client/src/outbound/outlook/calendar/invite.rs
@@ -0,0 +1,79 @@
+//! Adding guests to an Outlook meeting the mailbox organizes.
+use super::{OutlookApiClientRepository, attendee_body, unsupported};
+use crate::domain::models::AccessToken;
+use calendar_events::domain::{models::*, ports::*};
+use serde_json::{Value, json};
+use std::collections::HashSet;
+
+impl OutlookApiClientRepository {
+ /// Add guests to the meeting `id`, or to one of its occurrences, and
+ /// refresh the series.
+ ///
+ /// The mailbox is the inbox the addressed copy syncs through. Graph has no
+ /// attendee-side write, so only the organizer's copy can take new guests;
+ /// anyone else is refused with a permanent error.
+ pub(super) async fn add_calendar_guests(
+ &self,
+ token: &AccessToken,
+ target: &ProviderCalendarTarget,
+ id: &str,
+ guests: &[CalendarAttendeeInput],
+ scope: &CalendarUpdateScope,
+ ) -> Result<ProviderInviteOutcome, CalendarProviderError> {
+ let Some(master) = self.calendar_event(token, target, id).await? else {
+ return Ok(ProviderInviteOutcome::Gone);
+ };
+ if master["isOrganizer"].as_bool() != Some(true) {
+ return Err(unsupported(
+ "Outlook lets only the organizer add guests to a meeting",
+ ));
+ }
+ let event = match scope {
+ CalendarUpdateScope::All => Some(master),
+ CalendarUpdateScope::ThisEvent { recurrence_id } => {
+ self.instance_at(token, target, &master, recurrence_id)
+ .await?
+ }
+ };
+ if let Some(event) = &event
+ && let Some(body) = attendees_body(event, guests)
+ {
+ self.patch_calendar_event(token, event, &body).await?;
+ }
+ Ok(match self.calendar_refresh(token, target, id).await? {
+ Some(echo) if event.is_some() => ProviderInviteOutcome::Applied(Box::new(echo)),
+ Some(echo) => ProviderInviteOutcome::OccurrenceGone(Box::new(echo)),
+ None => ProviderInviteOutcome::Gone,
+ })
+ }
+}
+
+/// Body adding guests to an Outlook event while keeping everyone already on
+/// it, or `None` when every guest already is.
+///
+/// Microsoft Graph has no partial attendee write: `attendees` replaces the
+/// whole collection. So the patch carries every attendee Graph returned,
+/// unchanged so their answers survive, then the new guests. A patch that
+/// holds only `attendees` sends the meeting request to the changed
+/// attendees alone, so only the new guests hear about it.
+pub(super) fn attendees_body(current: &Value, guests: &[CalendarAttendeeInput]) -> Option<Value> {
+ let mut attendees = current["attendees"].as_array().cloned().unwrap_or_default();
+ let mut listed: HashSet<String> = attendees
+ .iter()
+ .chain([&current["organizer"]])
+ .filter_map(|attendee| attendee["emailAddress"]["address"].as_str())
+ .map(str::to_ascii_lowercase)
+ .collect();
+ let additions: Vec<CalendarAttendeeInput> = guests
+ .iter()
+ .filter(|guest| listed.insert(guest.email.trim().to_ascii_lowercase()))
+ .cloned()
+ .collect();
+ if additions.is_empty() {
+ return None;
+ }
+ if let Value::Array(new) = attendee_body(&additions) {
+ attendees.extend(new);
+ }
+ Some(json!({ "attendees": attendees }))
+}
diff --git a/crates/email_api_client/src/outbound/outlook/calendar/test.rs b/crates/email_api_client/src/outbound/outlook/calendar/test.rs
index 27d90681bb..2ef3433c75 100644
--- a/crates/email_api_client/src/outbound/outlook/calendar/test.rs
+++ b/crates/email_api_client/src/outbound/outlook/calendar/test.rs
@@ -669,3 +669,139 @@ fn occurrence_preferences_override_or_inherit_series_reminders_and_decline_polic
Some(&policy)
);
}
+
+fn guest(email: &str) -> CalendarAttendeeInput {
+ CalendarAttendeeInput {
+ email: email.into(),
+ is_optional: false,
+ response_status: None,
+ }
+}
+
+/// A meeting with Ada, who accepted, on the mailbox's calendar.
+fn meeting(id: &str, is_organizer: bool) -> Value {
+ let mut meeting = event(id);
+ meeting["isOrganizer"] = json!(is_organizer);
+ meeting["organizer"] = json!({"emailAddress":{"address":"[email protected]","name":"Olivia"}});
+ meeting["attendees"] = json!([{
+ "emailAddress":{"address":"[email protected]","name":"Ada"},
+ "type":"required",
+ "status":{"response":"accepted","time":"2026-10-20T10:00:00Z"}
+ }]);
+ meeting
+}
+
+#[tokio::test]
+async fn an_organizer_adds_guests_by_writing_the_whole_attendee_list() {
+ let (server, api) = setup().await;
+ Mock::given(method("GET"))
+ .and(path("/v1.0/me/calendars/calendar/events/event"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(meeting("event", true)))
+ .mount(&server)
+ .await;
+ Mock::given(method("PATCH"))
+ .and(path("/v1.0/me/events/event"))
+ .and(header("if-match", "W/\"1\""))
+ .respond_with(ResponseTemplate::new(200).set_body_json(meeting("event", true)))
+ .expect(1)
+ .mount(&server)
+ .await;
+
+ let outcome = api
+ .add_calendar_guests(
+ &AccessToken::new("token".to_owned()),
+ &target(),
+ "event",
+ &[
+ guest("[email protected]"),
+ guest("[email protected]"),
+ guest("[email protected]"),
+ ],
+ &CalendarUpdateScope::All,
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(outcome, ProviderInviteOutcome::Applied(_)));
+ let requests = server.received_requests().await.unwrap();
+ let patch = requests
+ .iter()
+ .find(|r| r.method.as_str() == "PATCH")
+ .unwrap();
+ assert_eq!(
+ serde_json::from_slice::<Value>(&patch.body).unwrap(),
+ json!({"attendees":[
+ {
+ "emailAddress":{"address":"[email protected]","name":"Ada"},
+ "type":"required",
+ "status":{"response":"accepted","time":"2026-10-20T10:00:00Z"}
+ },
+ {"emailAddress":{"address":"[email protected]"},"type":"required"}
+ ]}),
+ "Ada keeps her answer, and only Bo is new"
+ );
+}
+
+#[tokio::test]
+async fn an_attendee_cannot_add_guests_to_an_outlook_meeting() {
+ let (server, api) = setup().await;
+ Mock::given(method("GET"))
+ .and(path("/v1.0/me/calendars/calendar/events/event"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(meeting("event", false)))
+ .mount(&server)
+ .await;
+
+ let result = api
+ .add_calendar_guests(
+ &AccessToken::new("token".to_owned()),
+ &target(),
+ "event",
+ &[guest("[email protected]")],
+ &CalendarUpdateScope::All,
+ )
+ .await;
+
+ assert!(
+ matches!(&result, Err(error) if error.kind() == CalendarProviderErrorKind::Permanent),
+ "the refusal stays a typed provider error"
+ );
+ assert!(
+ server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .all(|r| r.method.as_str() == "GET")
+ );
+}
+
+#[tokio::test]
+async fn guests_already_on_the_meeting_write_nothing() {
+ let (server, api) = setup().await;
+ Mock::given(method("GET"))
+ .and(path("/v1.0/me/calendars/calendar/events/event"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(meeting("event", true)))
+ .mount(&server)
+ .await;
+
+ let outcome = api
+ .add_calendar_guests(
+ &AccessToken::new("token".to_owned()),
+ &target(),
+ "event",
+ &[guest("[email protected]")],
+ &CalendarUpdateScope::All,
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(outcome, ProviderInviteOutcome::Applied(_)));
+ assert!(
+ server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .all(|r| r.method.as_str() == "GET")
+ );
+}
diff --git a/crates/graphql_calendar/src/mutation.rs b/crates/graphql_calendar/src/mutation.rs
index e86691bcf0..7af43b4756 100644
--- a/crates/graphql_calendar/src/mutation.rs
+++ b/crates/graphql_calendar/src/mutation.rs
@@ -225,7 +225,7 @@ pub(crate) fn mutation_error(error: CalendarMutationError) -> async_graphql::Err
),
CalendarMutationError::GuestsCannotInvite => (
"guests_cannot_invite",
- "The organizer doesn't let guests invite others.".into(),
+ "Only the organizer can invite guests to this event.".into(),
),
CalendarMutationError::GuestListHidden => (
"guest_list_hidden",
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
index f73883ad48..2ce30f796f 100644
--- a/docs/agent-guide/calendar.md
+++ b/docs/agent-guide/calendar.md
@@ -452,6 +452,12 @@ read-only pill that explains why. A guest on an event whose organizer hides the
may not invite either (`viewerCan.inviteGuests` is false; the route answers 403
`guest_list_hidden`). To check the refusal state without a Google account, answer
`POST /events/{id}/guests` with HTTP 403 and code `guests_cannot_invite`.
+An event that reached several connected inboxes shows one chip per inbox (overlapping;
+tell them apart by calendar color), and each copy answers only for its own inbox: a
+guest copy stays a guest copy, marked `(you)` on that inbox's row alone, even when
+another connected inbox organizes the event. An Outlook guest copy never offers `Add
+guests` (Outlook lets only the organizer change a meeting) and shows the same
+explanation; an Outlook organizer adds guests like a Google one.
The details header's `Download .ics` icon button, beside `Copy event`, saves the event as an
iCalendar file named after its title, so it can be passed on or added to another calendar. The
file holds the series (its repeat rule, in the event's original time zone), title, description
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/InviteCalendarEventGuestsErrors.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/InviteCalendarEventGuestsErrors.md
index 5f365919e9..6ab44af7d4 100644
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/InviteCalendarEventGuestsErrors.md
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/InviteCalendarEventGuestsErrors.md
@@ -8,7 +8,7 @@
| ------ | ------ | ------ |
| <a id="property-400"></a> `400` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | Invalid guests or scope |
| <a id="property-401"></a> `401` | `unknown` | Authentication required |
-| <a id="property-403"></a> `403` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | Calendar is read-only, the organizer doesn't let guests invite others, or the calendar needs reauthorization |
+| <a id="property-403"></a> `403` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | Calendar is read-only, only the organizer can invite guests, or the calendar needs reauthorization |
| <a id="property-404"></a> `404` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | Event or occurrence not found |
| <a id="property-409"></a> `409` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | The connected account neither organizes nor attends the event |
| <a id="property-503"></a> `503` | [`CalendarMutationApiError`](CalendarMutationApiError.md) | Transient provider failure |
diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.ts
index 5b45579d16..f84f7c1fdb 100644
--- a/packages/sdk/generated/calendar/types.gen.ts
+++ b/packages/sdk/generated/calendar/types.gen.ts
@@ -1106,7 +1106,7 @@ export type InviteCalendarEventGuestsErrors = {
*/
401: unknown;
/**
- * Calendar is read-only, the organizer doesn't let guests invite others, or the calendar needs reauthorization
+ * Calendar is read-only, only the organizer can invite guests, or the calendar needs reauthorization
*/
403: CalendarMutationApiError;
/**
diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.json
index 72cae5ccce..ae100ebc0f 100644
--- a/packages/sdk/specs/calendar.json
+++ b/packages/sdk/specs/calendar.json
@@ -404,7 +404,7 @@
"description": "Authentication required"
},
"403": {
- "description": "Calendar is read-only, the organizer doesn't let guests invite others, or the calendar needs reauthorization",
+ "description": "Calendar is read-only, only the organizer can invite guests, or the calendar needs reauthorization",
"content": {
"application/json": {
"schema": {