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): rsvp as actor instead of calendar owner (#5892)

teo4676fdd68313
diff --git a/.sqlx/query-4bc9261979cc9d7efd0c2caa7a09cbb0748f5386de237ae04df72e73e594995a.json b/.sqlx/query-4bc9261979cc9d7efd0c2caa7a09cbb0748f5386de237ae04df72e73e594995a.json
new file mode 100644
index 0000000000..950101d168
--- /dev/null
+++ b/.sqlx/query-4bc9261979cc9d7efd0c2caa7a09cbb0748f5386de237ae04df72e73e594995a.json
@@ -0,0 +1,22 @@
+{
+ "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/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendee.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendee.ts
index fc5e5fd442..d1170137d4 100644
--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendee.ts
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/calendarAttendee.ts
@@ -23,7 +23,10 @@ export interface CalendarAttendee {
isOptional: boolean;
/** Whether this attendee is the organizer. */
isOrganizer: boolean;
- /** Whether this attendee represents the connected account. */
+ /** Whether this attendee is one of the viewing requester's inboxes.
+
+Outbound projections use the requester's owned inboxes only.
+Persisted rows keep the provider's flag, which reminder decline reads. */
isSelf: boolean;
/** RSVP state. */
responseStatus: AttendeeResponseStatus;
diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.json
index 5a9fd8eb68..fb9ed1df53 100644
--- a/apps/web/src/lib/service-clients/service-email/openapi.json
+++ b/apps/web/src/lib/service-clients/service-email/openapi.json
@@ -4475,7 +4475,7 @@
},
"isSelf": {
"type": "boolean",
- "description": "Whether this attendee represents the connected account."
+ "description": "Whether this attendee is one of the viewing requester's inboxes.\n\nOutbound projections use the requester's owned inboxes only.\nPersisted rows keep the provider's flag, which reminder decline reads."
},
"responseStatus": {
"$ref": "#/components/schemas/AttendeeResponseStatus",
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendee.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendee.ts
index 473617618f..44ada89450 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendee.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendee.ts
@@ -23,7 +23,10 @@ export interface CalendarAttendee {
isOptional: boolean;
/** Whether this attendee is the organizer. */
isOrganizer: boolean;
- /** Whether this attendee represents the connected account. */
+ /** Whether this attendee is one of the viewing requester's inboxes.
+
+Outbound projections use the requester's owned inboxes only.
+Persisted rows keep the provider's flag, which reminder decline reads. */
isSelf: boolean;
/** RSVP state. */
responseStatus: AttendeeResponseStatus;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index c2e36ce600..f5b4daacd0 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -806,7 +806,7 @@ export const listOccurrencesResponse = zod
isSelf: zod
.boolean()
.describe(
- 'Whether this attendee represents the connected account.'
+ "Whether this attendee is one of the viewing requester's inboxes.\n\nOutbound projections use the requester's owned inboxes only.\nPersisted rows keep the provider's flag, which reminder decline reads."
),
responseStatus: zod
.enum([
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 7caac442b7..517ea9743b 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -13271,7 +13271,7 @@
},
"isSelf": {
"type": "boolean",
- "description": "Whether this attendee represents the connected account."
+ "description": "Whether this attendee is one of the viewing requester's inboxes.\n\nOutbound projections use the requester's owned inboxes only.\nPersisted rows keep the provider's flag, which reminder decline reads."
},
"responseStatus": {
"$ref": "#/components/schemas/AttendeeResponseStatus",
diff --git a/crates/calendar_events/src/domain/acting.rs b/crates/calendar_events/src/domain/acting.rs
new file mode 100644
index 0000000000..105cc1db5f
--- /dev/null
+++ b/crates/calendar_events/src/domain/acting.rs
@@ -0,0 +1,67 @@
+//! The clicker's owned inboxes.
+
+use super::models::CalendarAttendee;
+
+/// The clicker's own connected-inbox addresses.
+///
+/// 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.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ActorInboxes {
+ emails: Vec<String>,
+}
+
+impl ActorInboxes {
+ /// Normalize the requester's owned inbox addresses.
+ ///
+ /// 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
+ .into_iter()
+ .map(|email| email.to_ascii_lowercase())
+ .filter(|email| !email.is_empty())
+ .collect();
+ emails.sort();
+ emails.dedup();
+ if emails.is_empty() {
+ None
+ } else {
+ Some(Self { emails })
+ }
+ }
+
+ /// A single-address actor for fixtures.
+ #[cfg(test)]
+ pub(crate) fn sole(email: impl Into<String>) -> Self {
+ Self {
+ emails: vec![email.into().to_ascii_lowercase()],
+ }
+ }
+
+ /// 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)
+ }
+
+ /// Set `is_self` on the actor's rows and clear it on every other row.
+ pub fn mark_attendees(&self, attendees: &mut [CalendarAttendee]) {
+ for attendee in attendees {
+ attendee.is_self = self.matches(&attendee.email);
+ }
+ }
+
+ /// Iterate the normalized addresses.
+ pub fn iter(&self) -> impl Iterator<Item = &str> {
+ self.emails.iter().map(String::as_str)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/calendar_events/src/domain/acting/test.rs b/crates/calendar_events/src/domain/acting/test.rs
new file mode 100644
index 0000000000..c5f09eb01c
--- /dev/null
+++ b/crates/calendar_events/src/domain/acting/test.rs
@@ -0,0 +1,52 @@
+use super::*;
+use crate::domain::models::{AttendeeResponseStatus, CalendarAttendee};
+
+fn attendee(email: &str, is_self: bool) -> CalendarAttendee {
+ CalendarAttendee {
+ email: email.to_string(),
+ display_name: None,
+ response_status: AttendeeResponseStatus::NeedsAction,
+ is_organizer: false,
+ is_optional: false,
+ is_self,
+ comment: None,
+ }
+}
+
+#[test]
+fn from_owned_empty_is_none() {
+ assert!(ActorInboxes::from_owned(Vec::new()).is_none());
+}
+
+#[test]
+fn from_owned_does_not_add_addresses_that_were_not_supplied() {
+ let actor = ActorInboxes::from_owned(vec!["[email protected]".to_string()])
+ .expect("owned addresses remain after normalize");
+ assert!(actor.matches("[email protected]"));
+ assert!(!actor.matches("[email protected]"));
+}
+
+#[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(),
+ ])
+ .expect("owned addresses remain after normalize");
+ assert!(actor.matches("[email protected]"));
+ assert_eq!(actor.iter().collect::<Vec<_>>(), ["[email protected]"]);
+}
+
+#[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");
+ let mut attendees = vec![
+ attendee("[email protected]", true),
+ attendee("[email protected]", false),
+ ];
+ actor.mark_attendees(&mut attendees);
+ assert!(!attendees[0].is_self);
+ assert!(attendees[1].is_self);
+}
diff --git a/crates/calendar_events/src/domain/mod.rs b/crates/calendar_events/src/domain/mod.rs
index 9be62db172..437827a4b5 100644
--- a/crates/calendar_events/src/domain/mod.rs
+++ b/crates/calendar_events/src/domain/mod.rs
@@ -1,5 +1,7 @@
//! Calendar domain layer.
+/// The clicker's owned inboxes.
+pub mod acting;
/// Kafka event models for the calendar topic.
pub mod events;
/// Domain models.
diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rs
index 0acf7f10f6..9c2051c19c 100644
--- a/crates/calendar_events/src/domain/models.rs
+++ b/crates/calendar_events/src/domain/models.rs
@@ -6,6 +6,8 @@ use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
+pub use super::acting::ActorInboxes;
+
/// Read and write events on every calendar the user can access. Covers the
/// event list, get, instances, insert, patch, and watch calls.
pub const GOOGLE_CALENDAR_EVENTS_SCOPE: &str = "https://www.googleapis.com/auth/calendar.events";
@@ -319,7 +321,10 @@ pub struct CalendarAttendee {
pub is_organizer: bool,
/// Whether attendance is optional.
pub is_optional: bool,
- /// Whether this attendee represents the connected account.
+ /// Whether this attendee is one of the viewing requester's inboxes.
+ ///
+ /// Outbound projections use the requester's owned inboxes only.
+ /// Persisted rows keep the provider's flag, which reminder decline reads.
pub is_self: bool,
/// Optional attendee comment.
pub comment: Option<String>,
@@ -899,8 +904,10 @@ pub struct CalendarEventMutationTarget {
pub calendar_id: Uuid,
/// Provider calendar identifier used in Google API paths.
pub provider_calendar_id: String,
- /// Token identity of the connected inbox.
+ /// Grant of the connected inbox this calendar belongs to.
pub token_identity: CalendarLinkTokenIdentity,
+ /// The clicker's owned inboxes. `None` when they own none.
+ pub actor: Option<ActorInboxes>,
}
impl CalendarEventMutationTarget {
@@ -964,8 +971,10 @@ pub struct CalendarCreationTarget {
pub provider_calendar_id: String,
/// Whether the provider role prohibits event creation.
pub is_read_only: bool,
- /// Token identity of the connected inbox.
+ /// Grant of the connected inbox this calendar belongs to.
pub token_identity: CalendarLinkTokenIdentity,
+ /// The clicker's owned inboxes. `None` when they own none.
+ pub actor: Option<ActorInboxes>,
}
impl CalendarCreationTarget {
diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rs
index 5f232c9b93..c70cd722f2 100644
--- a/crates/calendar_events/src/domain/mutations.rs
+++ b/crates/calendar_events/src/domain/mutations.rs
@@ -11,8 +11,8 @@ use uuid::Uuid;
use super::{
models::{
- AttendeeResponseStatus, CalendarAttendeeInput, CalendarEvent, CalendarEventDraft,
- CalendarEventMutationTarget, CalendarEventPatch, CalendarEventUpsert,
+ ActorInboxes, AttendeeResponseStatus, CalendarAttendeeInput, CalendarEvent,
+ CalendarEventDraft, CalendarEventMutationTarget, CalendarEventPatch, CalendarEventUpsert,
DisconnectedGoogleCalendar, EventReminders, EventTime, OccurrenceRange,
REMINDER_METHOD_EMAIL, REMINDER_METHOD_POPUP, REMINDER_MINUTES_MAX, REMINDER_OVERRIDES_MAX,
},
@@ -134,6 +134,7 @@ where
/// applied entity id.
async fn persist_echo(
&self,
+ viewer: Option<&ActorInboxes>,
upsert: CalendarEventUpsert,
) -> Result<CalendarEvent, CalendarMutationError> {
let mut event = upsert.event.clone();
@@ -144,6 +145,9 @@ where
.map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;
event.id = outcome.event_id;
self.publish_write_outcome(&outcome);
+ if let Some(viewer) = viewer {
+ viewer.mark_attendees(&mut event.attendees);
+ }
Ok(event)
}
}
@@ -188,7 +192,7 @@ where
)
.await
.map_err(provider_error)?;
- self.persist_echo(upsert).await
+ self.persist_echo(target.actor.as_ref(), upsert).await
}
#[tracing::instrument(skip(self, requester_id, patch), err)]
@@ -246,7 +250,7 @@ where
self.retire_gone_source(&target).await;
return Err(CalendarMutationError::NotFound);
};
- self.persist_echo(upsert).await
+ self.persist_echo(target.actor.as_ref(), upsert).await
}
CalendarUpdateScope::ThisEvent { recurrence_id } => {
let outcome = self
@@ -262,13 +266,13 @@ where
.map_err(provider_error)?;
match outcome {
GoogleInstanceUpdateOutcome::Applied(upsert) => {
- self.persist_echo(*upsert).await
+ self.persist_echo(target.actor.as_ref(), *upsert).await
}
GoogleInstanceUpdateOutcome::OccurrenceGone(upsert) => {
// Nothing was written, but the provider's view of the
// series is fresher than whatever listed this
// occurrence — persist it so the phantom disappears.
- self.persist_echo(*upsert)
+ self.persist_echo(target.actor.as_ref(), *upsert)
.await
.inspect_err(|error| {
tracing::warn!(
@@ -336,9 +340,10 @@ where
.map_err(provider_error)?,
};
match outcome {
- GoogleSeriesMutationOutcome::Applied(upsert) => {
- self.persist_echo(*upsert).await.map(|_| ())
- }
+ GoogleSeriesMutationOutcome::Applied(upsert) => self
+ .persist_echo(target.actor.as_ref(), *upsert)
+ .await
+ .map(|_| ()),
// Either the deletion removed the series or it was already
// gone; retiring the local source converges both.
GoogleSeriesMutationOutcome::SeriesDeleted | GoogleSeriesMutationOutcome::Gone => {
@@ -372,6 +377,9 @@ where
if target.is_read_only {
return Err(CalendarMutationError::ReadOnly);
}
+ let Some(actor) = target.actor.as_ref() else {
+ return Err(CalendarMutationError::NotAttendee);
+ };
let access_token = self.fetch_token(&target.token_identity).await?;
let outcome = self
.provider
@@ -379,14 +387,16 @@ where
&access_token,
&target.google_target(OccurrenceRange::maintenance_horizon(Utc::now())),
target.master_provider_event_id(),
- &target.token_identity.email_address,
+ actor,
response,
&scope,
)
.await
.map_err(provider_error)?;
match outcome {
- GoogleRsvpOutcome::Applied(upsert) => self.persist_echo(*upsert).await,
+ GoogleRsvpOutcome::Applied(upsert) => {
+ self.persist_echo(target.actor.as_ref(), *upsert).await
+ }
GoogleRsvpOutcome::NotAttendee => Err(CalendarMutationError::NotAttendee),
GoogleRsvpOutcome::Gone => {
self.retire_gone_source(&target).await;
diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rs
index 13fddf5e5a..d59c51aa37 100644
--- a/crates/calendar_events/src/domain/mutations/test.rs
+++ b/crates/calendar_events/src/domain/mutations/test.rs
@@ -1,11 +1,11 @@
use super::*;
use crate::domain::models::{
- AppliedGoogleGrant, CalendarAttendeeInput, CalendarBackfillJobKey, CalendarCreationTarget,
- CalendarEventSource, CalendarLinkTokenIdentity, CalendarOccurrence, CalendarOccurrenceCursor,
- CalendarSyncStatus, CalendarWatchRelease, ConferenceChange, DisconnectedGoogleCalendar,
- EventStatus, EventTransparency, EventVisibility, GoogleCalendarSyncSnapshot,
- GoogleCalendarTarget, GoogleEventSource, GoogleWatchChannel, ProviderCalendar,
- StoredGoogleCalendar,
+ ActorInboxes, AppliedGoogleGrant, CalendarAttendee, CalendarAttendeeInput,
+ CalendarBackfillJobKey, CalendarCreationTarget, CalendarEventSource, CalendarLinkTokenIdentity,
+ CalendarOccurrence, CalendarOccurrenceCursor, CalendarSyncStatus, CalendarWatchRelease,
+ ConferenceChange, DisconnectedGoogleCalendar, EventStatus, EventTransparency, EventVisibility,
+ GoogleCalendarSyncSnapshot, GoogleCalendarTarget, GoogleEventSource, GoogleWatchChannel,
+ ProviderCalendar, StoredGoogleCalendar, VisibleCalendar,
};
use crate::domain::ports::RetiredCalendarEvent;
use chrono::{Duration, TimeZone};
@@ -31,6 +31,19 @@ fn mutation_target(is_read_only: bool) -> CalendarEventMutationTarget {
calendar_id: Uuid::now_v7(),
provider_calendar_id: "primary".to_string(),
token_identity: token_identity(),
+ actor: Some(ActorInboxes::sole("[email protected]")),
+ }
+}
+
+fn echo_attendee(email: &str, is_self: bool) -> CalendarAttendee {
+ CalendarAttendee {
+ email: email.to_string(),
+ display_name: None,
+ response_status: AttendeeResponseStatus::NeedsAction,
+ is_organizer: false,
+ is_optional: false,
+ is_self,
+ comment: None,
}
}
@@ -43,6 +56,7 @@ fn creation_target(is_read_only: bool) -> CalendarCreationTarget {
provider_calendar_id: "primary".to_string(),
is_read_only,
token_identity: token_identity(),
+ actor: Some(ActorInboxes::sole("[email protected]")),
}
}
@@ -129,6 +143,9 @@ struct FakeRepo {
retired_events: Vec<RetiredCalendarEvent>,
disconnected: Option<DisconnectedGoogleCalendar>,
disconnect_requests: Arc<Mutex<Vec<(String, Uuid)>>>,
+ visible_calendars: Vec<VisibleCalendar>,
+ fail_list_visible: bool,
+ fail_owned_inboxes: bool,
}
impl Default for FakeRepo {
@@ -143,6 +160,9 @@ impl Default for FakeRepo {
retired_events: Vec::new(),
disconnected: None,
disconnect_requests: Default::default(),
+ visible_calendars: Vec::new(),
+ fail_list_visible: false,
+ fail_owned_inboxes: false,
}
}
}
@@ -273,6 +293,9 @@ impl CalendarRepository for FakeRepo {
_requester_id: &str,
_event_id: Uuid,
) -> Result<Option<CalendarEventMutationTarget>, rootcause::Report> {
+ if self.fail_owned_inboxes {
+ return Err(rootcause::report!("owned inboxes unavailable"));
+ }
Ok(self.mutation_target.clone())
}
@@ -282,6 +305,9 @@ impl CalendarRepository for FakeRepo {
_email_link_id: Option<Uuid>,
_calendar_id: Option<Uuid>,
) -> Result<Option<CalendarCreationTarget>, rootcause::Report> {
+ if self.fail_owned_inboxes {
+ return Err(rootcause::report!("owned inboxes unavailable"));
+ }
Ok(self.creation_target.clone())
}
@@ -289,6 +315,19 @@ impl CalendarRepository for FakeRepo {
&self,
_requester_id: &str,
) -> Result<Vec<crate::domain::models::VisibleCalendar>, rootcause::Report> {
+ if self.fail_list_visible {
+ return Err(rootcause::report!("visible calendars unavailable"));
+ }
+ Ok(self.visible_calendars.clone())
+ }
+
+ async fn owned_inbox_emails(
+ &self,
+ _requester_id: &str,
+ ) -> Result<Vec<String>, rootcause::Report> {
+ if self.fail_owned_inboxes {
+ return Err(rootcause::report!("owned inboxes unavailable"));
+ }
Ok(Vec::new())
}
@@ -320,6 +359,8 @@ enum FakeProviderBehavior {
struct FakeProvider {
behavior: FakeProviderBehavior,
calls: Arc<Mutex<Vec<String>>>,
+ rsvp_self_emails: Arc<Mutex<Vec<Vec<String>>>>,
+ echo_attendees: Vec<CalendarAttendee>,
created_drafts: Arc<Mutex<Vec<CalendarEventDraft>>>,
}
@@ -328,10 +369,18 @@ impl FakeProvider {
Self {
behavior,
calls: Arc::new(Mutex::new(Vec::new())),
+ rsvp_self_emails: Arc::new(Mutex::new(Vec::new())),
+ echo_attendees: Vec::new(),
created_drafts: Arc::new(Mutex::new(Vec::new())),
}
}
+ fn echo(&self, owner_id: &str) -> CalendarEventUpsert {
+ let mut upsert = echo_upsert(owner_id);
+ upsert.event.attendees = self.echo_attendees.clone();
+ upsert
+ }
+
fn fail(&self) -> Option<GoogleProviderError> {
match &self.behavior {
FakeProviderBehavior::Fail(kind) => {
@@ -354,7 +403,7 @@ impl GoogleCalendarMutationProvider for FakeProvider {
if let Some(error) = self.fail() {
return Err(error);
}
- Ok(echo_upsert(&target.owner_id))
+ Ok(self.echo(&target.owner_id))
}
async fn update_event(
@@ -374,7 +423,7 @@ impl GoogleCalendarMutationProvider for FakeProvider {
if matches!(self.behavior, FakeProviderBehavior::Gone) {
return Ok(None);
}
- Ok(Some(echo_upsert(&target.owner_id)))
+ Ok(Some(self.echo(&target.owner_id)))
}
async fn update_event_instance(
@@ -394,9 +443,9 @@ impl GoogleCalendarMutationProvider for FakeProvider {
Ok(match self.behavior {
FakeProviderBehavior::Gone => GoogleInstanceUpdateOutcome::SeriesGone,
FakeProviderBehavior::OccurrenceGone => {
- GoogleInstanceUpdateOutcome::OccurrenceGone(Box::new(echo_upsert(&target.owner_id)))
+ GoogleInstanceUpdateOutcome::OccurrenceGone(Box::new(self.echo(&target.owner_id)))
}
- _ => GoogleInstanceUpdateOutcome::Applied(Box::new(echo_upsert(&target.owner_id))),
+ _ => GoogleInstanceUpdateOutcome::Applied(Box::new(self.echo(&target.owner_id))),
})
}
@@ -448,7 +497,7 @@ impl GoogleCalendarMutationProvider for FakeProvider {
}
Ok(match self.behavior {
FakeProviderBehavior::Gone => GoogleSeriesMutationOutcome::Gone,
- _ => GoogleSeriesMutationOutcome::Applied(Box::new(echo_upsert(&target.owner_id))),
+ _ => GoogleSeriesMutationOutcome::Applied(Box::new(self.echo(&target.owner_id))),
})
}
@@ -467,7 +516,7 @@ impl GoogleCalendarMutationProvider for FakeProvider {
}
Ok(match self.behavior {
FakeProviderBehavior::Gone => GoogleSeriesMutationOutcome::SeriesDeleted,
- _ => GoogleSeriesMutationOutcome::Applied(Box::new(echo_upsert(&target.owner_id))),
+ _ => GoogleSeriesMutationOutcome::Applied(Box::new(self.echo(&target.owner_id))),
})
}
@@ -476,7 +525,7 @@ impl GoogleCalendarMutationProvider for FakeProvider {
_access_token: &str,
target: &GoogleCalendarTarget,
master_provider_event_id: &str,
- _self_email: &str,
+ actor: &ActorInboxes,
_response: AttendeeResponseStatus,
scope: &CalendarRsvpScope,
) -> Result<GoogleRsvpOutcome, GoogleProviderError> {
@@ -488,13 +537,17 @@ impl GoogleCalendarMutationProvider for FakeProvider {
.lock()
.unwrap()
.push(format!("rsvp:{master_provider_event_id}:{scope}"));
+ self.rsvp_self_emails
+ .lock()
+ .unwrap()
+ .push(actor.iter().map(str::to_string).collect());
if let Some(error) = self.fail() {
return Err(error);
}
Ok(match self.behavior {
FakeProviderBehavior::Gone => GoogleRsvpOutcome::Gone,
FakeProviderBehavior::NotAttendee => GoogleRsvpOutcome::NotAttendee,
- _ => GoogleRsvpOutcome::Applied(Box::new(echo_upsert(&target.owner_id))),
+ _ => GoogleRsvpOutcome::Applied(Box::new(self.echo(&target.owner_id))),
})
}
}
@@ -650,6 +703,53 @@ async fn create_persists_the_provider_echo_and_returns_the_applied_id() {
assert_eq!(upserts.lock().unwrap().len(), 1);
}
+#[tokio::test]
+async fn create_does_not_write_when_inbox_lookup_fails() {
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let calls = provider.calls.clone();
+ let repo = FakeRepo {
+ creation_target: Some(creation_target(false)),
+ fail_owned_inboxes: true,
+ ..FakeRepo::default()
+ };
+ let upserts = repo.upserts.clone();
+
+ let error = service(repo, provider, FakeTokens::ok())
+ .create_event("macro|user", None, None, draft())
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, CalendarMutationError::Retryable(_)));
+ assert!(calls.lock().unwrap().is_empty());
+ assert!(upserts.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn create_returned_echo_marks_requester_inboxes_as_self() {
+ let mut provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ provider.echo_attendees = vec![
+ echo_attendee("[email protected]", true),
+ echo_attendee("[email protected]", false),
+ ];
+ let created = service(
+ FakeRepo {
+ creation_target: Some(CalendarCreationTarget {
+ actor: ActorInboxes::from_owned(vec!["[email protected]".to_string()]),
+ ..creation_target(false)
+ }),
+ ..FakeRepo::default()
+ },
+ provider,
+ FakeTokens::ok(),
+ )
+ .create_event("macro|user", None, None, draft())
+ .await
+ .unwrap();
+
+ assert!(!created.attendees[0].is_self);
+ assert!(created.attendees[1].is_self);
+}
+
#[tokio::test]
async fn create_publishes_created_when_the_row_was_inserted() {
let applied_id = Uuid::now_v7();
@@ -1331,6 +1431,129 @@ async fn rsvp_surfaces_attendance_and_persists_the_echo() {
);
}
+#[tokio::test]
+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()]);
+ service(
+ FakeRepo {
+ mutation_target: Some(target),
+ ..FakeRepo::default()
+ },
+ provider,
+ FakeTokens::ok(),
+ )
+ .respond_to_event(
+ "macro|user",
+ Uuid::now_v7(),
+ AttendeeResponseStatus::Accepted,
+ CalendarRsvpScope::All,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ emails.lock().unwrap().as_slice(),
+ [vec!["[email protected]".to_string()]]
+ );
+}
+
+#[tokio::test]
+async fn rsvp_through_a_delegated_inbox_never_hands_the_subject_email_to_the_provider() {
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let emails = provider.rsvp_self_emails.clone();
+ let mut target = mutation_target(false);
+ target.token_identity = CalendarLinkTokenIdentity {
+ fusionauth_user_id: "fusion-jacob".to_string(),
+ email_address: "[email protected]".to_string(),
+ provider: "GMAIL".to_string(),
+ };
+ target.actor = ActorInboxes::from_owned(vec!["[email protected]".to_string()]);
+ service(
+ FakeRepo {
+ mutation_target: Some(target),
+ ..FakeRepo::default()
+ },
+ provider,
+ FakeTokens::ok(),
+ )
+ .respond_to_event(
+ "macro|user",
+ Uuid::now_v7(),
+ AttendeeResponseStatus::Accepted,
+ CalendarRsvpScope::All,
+ )
+ .await
+ .unwrap();
+
+ let recorded = emails.lock().unwrap();
+ assert_eq!(recorded.len(), 1);
+ assert!(
+ recorded[0]
+ .iter()
+ .any(|email| email == "[email protected]")
+ );
+ assert!(!recorded[0].iter().any(|email| email == "[email protected]"));
+}
+
+#[tokio::test]
+async fn rsvp_through_a_delegated_inbox_without_an_own_inbox_is_not_attendee_before_any_provider_call()
+ {
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let calls = provider.calls.clone();
+ let mut target = mutation_target(false);
+ target.actor = None;
+ let error = service(
+ FakeRepo {
+ mutation_target: Some(target),
+ ..FakeRepo::default()
+ },
+ provider,
+ FakeTokens::ok(),
+ )
+ .respond_to_event(
+ "macro|user",
+ Uuid::now_v7(),
+ AttendeeResponseStatus::Accepted,
+ CalendarRsvpScope::All,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, CalendarMutationError::NotAttendee));
+ assert!(calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn rsvp_echo_marks_actor_inboxes_as_self() {
+ let mut provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ provider.echo_attendees = vec![
+ echo_attendee("[email protected]", true),
+ echo_attendee("[email protected]", false),
+ ];
+ let event = service(
+ FakeRepo {
+ mutation_target: Some(mutation_target(false)),
+ ..FakeRepo::default()
+ },
+ provider,
+ FakeTokens::ok(),
+ )
+ .respond_to_event(
+ "macro|user",
+ Uuid::now_v7(),
+ AttendeeResponseStatus::Accepted,
+ CalendarRsvpScope::All,
+ )
+ .await
+ .unwrap();
+
+ assert!(!event.attendees[0].is_self);
+ assert!(event.attendees[1].is_self);
+}
+
#[tokio::test]
async fn token_and_provider_failures_map_to_typed_errors() {
let reauth = service(
diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rs
index 42d47351e4..ff80cca5df 100644
--- a/crates/calendar_events/src/domain/ports.rs
+++ b/crates/calendar_events/src/domain/ports.rs
@@ -7,7 +7,7 @@ use rootcause::Report;
use uuid::Uuid;
use super::models::{
- AppliedGoogleGrant, AttendeeResponseStatus, CalendarBackfillClaim,
+ ActorInboxes, AppliedGoogleGrant, AttendeeResponseStatus, CalendarBackfillClaim,
CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJobKey,
CalendarCreationTarget, CalendarEvent, CalendarEventDraft, CalendarEventMutationTarget,
CalendarEventPatch, CalendarEventUpsert, CalendarGrantIntent, CalendarLinkTokenIdentity,
@@ -175,10 +175,10 @@ pub trait GoogleCalendarMutationProvider: Send + Sync + 'static {
original_start: &str,
) -> impl Future<Output = Result<GoogleSeriesMutationOutcome, GoogleProviderError>> + Send;
- /// Set the connected account's own RSVP on an event. An event that no
- /// longer exists at the provider surfaces as [`GoogleRsvpOutcome::Gone`];
- /// absence of a self attendee surfaces as
- /// [`GoogleRsvpOutcome::NotAttendee`].
+ /// Set the actor's own RSVP on an event. `actor` is the requester's
+ /// owned-inbox identity. An event that no longer exists at the
+ /// provider surfaces as [`GoogleRsvpOutcome::Gone`]; absence of a matching
+ /// attendee surfaces as [`GoogleRsvpOutcome::NotAttendee`].
///
/// `scope` selects what the response covers: the master for
/// [`CalendarRsvpScope::All`], one exception instance for
@@ -188,7 +188,7 @@ pub trait GoogleCalendarMutationProvider: Send + Sync + 'static {
access_token: &str,
target: &GoogleCalendarTarget,
master_provider_event_id: &str,
- self_email: &str,
+ actor: &ActorInboxes,
response: AttendeeResponseStatus,
scope: &CalendarRsvpScope,
) -> impl Future<Output = Result<GoogleRsvpOutcome, GoogleProviderError>> + Send;
@@ -505,6 +505,14 @@ pub trait CalendarRepository: Send + Sync + 'static {
requester_id: &str,
) -> impl Future<Output = Result<Vec<VisibleCalendar>, Report>> + Send;
+ /// Addresses of 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(
+ &self,
+ requester_id: &str,
+ ) -> impl Future<Output = Result<Vec<String>, Report>> + Send;
+
/// Retire a Google source the provider confirmed deleted (a recurring
/// master also retires its expanded instances), restoring the best
/// surviving source or removing the entity, mirroring feed tombstones.
diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rs
index 4f5416d988..a89695e2c7 100644
--- a/crates/calendar_events/src/domain/service.rs
+++ b/crates/calendar_events/src/domain/service.rs
@@ -10,10 +10,10 @@ use macro_event_broker::MacroEventBroker;
use super::{
models::{
- AppliedGoogleGrant, CalendarBackfillClaim, CalendarBackfillFailureDisposition,
- CalendarBackfillFailureOutcome, CalendarBackfillJobKey, CalendarEventUpsert,
- CalendarGrantIntent, CalendarOccurrenceCursor, GoogleBackfillRunReport,
- GoogleCalendarSyncSnapshot, GoogleScopeSet, OccurrenceRange,
+ ActorInboxes, AppliedGoogleGrant, CalendarBackfillClaim,
+ CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJobKey,
+ CalendarEventUpsert, CalendarGrantIntent, CalendarOccurrenceCursor,
+ GoogleBackfillRunReport, GoogleCalendarSyncSnapshot, GoogleScopeSet, OccurrenceRange,
},
ports::{
CalendarBackfillRepository, CalendarEventChange, CalendarEventWrite,
@@ -96,9 +96,18 @@ where
Report,
> {
validate_query(&range, limit)?;
- self.repository
+ let mut rows = self
+ .repository
.list_occurrences(requester_id, range, cursor, limit)
- .await
+ .await?;
+ if let Some(viewer) =
+ ActorInboxes::from_owned(self.repository.owned_inbox_emails(requester_id).await?)
+ {
+ for (event, _) in &mut rows {
+ viewer.mark_attendees(&mut event.attendees);
+ }
+ }
+ Ok(rows)
}
/// Return the aggregate ingestion state of the requester's visible accounts.
diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rs
index eeedc2407d..7b54341f13 100644
--- a/crates/calendar_events/src/domain/service/test.rs
+++ b/crates/calendar_events/src/domain/service/test.rs
@@ -113,7 +113,11 @@ impl CalendarRepository for FakeRepo {
&self,
_requester_id: &str,
) -> Result<Vec<crate::domain::models::VisibleCalendar>, Report> {
- unreachable!("mutation lookups are not exercised by sync tests")
+ Ok(Vec::new())
+ }
+
+ async fn owned_inbox_emails(&self, _requester_id: &str) -> Result<Vec<String>, Report> {
+ Ok(Vec::new())
}
async fn remove_google_source(
diff --git a/crates/calendar_events/src/outbound/google.rs b/crates/calendar_events/src/outbound/google.rs
index 84eac34cdc..468dc95d30 100644
--- a/crates/calendar_events/src/outbound/google.rs
+++ b/crates/calendar_events/src/outbound/google.rs
@@ -10,11 +10,11 @@ use uuid::Uuid;
use crate::domain::{
models::{
- AttendeeResponseStatus, CalendarAttendee, CalendarAttendeeInput, CalendarEvent,
- CalendarEventDraft, CalendarEventOverride, CalendarEventPatch, CalendarEventSource,
- CalendarEventUpsert, CalendarOccurrence, ConferenceChange, ConferenceProvider,
- EventReminderOverride, EventReminders, EventStart, EventStatus, EventTime,
- EventTransparency, EventVisibility, GoogleCalendarTarget, GoogleEventSource,
+ ActorInboxes, AttendeeResponseStatus, CalendarAttendee, CalendarAttendeeInput,
+ CalendarEvent, CalendarEventDraft, CalendarEventOverride, CalendarEventPatch,
+ CalendarEventSource, CalendarEventUpsert, CalendarOccurrence, ConferenceChange,
+ ConferenceProvider, EventReminderOverride, EventReminders, EventStart, EventStatus,
+ EventTime, EventTransparency, EventVisibility, GoogleCalendarTarget, GoogleEventSource,
GoogleEventSyncBatch, GoogleSyncPlan, GoogleWatchChannel, GoogleWatchConfig,
OccurrenceRange, ProviderCalendar,
},
@@ -1140,7 +1140,7 @@ impl<G: GoogleRequestGate> GoogleCalendarMutationProvider for GoogleCalendarClie
}
#[tracing::instrument(
- skip(self, access_token, target, self_email),
+ skip(self, access_token, target, actor),
fields(provider_calendar_id = %target.provider_calendar_id),
err
)]
@@ -1149,7 +1149,7 @@ impl<G: GoogleRequestGate> GoogleCalendarMutationProvider for GoogleCalendarClie
access_token: &str,
target: &GoogleCalendarTarget,
master_provider_event_id: &str,
- self_email: &str,
+ actor: &ActorInboxes,
response: AttendeeResponseStatus,
scope: &CalendarRsvpScope,
) -> Result<GoogleRsvpOutcome, GoogleProviderError> {
@@ -1169,13 +1169,7 @@ impl<G: GoogleRequestGate> GoogleCalendarMutationProvider for GoogleCalendarClie
};
if let Some(provider_event_id) = &patch_target {
match self
- .patch_self_response(
- access_token,
- target,
- provider_event_id,
- self_email,
- response,
- )
+ .patch_actor_response(access_token, target, provider_event_id, actor, response)
.await?
{
RsvpPatch::Applied => {}
@@ -1271,22 +1265,22 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
.map(|instance| instance.id))
}
- /// Rewrite just the connected account's `responseStatus` on one provider
- /// event, leaving every other attendee untouched.
+ /// Rewrite just the actor's `responseStatus` on one provider event,
+ /// leaving every other attendee untouched.
///
- /// The patch sends `attendeesOmitted: true` with only the connected
- /// attendee's entry — Google's documented mechanism for updating one
- /// participant's response — so a concurrent attendee change between our
+ /// The patch sends `attendeesOmitted: true` with only the actor's
+ /// entry, which is Google's documented mechanism for updating one
+ /// participant's response. A concurrent attendee change between our
/// read and this write cannot be overwritten by a full-array replace.
/// The read stays: it distinguishes a vanished event from a requester
/// who simply is not on the guest list, which the patch alone would
/// answer by quietly adding them.
- async fn patch_self_response(
+ async fn patch_actor_response(
&self,
access_token: &str,
target: &GoogleCalendarTarget,
provider_event_id: &str,
- self_email: &str,
+ actor: &ActorInboxes,
response: AttendeeResponseStatus,
) -> Result<RsvpPatch, GoogleProviderError> {
let Some(current) = self
@@ -1301,21 +1295,10 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
return Ok(RsvpPatch::Gone);
};
let attendees: Vec<GoogleAttendee> = current.attendees.clone().unwrap_or_default();
- let self_attendee = attendees
- .iter()
- .find(|attendee| attendee.is_self)
- .or_else(|| {
- attendees.iter().find(|attendee| {
- attendee
- .email
- .as_deref()
- .is_some_and(|email| email.eq_ignore_ascii_case(self_email))
- })
- });
- let Some(self_attendee) = self_attendee else {
+ let Some(actor_attendee) = find_actor_attendee(&attendees, actor) else {
return Ok(RsvpPatch::NotAttendee);
};
- let body = rsvp_patch_body(self_attendee, response);
+ let body = rsvp_patch_body(actor_attendee, response);
match self
.patch_event_raw(access_token, target, provider_event_id, body)
.await?
@@ -1419,6 +1402,18 @@ fn google_response_status(status: AttendeeResponseStatus) -> &'static str {
}
}
+fn find_actor_attendee<'a>(
+ attendees: &'a [GoogleAttendee],
+ actor: &ActorInboxes,
+) -> Option<&'a GoogleAttendee> {
+ attendees.iter().find(|attendee| {
+ attendee
+ .email
+ .as_deref()
+ .is_some_and(|email| actor.matches(email))
+ })
+}
+
/// Body updating only the connected attendee's response: `attendeesOmitted`
/// tells Google the array is partial, so other attendees survive untouched.
fn rsvp_patch_body(
diff --git a/crates/calendar_events/src/outbound/google/test.rs b/crates/calendar_events/src/outbound/google/test.rs
index 11247d04a2..3dba9fdc49 100644
--- a/crates/calendar_events/src/outbound/google/test.rs
+++ b/crates/calendar_events/src/outbound/google/test.rs
@@ -559,6 +559,38 @@ fn rsvp_patch_updates_only_the_connected_attendee() {
assert_eq!(attendees[0]["comment"], "unrelated state that must survive");
}
+fn google_attendee(email: &str, is_self: bool) -> GoogleAttendee {
+ serde_json::from_value(serde_json::json!({
+ "email": email,
+ "self": is_self,
+ "responseStatus": "needsAction",
+ }))
+ .unwrap()
+}
+
+#[test]
+fn rsvp_patches_the_actor_row_not_the_google_self_flag() {
+ let attendees = vec![
+ 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 found = find_actor_attendee(&attendees, &actor);
+ assert_eq!(
+ found.and_then(|attendee| attendee.email.as_deref()),
+ );
+}
+
+#[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");
+ assert!(find_actor_attendee(&attendees, &actor).is_none());
+}
+
#[test]
fn google_attendees_write_an_explicit_response_status() {
let body = google_attendees_body(&[
diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rs
index e79d87ab92..6a26e319b6 100644
--- a/crates/calendar_events/src/outbound/pg.rs
+++ b/crates/calendar_events/src/outbound/pg.rs
@@ -11,10 +11,10 @@ use uuid::Uuid;
use crate::domain::{
models::{
- AppliedGoogleGrant, AttendeeResponseStatus, CalendarAttendee, CalendarBackfillClaim,
- CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJob,
- CalendarBackfillJobKey, CalendarBackfillKind, CalendarCreationTarget, CalendarEvent,
- CalendarEventMutationTarget, CalendarEventOverride, CalendarEventSource,
+ ActorInboxes, AppliedGoogleGrant, AttendeeResponseStatus, CalendarAttendee,
+ CalendarBackfillClaim, CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome,
+ CalendarBackfillJob, CalendarBackfillJobKey, CalendarBackfillKind, CalendarCreationTarget,
+ CalendarEvent, CalendarEventMutationTarget, CalendarEventOverride, CalendarEventSource,
CalendarEventUpsert, CalendarGrantIntent, CalendarLinkTokenIdentity, CalendarMentionEvent,
CalendarMentionPreview, CalendarMentionRequestItem, CalendarOccurrence,
CalendarOccurrenceCursor, CalendarReminderFiring, CalendarSyncStatus, CalendarWatchRelease,
@@ -1559,7 +1559,16 @@ impl CalendarRepository for PgCalendarRepository {
.fetch_optional(&self.pool)
.await
.map_err(report)?;
- Ok(row.map(|row| CalendarEventMutationTarget {
+ let Some(row) = row else {
+ return Ok(None);
+ };
+ let actor = ActorInboxes::from_owned(self.owned_inbox_emails(requester_id).await?);
+ let token_identity = CalendarLinkTokenIdentity {
+ fusionauth_user_id: row.fusionauth_user_id,
+ email_address: row.email_address,
+ provider: row.provider,
+ };
+ Ok(Some(CalendarEventMutationTarget {
event_id: row.event_id,
is_read_only: row.is_read_only,
provider_event_id: row.provider_event_id,
@@ -1569,11 +1578,8 @@ impl CalendarRepository for PgCalendarRepository {
account_id: row.account_id,
calendar_id: row.calendar_id,
provider_calendar_id: row.provider_calendar_id,
- token_identity: CalendarLinkTokenIdentity {
- fusionauth_user_id: row.fusionauth_user_id,
- email_address: row.email_address,
- provider: row.provider,
- },
+ token_identity,
+ actor,
}))
}
@@ -1628,18 +1634,24 @@ impl CalendarRepository for PgCalendarRepository {
.fetch_optional(&self.pool)
.await
.map_err(report)?;
- Ok(row.map(|row| CalendarCreationTarget {
+ let Some(row) = row else {
+ return Ok(None);
+ };
+ let actor = ActorInboxes::from_owned(self.owned_inbox_emails(requester_id).await?);
+ let token_identity = CalendarLinkTokenIdentity {
+ fusionauth_user_id: row.fusionauth_user_id,
+ email_address: row.email_address,
+ provider: row.provider,
+ };
+ Ok(Some(CalendarCreationTarget {
owner_id: row.owner_id,
email_link_id: row.email_link_id,
account_id: row.account_id,
calendar_id: row.calendar_id,
provider_calendar_id: row.provider_calendar_id,
is_read_only: !matches!(row.access_role.as_deref(), Some("owner" | "writer")),
- token_identity: CalendarLinkTokenIdentity {
- fusionauth_user_id: row.fusionauth_user_id,
- email_address: row.email_address,
- provider: row.provider,
- },
+ token_identity,
+ actor,
}))
}
@@ -1705,6 +1717,21 @@ impl CalendarRepository for PgCalendarRepository {
.collect())
}
+ #[tracing::instrument(skip(self, requester_id), err)]
+ async fn owned_inbox_emails(&self, requester_id: &str) -> Result<Vec<String>, Report> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT email_address::text AS "email_address!"
+ FROM email_links
+ WHERE macro_id = $1
+ "#,
+ requester_id,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(report)
+ }
+
#[tracing::instrument(skip(self), err)]
async fn remove_google_source(
&self,
diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rs
index 8df8d34de5..26803cf6b0 100644
--- a/crates/calendar_events/src/outbound/pg/test.rs
+++ b/crates/calendar_events/src/outbound/pg/test.rs
@@ -2312,13 +2312,26 @@ async fn mutation_target_resolves_only_for_visible_requesters(pool: PgPool) {
assert_eq!(target.calendar_id, provider.1);
assert_eq!(target.provider_calendar_id, "primary");
assert_eq!(target.owner_id, owner_id);
+ let inbox = format!("calendar-{link_id}@example.com");
assert_eq!(target.token_identity.provider, "GMAIL");
+ assert_eq!(target.token_identity.email_address, inbox);
+ assert!(
+ target
+ .actor
+ .as_ref()
+ .is_some_and(|actor| actor.matches(&inbox))
+ );
let delegated = repo
.get_event_mutation_target(delegate_id, event_id)
.await
- .unwrap();
- assert!(delegated.is_some(), "delegate sees the mutation target");
+ .unwrap()
+ .expect("delegate sees the mutation target");
+ assert_eq!(delegated.token_identity.email_address, inbox);
+ assert!(
+ delegated.actor.is_none(),
+ "a delegate without their own inbox has no actor"
+ );
let hidden = repo
.get_event_mutation_target(stranger_id, event_id)
@@ -2327,6 +2340,54 @@ async fn mutation_target_resolves_only_for_visible_requesters(pool: PgPool) {
assert!(hidden.is_none(), "stranger cannot see the mutation target");
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn creation_target_actor_is_owned_inboxes_not_the_calendar_inbox(pool: PgPool) {
+ let owner_id = "macro|[email protected]";
+ let delegate_id = "macro|[email protected]";
+ insert_user(&pool, owner_id).await;
+ insert_user(&pool, delegate_id).await;
+ let link_id = insert_link(&pool, owner_id).await;
+ let repo = PgCalendarRepository::new(pool.clone());
+ grant_and_provider_ids(&repo, link_id).await;
+ sqlx::query!(
+ r#"
+ INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)
+ VALUES ($1, $2, $3)
+ "#,
+ delegate_id,
+ owner_id,
+ link_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let inbox = format!("calendar-{link_id}@example.com");
+ let owner = repo
+ .get_creation_target(owner_id, None, None)
+ .await
+ .unwrap()
+ .expect("owner resolves a creation target");
+ assert_eq!(owner.token_identity.email_address, inbox);
+ assert!(
+ owner
+ .actor
+ .as_ref()
+ .is_some_and(|actor| actor.matches(&inbox))
+ );
+
+ let delegated = repo
+ .get_creation_target(delegate_id, None, None)
+ .await
+ .unwrap()
+ .expect("delegate resolves a creation target");
+ assert_eq!(delegated.token_identity.email_address, inbox);
+ assert!(
+ delegated.actor.is_none(),
+ "a delegate without their own inbox has no actor"
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn creation_target_prefers_the_requesters_own_primary_inbox(pool: PgPool) {
let owner_id = "macro|[email protected]";
diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.ts
index 3ede6bade3..2a9a323b75 100644
--- a/packages/sdk/generated/email/types.gen.ts
+++ b/packages/sdk/generated/email/types.gen.ts
@@ -559,7 +559,10 @@ export type CalendarAttendee = {
*/
isOrganizer: boolean;
/**
- * Whether this attendee represents the connected account.
+ * Whether this attendee is one of the viewing requester's inboxes.
+ *
+ * Outbound projections use the requester's owned inboxes only.
+ * Persisted rows keep the provider's flag, which reminder decline reads.
*/
isSelf: boolean;
/**
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 9bb7724110..804ecafb0d 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -1224,7 +1224,10 @@ export type CalendarAttendee = {
*/
isOrganizer: boolean;
/**
- * Whether this attendee represents the connected account.
+ * Whether this attendee is one of the viewing requester's inboxes.
+ *
+ * Outbound projections use the requester's owned inboxes only.
+ * Persisted rows keep the provider's flag, which reminder decline reads.
*/
isSelf: boolean;
/**
diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.json
index 5a9fd8eb68..fb9ed1df53 100644
--- a/packages/sdk/specs/email.json
+++ b/packages/sdk/specs/email.json
@@ -4475,7 +4475,7 @@
},
"isSelf": {
"type": "boolean",
- "description": "Whether this attendee represents the connected account."
+ "description": "Whether this attendee is one of the viewing requester's inboxes.\n\nOutbound projections use the requester's owned inboxes only.\nPersisted rows keep the provider's flag, which reminder decline reads."
},
"responseStatus": {
"$ref": "#/components/schemas/AttendeeResponseStatus",
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 7caac442b7..517ea9743b 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -13271,7 +13271,7 @@
},
"isSelf": {
"type": "boolean",
- "description": "Whether this attendee represents the connected account."
+ "description": "Whether this attendee is one of the viewing requester's inboxes.\n\nOutbound projections use the requester's owned inboxes only.\nPersisted rows keep the provider's flag, which reminder decline reads."
},
"responseStatus": {
"$ref": "#/components/schemas/AttendeeResponseStatus",