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(email): stop inbox reconnect from self-deleting the link (#4093)
gbirmanf2d6b87f56ec
diff --git a/rust/cloud-storage/.sqlx/query-0b25861527e4ecd715a759799e7dc2d43865571925e95582689df12c3b02322a.json b/rust/cloud-storage/.sqlx/query-2237ef2e86f1c48cef5ebd2fe896c84624135cd808de26975538992ca7d3b69f.jsonsimilarity index 91%rename from rust/cloud-storage/.sqlx/query-0b25861527e4ecd715a759799e7dc2d43865571925e95582689df12c3b02322a.jsonrename to rust/cloud-storage/.sqlx/query-2237ef2e86f1c48cef5ebd2fe896c84624135cd808de26975538992ca7d3b69f.jsonindex 9263cd881c..ee636ccb21 100644--- a/rust/cloud-storage/.sqlx/query-0b25861527e4ecd715a759799e7dc2d43865571925e95582689df12c3b02322a.json+++ b/rust/cloud-storage/.sqlx/query-2237ef2e86f1c48cef5ebd2fe896c84624135cd808de26975538992ca7d3b69f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE fusionauth_user_id = $1\n AND created_at > NOW() - INTERVAL '24 hours'\n ORDER BY created_at DESC\n ",+ "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE fusionauth_user_id = $1\n AND created_at > NOW() - INTERVAL '24 hours'\n AND status NOT IN ('Cancelled', 'Failed')\n ORDER BY created_at DESC\n ","describe": {"columns": [{@@ -79,5 +79,5 @@false]},- "hash": "0b25861527e4ecd715a759799e7dc2d43865571925e95582689df12c3b02322a"+ "hash": "2237ef2e86f1c48cef5ebd2fe896c84624135cd808de26975538992ca7d3b69f"}diff --git a/rust/cloud-storage/email_db_client/src/backfill/job/get.rs b/rust/cloud-storage/email_db_client/src/backfill/job/get.rsindex 73c3bee550..0d96d01ee4 100644--- a/rust/cloud-storage/email_db_client/src/backfill/job/get.rs+++ b/rust/cloud-storage/email_db_client/src/backfill/job/get.rs@@ -132,7 +132,8 @@ pub async fn get_recent_jobs_by_fusionauth_user_id(pool: &PgPool,fusionauth_user_id: &str,) -> anyhow::Result<Vec<service::backfill::BackfillJob>> {- // Query for all jobs created within the last 24 hours for the specified link+ // Jobs created in the last 24h for this user, excluding terminal (Cancelled/Failed)+ // statuses, used for the connect rate limit.let records = sqlx::query_as!(db::backfill::BackfillJob,r#"@@ -149,6 +150,7 @@ pub async fn get_recent_jobs_by_fusionauth_user_id(FROM email_backfill_jobsWHERE fusionauth_user_id = $1AND created_at > NOW() - INTERVAL '24 hours'+ AND status NOT IN ('Cancelled', 'Failed')ORDER BY created_at DESC"#,fusionauth_user_id@@ -161,3 +163,6 @@ pub async fn get_recent_jobs_by_fusionauth_user_id(Ok(jobs)}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/email_db_client/src/backfill/job/get/test.rs b/rust/cloud-storage/email_db_client/src/backfill/job/get/test.rsnew file mode 100644index 0000000000..3541d3a238--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/backfill/job/get/test.rs@@ -0,0 +1,51 @@+use super::get_recent_jobs_by_fusionauth_user_id;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_email::email::db::backfill::BackfillJobStatus as DbStatus;+use models_email::email::service::backfill::BackfillJobStatus;+use sqlx::types::Uuid;+use sqlx::{Pool, Postgres};++async fn insert_job(pool: &Pool<Postgres>, fusion: &str, status: DbStatus, hours_ago: i32) {+ sqlx::query!(+ r#"INSERT INTO email_backfill_jobs (id, fusionauth_user_id, status, created_at)+ VALUES ($1, $2, $3::email_backfill_job_status, NOW() - ($4::int * INTERVAL '1 hour'))"#,+ Uuid::new_v4(),+ fusion,+ status as _,+ hours_ago,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn recent_jobs_excludes_terminal_and_old_and_other_users(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ const FUSION: &str = "fusion-rate-limit-user";+ const OTHER: &str = "fusion-other-user";++ // Recent, non-terminal → counted.+ insert_job(&pool, FUSION, DbStatus::Init, 1).await;+ insert_job(&pool, FUSION, DbStatus::InProgress, 2).await;+ insert_job(&pool, FUSION, DbStatus::Complete, 3).await;+ // Recent but terminal → excluded so connect/disconnect churn does not count.+ insert_job(&pool, FUSION, DbStatus::Cancelled, 1).await;+ insert_job(&pool, FUSION, DbStatus::Failed, 2).await;+ // Older than the 24h window → excluded.+ insert_job(&pool, FUSION, DbStatus::Init, 25).await;+ // Different user → excluded.+ insert_job(&pool, OTHER, DbStatus::Init, 1).await;++ let jobs = get_recent_jobs_by_fusionauth_user_id(&pool, FUSION).await?;++ assert_eq!(jobs.len(), 3);+ assert!(jobs.iter().all(|j| j.fusionauth_user_id == FUSION));+ assert!(jobs.iter().all(|j| !matches!(+ j.status,+ BackfillJobStatus::Cancelled | BackfillJobStatus::Failed+ )));++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rsindex 516529d65a..a30f7b1924 100644--- a/rust/cloud-storage/email_service/src/api/email/init.rs+++ b/rust/cloud-storage/email_service/src/api/email/init.rs@@ -17,6 +17,7 @@ use model::user::axum_extractor::MacroUserExtractor;use models_email::email::service::backfill::{BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, InitPayload, JobScopedPayload,};+use models_email::gmail::error::GmailError;use models_email::service::link;use models_email::service::link::Link;use strum_macros::AsRefStr;@@ -160,7 +161,7 @@ pub async fn handler(let pg_repo = EmailPgRepo::new(ctx.db.clone());- let (link, email_address) = if let Some(link_id) = link_id {+ let (link, _email_address) = if let Some(link_id) = link_id {let in_progress =macro_db_client::in_progress_user_link::get_in_progress_user_link(&ctx.db, &link_id).await@@ -270,9 +271,11 @@ pub async fn handler(.context("child macro user disappeared before self-link bootstrap")?.to_string();+ enforce_backfill_rate_limit(&ctx.db, &child_fusion_id, &linked_email).await?;+let gmail_token =fetch_gmail_token_for_email(&ctx, &child_fusion_id, &linked_email).await?;- let watch_response = ctx.gmail_client.register_watch(&gmail_token).await?;+ let watch_response = register_watch_recovering(&ctx.gmail_client, &gmail_token).await?;// All writes commit atomically so a partial failure leaves no dangling link,// edge, or consumed in_progress row.@@ -446,10 +449,13 @@ pub async fn handler(.into_response());}+ enforce_backfill_rate_limit(&ctx.db, &user_context.fusion_user_id, &linked_email)+ .await?;+let gmail_token =fetch_gmail_token_for_email(&ctx, &user_context.fusion_user_id, &linked_email).await?;- let watch_response = ctx.gmail_client.register_watch(&gmail_token).await?;+ let watch_response = register_watch_recovering(&ctx.gmail_client, &gmail_token).await?;let mut tx = ctx.db@@ -496,6 +502,8 @@ pub async fn handler(let email = extract_email_with_response(&user_context.user_id).map_err(|_| InitError::BadRequest("Failed to extract email".to_string()))?;+ enforce_backfill_rate_limit(&ctx.db, &user_context.fusion_user_id, &email).await?;+let gmail_token = email_service::util::gmail::auth::fetch_gmail_token_no_cache(&user_context,&ctx.redis_client,@@ -504,7 +512,7 @@ pub async fn handler(.await.map_err(|_| InitError::BadRequest("Failed to fetch Gmail token".to_string()))?;- let watch_response = ctx.gmail_client.register_watch(&gmail_token).await?;+ let watch_response = register_watch_recovering(&ctx.gmail_client, &gmail_token).await?;let mut tx = ctx.db@@ -528,23 +536,6 @@ pub async fn handler((link, email)};- // users can only have 3 jobs within past 24h and one backfill job per link in progress at a time- let recent_jobs = email_db_client::backfill::job::get::get_recent_jobs_by_fusionauth_user_id(- &ctx.db,- &link.fusionauth_user_id,- )- .await- .context("Failed to fetch jobs by macro id")?;-- if recent_jobs.len() >= 3 && !email_address.ends_with("@macro.com") {- tracing::info!(user_id = %user_context.user_id, "Too many jobs error");- email_db_client::links::delete::delete_link_by_id(&ctx.db, link.id)- .await- .context("Failed to delete link")?;-- return Err(InitError::TooManyJobs);- }-// Record link creation in history table for tracking (best-effort)email_db_client::links_history::insert::insert_email_link_history(&ctx.db,@@ -615,6 +606,51 @@ pub async fn handler(.into_response())}+/// Rejects a connect when this Gmail identity already has 3+ recent backfill jobs in+/// the last 24h (`@macro.com` is exempt). Enforced before the link and Gmail watch are+/// created so a rejected connect never has to tear down a half-provisioned inbox.+async fn enforce_backfill_rate_limit(+ db: &sqlx::PgPool,+ fusion_user_id: &str,+ email_address: &str,+) -> Result<(), InitError> {+ let recent_jobs = email_db_client::backfill::job::get::get_recent_jobs_by_fusionauth_user_id(+ db,+ fusion_user_id,+ )+ .await+ .context("Failed to fetch recent backfill jobs")?;++ if recent_jobs.len() >= 3 && !email_address.ends_with("@macro.com") {+ return Err(InitError::TooManyJobs);+ }++ Ok(())+}++/// Registers a Gmail watch, recovering from the one-watch-per-mailbox limit. A watch+/// left over from a prior connect (e.g. a disconnect that could not reach Gmail to stop+/// it) makes a fresh registration fail with 400 "Only one user push notification client+/// allowed ... call /stop then try again". On that error we stop the stale watch and+/// retry once.+async fn register_watch_recovering(+ client: &gmail_client::GmailClient,+ access_token: &str,+) -> Result<models_email::gmail::history::WatchResponse, InitError> {+ match client.register_watch(access_token).await {+ Ok(response) => Ok(response),+ Err(GmailError::Conflict(_)) => {+ tracing::warn!("Stale Gmail watch blocks registration; stopping it and retrying");+ client+ .stop_watch(access_token)+ .await+ .context("Failed to stop stale Gmail watch before retry")?;+ Ok(client.register_watch(access_token).await?)+ }+ Err(e) => Err(e.into()),+ }+}+/// Fetches a Gmail access token scoped to a specific linked email. Use this instead/// of going through the `UserContext`-keyed path when the target inbox is not the/// JWT subject's primary email.diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rsindex d17585be0d..9c1de009f6 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs@@ -1,7 +1,7 @@use crate::pubsub::link_manager::context::LinkManagerContext;use crate::pubsub::util::cg_refresh_email;use crate::util::gmail::auth::{- fetch_gmail_access_token_from_link, fetch_token_or_delete_on_revocation,+ fetch_gmail_access_token_from_link, fetch_token_or_delete_on_revocation, is_forbidden_error,};use crate::util::sync_contacts::sync_contacts;use anyhow::{Context, anyhow};@@ -42,13 +42,7 @@ pub async fn process_message(let link = get_link_or_skip(&ctx, message, link_id).await?;let Some(link) = link else { return Ok(()) };- let gmail_access_token = fetch_gmail_access_token_from_link(- &link,- &ctx.redis_client,- &ctx.auth_service_client,- )- .await- .ok();+ let gmail_access_token = fetch_teardown_token(&ctx, &link).await;handle_delete(&ctx, &link, gmail_access_token.as_deref(), &deletion_reason).await?;}LinkManagerMessage::DeleteUser { fusionauth_user_id } => {@@ -74,6 +68,38 @@ async fn get_link_or_skip(Ok(link)}+/// Best-effort token fetch for stopping a Gmail watch during link teardown. A transient+/// auth-service failure would otherwise drop the stop silently and leave the watch+/// running, so retry a few times. A revoked grant (Forbidden) can never yield a token,+/// so don't retry it — the watch then lingers until Gmail expires it or the next connect+/// stops it.+async fn fetch_teardown_token(ctx: &LinkManagerContext, link: &Link) -> Option<String> {+ const MAX_ATTEMPTS: u32 = 3;++ for attempt in 1..=MAX_ATTEMPTS {+ match fetch_gmail_access_token_from_link(link, &ctx.redis_client, &ctx.auth_service_client)+ .await+ {+ Ok(token) => return Some(token),+ Err(e) if is_forbidden_error(&e) => {+ tracing::warn!(error=?e, link_id=%link.id, "Gmail access revoked; cannot stop watch (it will expire on its own)");+ return None;+ }+ Err(e) if attempt < MAX_ATTEMPTS => {+ tracing::warn!(error=?e, attempt, link_id=%link.id, "Transient failure fetching token to stop Gmail watch; retrying");+ tokio::time::sleep(std::time::Duration::from_millis(200 * u64::from(attempt)))+ .await;+ }+ Err(e) => {+ tracing::warn!(error=?e, link_id=%link.id, "Could not fetch token to stop Gmail watch after retries; watch will linger until it expires or the next connect stops it");+ return None;+ }+ }+ }++ None+}+/// Handles the Refresh operation: renews Gmail watch subscription and syncs contacts.#[tracing::instrument(skip(ctx, gmail_access_token), fields(link = ?link), err)]async fn handle_refresh(@@ -134,10 +160,7 @@ async fn handle_delete_all_user_links();for link in &links {- let gmail_access_token =- fetch_gmail_access_token_from_link(link, &ctx.redis_client, &ctx.auth_service_client)- .await- .ok();+ let gmail_access_token = fetch_teardown_token(ctx, link).await;if let Err(e) = handle_delete(ctx,diff --git a/rust/cloud-storage/email_service/src/util/gmail/auth.rs b/rust/cloud-storage/email_service/src/util/gmail/auth.rsindex 7f8d3563f4..edc38dd314 100644--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs@@ -53,7 +53,7 @@ pub async fn fetch_token_or_delete_on_revocation(}/// Checks if an error chain contains a Forbidden error from the auth service-fn is_forbidden_error(e: &anyhow::Error) -> bool {+pub(crate) fn is_forbidden_error(e: &anyhow::Error) -> bool {e.chain().any(|cause| {cause.downcast_ref::<AuthServiceClientError>()diff --git a/rust/cloud-storage/gmail_client/src/watch.rs b/rust/cloud-storage/gmail_client/src/watch.rsindex ebf2817870..90f92f91b8 100644--- a/rust/cloud-storage/gmail_client/src/watch.rs+++ b/rust/cloud-storage/gmail_client/src/watch.rs@@ -40,6 +40,17 @@ pub(crate) async fn register_watch(.text().await.unwrap_or_else(|_| "Failed to read error body".to_string());++ // Gmail permits only one active push channel per mailbox; a watch left over from a+ // prior registration makes a fresh watch fail with a 400 carrying this message. Map+ // it to a typed Conflict so callers can stop the stale watch and retry rather than+ // matching the response body themselves.+ if status == reqwest::StatusCode::BAD_REQUEST+ && error_body.contains("push notification client allowed")+ {+ return Err(GmailError::Conflict(error_body));+ }+return Err(GmailError::ApiError(format!("({}): {}",status, error_body