Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calendar): delete an event's channel access grants with the event (#8749)
gbirman6d6331613db9
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 2e4e5d0559..f14d2be32b 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -92,6 +92,13 @@ reminder dispatch, team availability, and provider/Postgres persistence.`InvalidInput`.`ViewerCapabilities::set_guest_policy` is therefore Google-only, and`organize` is the organizer signal clients read instead.+- Sharing an event into a channel writes an `entity_access` row on the+ sharer's copy. The `calendar_event_entity_access_cleanup` trigger deletes it+ with the event row, which covers every way a copy goes away: a delete+ through Macro, a sync tombstone or removal, a disabled calendar, and the+ `email_links` cascade when the inbox is removed. A cancelled, private or+ confidential row keeps its grants, since readers skip them and the row can+ come back. Removing one source, or cancelling one occurrence, leaves the row.- A channel-shared event reaches a member's calendar as a snapshot, not aseat: `copy_shared_event` (`src/domain/mutations/copy.rs`) imports it underthe meeting's iCalendar UID with no join link, behind the samediff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex d047f73bcf..d4df3b374f 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -7257,6 +7257,7 @@ async fn retiring_an_unrelated_copy_keeps_a_fresher_schedule_written_through_ano}mod changes;+mod channel_grants;mod details;mod export;mod invitations;diff --git a/crates/calendar_events/src/outbound/pg/test/channel_grants.rs b/crates/calendar_events/src/outbound/pg/test/channel_grants.rsnew file mode 100644index 0000000000..8e2bdb364e--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/channel_grants.rs@@ -0,0 +1,232 @@+use super::*;++/// Calendar events that still hold an access grant, in id order.+async fn granted_event_ids(pool: &PgPool) -> Vec<Uuid> {+ sqlx::query_scalar!(+ r#"+ SELECT entity_id AS "entity_id!"+ FROM entity_access+ WHERE entity_type = 'calendar_event'+ ORDER BY entity_id+ "#,+ )+ .fetch_all(pool)+ .await+ .unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn deleting_an_event_through_macro_removes_its_channel_grants(pool: PgPool) {+ let sharer_id = "macro|[email protected]";+ let member_id = "macro|[email protected]";+ let sharer_link = insert_link(&pool, sharer_id).await;+ let member_link = insert_link(&pool, member_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, primary_id) = grant_and_provider_ids(&repo, sharer_link).await;+ let team_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "team".to_string(),+ name: "Team".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("writer".to_string()),+ is_primary: false,+ is_selected: true,+ default_reminders: Vec::new(),+ },+ )+ .await+ .unwrap();++ // The sharer holds the meeting on two of their calendars (one entity, two+ // sources); the member holds their own copy, which is a separate entity.+ let sharer_event_id = repo+ .upsert_event_fixture(timed_upsert(+ sharer_id,+ sharer_link,+ (account_id, primary_id),+ "[email protected]",+ "Planning",+ 1,+ ))+ .await+ .unwrap();+ let mut team_copy = timed_upsert(+ sharer_id,+ sharer_link,+ (account_id, team_id),+ "[email protected]",+ "Planning",+ 1,+ );+ team_copy.source = CalendarEventSource::Google(ProviderEventSource {+ automatic_decline: None,+ binding: None,+ observed_access_role: Some("writer".to_owned()),+ email_link_id: sharer_link,+ account_id,+ calendar_id: team_id,+ provider_event_id: "team-grant-meeting".to_string(),+ provider_recurring_event_id: None,+ provider_etag: None,+ raw_payload: serde_json::json!({}),+ });+ assert_eq!(+ repo.upsert_event_fixture(team_copy).await.unwrap(),+ sharer_event_id+ );+ let member_provider = provider_ids(&repo, member_link).await;+ let member_event_id = repo+ .upsert_event_fixture(timed_upsert(+ member_id,+ member_link,+ member_provider,+ "[email protected]",+ "Planning",+ 1,+ ))+ .await+ .unwrap();+ let channel_id = insert_channel(&pool, sharer_id, &[sharer_id, member_id]).await;+ share_with_channel(&pool, sharer_event_id, channel_id).await;+ share_with_channel(&pool, member_event_id, channel_id).await;+ let mut both = vec![sharer_event_id, member_event_id];+ both.sort();++ // Removing it from one calendar leaves the event, and its grant, in place.+ repo.remove_provider_source(account_id, primary_id, "[email protected]")+ .await+ .unwrap();+ assert_eq!(granted_event_ids(&pool).await, both);++ // Removing the last source deletes the sharer's copy and its grant; the+ // member's copy of the same meeting keeps its own.+ repo.remove_provider_source(account_id, team_id, "team-grant-meeting")+ .await+ .unwrap();+ assert_eq!(granted_event_ids(&pool).await, vec![member_event_id]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_cancelled_occurrence_keeps_the_series_grant_and_a_cancelled_series_drops_it(+ pool: PgPool,+) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let enabled = repo+ .apply_google_grant(+ link_id,+ complete_grant(),+ CalendarGrantIntent::CalendarRequested,+ )+ .await+ .unwrap();+ let provider = provider_ids(&repo, link_id).await;+ let series = timed_upsert(+ owner_id,+ link_id,+ provider,+ "[email protected]",+ "Standup",+ 1,+ );+ let event_id = repo.upsert_event_fixture(series.clone()).await.unwrap();+ let channel_id = insert_channel(&pool, owner_id, &[owner_id]).await;+ share_with_channel(&pool, event_id, channel_id).await;++ // Google cancels one instance by refreshing the series without it.+ let mut one_cancelled = series;+ one_cancelled.event.sequence = 2;+ one_cancelled.event.updated_at += Duration::minutes(1);+ one_cancelled.occurrences[1].is_cancelled = true;+ assert_eq!(+ repo.upsert_event_fixture(one_cancelled).await.unwrap(),+ event_id+ );+ assert_eq!(+ sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM calendar_event_occurrences WHERE event_id = $1 AND is_cancelled"#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 1+ );+ assert_eq!(granted_event_ids(&pool).await, vec![event_id]);++ // A tombstone for the series retires it, and the grant goes with it.+ let google_job = enabled+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let key = CalendarBackfillJobKey {+ job_id: google_job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ repo.commit_google_calendar_sync(+ key,+ lease_token,+ provider.0,+ GoogleCalendarSyncSnapshot {+ calendar_id: provider.1,+ next_sync_token: "after-tombstone".to_string(),+ observed_provider_event_ids: None,+ materialized_range: None,+ cancelled_provider_event_ids: vec!["[email protected]".to_string()],+ },+ 0,+ )+ .await+ .unwrap();+ assert_eq!(granted_event_ids(&pool).await, Vec::<Uuid>::new());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn removing_the_calendar_or_the_inbox_removes_its_events_grants(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let disconnected_link = insert_link(&pool, owner_id).await;+ let removed_link = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (_, _, disconnected_event_id, _) =+ connected_calendar(&pool, &repo, owner_id, disconnected_link).await;+ let removed_provider = provider_ids(&repo, removed_link).await;+ let removed_event_id = repo+ .upsert_event_fixture(timed_upsert(+ owner_id,+ removed_link,+ removed_provider,+ "[email protected]",+ "Review",+ 1,+ ))+ .await+ .unwrap();+ let channel_id = insert_channel(&pool, owner_id, &[owner_id]).await;+ share_with_channel(&pool, disconnected_event_id, channel_id).await;+ share_with_channel(&pool, removed_event_id, channel_id).await;++ // Turning calendar off for one inbox deletes its events.+ repo.disconnect_provider_calendar(owner_id, disconnected_link)+ .await+ .unwrap()+ .expect("the owner's inbox is disconnectable");+ assert_eq!(granted_event_ids(&pool).await, vec![removed_event_id]);++ // Removing the other inbox cascades to its events.+ sqlx::query!("DELETE FROM email_links WHERE id = $1", removed_link)+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(granted_event_ids(&pool).await, Vec::<Uuid>::new());+}diff --git a/crates/macro_db_client/migrations/20261024085045_calendar_event_channel_grant_cleanup.sql b/crates/macro_db_client/migrations/20261024085045_calendar_event_channel_grant_cleanup.sqlnew file mode 100644index 0000000000..3da31c5d91--- /dev/null+++ b/crates/macro_db_client/migrations/20261024085045_calendar_event_channel_grant_cleanup.sql@@ -0,0 +1,28 @@+-- A calendar event's access grants go with its row, as a form's, a CRM+-- pipeline's and a call's do.+--+-- Sharing an event into a channel writes an entity_access row naming that+-- event. The row is deleted by sync once its last source is gone (a delete+-- through Macro, a cancellation or removal synced from Google or Outlook, a+-- disabled calendar) and by the email_links cascade when the inbox is+-- removed, so the cleanup lives on the row rather than on each of those+-- paths. Ids are never reused, so a grant on a deleted row can never be read+-- again. A cancelled or hidden event keeps its grants: readers already skip+-- them, and the row can come back.++SET LOCAL lock_timeout = '5s';++CREATE FUNCTION delete_calendar_event_entity_access()+ RETURNS TRIGGER+ LANGUAGE PLPGSQL+ AS+$$+ BEGIN+ DELETE FROM entity_access WHERE entity_type = 'calendar_event' AND entity_id = OLD.id;+ RETURN NULL;+ END;+$$;++CREATE TRIGGER calendar_event_entity_access_cleanup+ AFTER DELETE ON calendar_events+ FOR EACH ROW EXECUTE FUNCTION delete_calendar_event_entity_access();diff --git a/crates/macro_db_client/migrations/20261024085050_delete_orphaned_calendar_event_grants.sql b/crates/macro_db_client/migrations/20261024085050_delete_orphaned_calendar_event_grants.sqlnew file mode 100644index 0000000000..1085d64ccd--- /dev/null+++ b/crates/macro_db_client/migrations/20261024085050_delete_orphaned_calendar_event_grants.sql@@ -0,0 +1,40 @@+-- no-transaction++-- Delete the access grants of calendar events that were deleted before+-- calendar_event_entity_access_cleanup. Nothing reads them: every reader joins+-- the event row first. One read finds them (no index leads with entity_type),+-- then each batch commits on its own, so no lock outlives a batch. Each delete+-- rechecks that the event is gone, so a rerun after a failure is safe.+-- Keep this file a single statement: COMMIT inside DO needs a top-level call.+DO $$+DECLARE+ batch_size CONSTANT integer := 1000;+ orphaned bigint[];+ batch_start integer := 1;+ batch_deleted integer;+ deleted bigint := 0;+BEGIN+ SELECT COALESCE(array_agg(grant_row.id ORDER BY grant_row.id), '{}')+ INTO orphaned+ FROM entity_access grant_row+ WHERE grant_row.entity_type = 'calendar_event'+ AND NOT EXISTS (+ SELECT 1 FROM calendar_events event WHERE event.id = grant_row.entity_id+ );+ COMMIT;++ WHILE batch_start <= cardinality(orphaned) LOOP+ DELETE FROM entity_access grant_row+ WHERE grant_row.id = ANY(orphaned[batch_start:batch_start + batch_size - 1])+ AND grant_row.entity_type = 'calendar_event'+ AND NOT EXISTS (+ SELECT 1 FROM calendar_events event WHERE event.id = grant_row.entity_id+ );+ GET DIAGNOSTICS batch_deleted = ROW_COUNT;+ deleted := deleted + batch_deleted;+ COMMIT;+ batch_start := batch_start + batch_size;+ END LOOP;++ RAISE NOTICE 'deleted % access grants of deleted calendar events', deleted;+END $$;diff --git a/docs/guides/add-entity.md b/docs/guides/add-entity.mdindex bafa866045..60ecdf9c2a 100644--- a/docs/guides/add-entity.md+++ b/docs/guides/add-entity.md@@ -88,8 +88,8 @@ migrations, the SQLx cache, and tests.- **Grant cleanup trigger:** `entity_access`, `entity_properties`, `favorite`, andcollab surfaces have no foreign key to your table. Add an `AFTER DELETE` triggerthat deletes the kind's `entity_access` rows, as `database_entities`,- `crm_pipeline_entities`, and `forms` do. Initiatives lack one, so deleting an- owner's account can orphan their grants.+ `crm_pipeline_entities`, `calendar_events`, and `forms` do. Initiatives lack+ one, so deleting an owner's account can orphan their grants.- **Enum values get their own migration.** `ALTER TYPE ... ADD VALUE` cannot beused in the transaction that adds it, and SQLx runs each file in onetransaction. Add the value in one migration and backfill in the next (see