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.

feat(email): delete user email links on user deletion (#2213)

Evan Hutnik4a8b8017aff0
diff --git a/infra/packages/shared/src/index.ts b/infra/packages/shared/src/index.ts
index 36377091f5..ac326006d3 100644
--- a/infra/packages/shared/src/index.ts
+++ b/infra/packages/shared/src/index.ts
@@ -42,3 +42,4 @@ export const CLOUDWATCH_KINESIS_STREAM_ROLE_ARN =
export { getMacroApiToken } from './macro_api_token';
export { getMacroNotify } from './macro_notify';
export { getSearchEventQueue } from './search_event_queue';
+export { getLinkManagerQueue } from './link_manager_queue';
diff --git a/infra/packages/shared/src/link_manager_queue.ts b/infra/packages/shared/src/link_manager_queue.ts
new file mode 100644
index 0000000000..1473e9e6e9
--- /dev/null
+++ b/infra/packages/shared/src/link_manager_queue.ts
@@ -0,0 +1,27 @@
+import * as pulumi from '@pulumi/pulumi';
+import { stack } from '../../shared';
+
+export function getLinkManagerQueue(): {
+ linkManagerQueueName: pulumi.Output<string>;
+ linkManagerQueueArn: pulumi.Output<string>;
+} {
+ const emailServiceStack = new pulumi.StackReference(
+ 'link-manager-queue-stack',
+ {
+ name: `macro-inc/email-service/${stack}`,
+ }
+ );
+
+ const linkManagerQueueArn: pulumi.Output<string> = emailServiceStack
+ .getOutput('linkManagerQueueArn')
+ .apply((arn) => arn as string);
+
+ const linkManagerQueueName: pulumi.Output<string> = emailServiceStack
+ .getOutput('linkManagerQueueName')
+ .apply((name) => name as string);
+
+ return {
+ linkManagerQueueName,
+ linkManagerQueueArn,
+ };
+}
diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.ts
index 6fb014597f..98a70d4c48 100644
--- a/infra/stacks/authentication-service/index.ts
+++ b/infra/stacks/authentication-service/index.ts
@@ -2,6 +2,7 @@ import * as aws from '@pulumi/aws';
import * as pulumi from '@pulumi/pulumi';
import {
config,
+ getLinkManagerQueue,
getMacroApiToken,
getMacroNotify,
getSearchEventQueue,
@@ -192,6 +193,8 @@ const { notificationIngressQueueName, notificationIngressQueueArn } =
const { searchEventQueueName, searchEventQueueArn } = getSearchEventQueue();
+const { linkManagerQueueName, linkManagerQueueArn } = getLinkManagerQueue();
+
const service = new AuthenticationService('authentication-service', {
secretKeyArns,
clusterName: fusionAuthClusterName,
@@ -205,7 +208,11 @@ const service = new AuthenticationService('authentication-service', {
isPrivate: false,
healthCheckPath: '/health',
tags,
- queueArns: [notificationIngressQueueArn, searchEventQueueArn],
+ queueArns: [
+ notificationIngressQueueArn,
+ searchEventQueueArn,
+ linkManagerQueueArn,
+ ],
containerEnvVars: [
{ name: 'ENVIRONMENT', value: stack },
{
@@ -289,6 +296,10 @@ const service = new AuthenticationService('authentication-service', {
name: 'SEARCH_EVENT_QUEUE',
value: pulumi.interpolate`${searchEventQueueName}`,
},
+ {
+ name: 'LINK_MANAGER_QUEUE',
+ value: pulumi.interpolate`${linkManagerQueueName}`,
+ },
{
name: 'MACRO_API_TOKEN_ISSUER',
value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 160b6da708..3663156b44 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -105,6 +105,7 @@ sha1 = "0.10.6"
sqlx = { workspace = true }
sqs_client = { path = "../sqs_client", default-features = false, features = [
"search",
+ "email",
] }
teams = { path = "../teams" }
thiserror = { workspace = true }
diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/user/delete_user_webhook.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
index 6f7d2b5dcb..f9ac62dfc9 100644
--- a/rust/cloud-storage/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
@@ -17,6 +17,7 @@ use stripe::CustomerId;
use tracing::Instrument;
use crate::api::context::ApiContext;
+use sqs_client::email::LinkManagerMessage;
/// Delete user webhook
#[tracing::instrument(skip(ctx, req, _internal_access), fields(event_id=req.event.id, email=req.event.user.email,fusionauth_user_id=req.event.user.id))]
@@ -67,7 +68,7 @@ pub async fn handler(
// TODO: should probably make this into an event so we can handle service restarts
// Spawn a single tokio task to perform the user deletion
- tokio::spawn(delete_user(ctx, macro_user, user_ids).in_current_span());
+ tokio::spawn(delete_user(ctx, macro_user, fusionauth_user_id, user_ids).in_current_span());
Ok(StatusCode::OK.into_response())
}
@@ -76,10 +77,28 @@ pub async fn handler(
async fn delete_user(
ctx: ApiContext,
macro_user: macro_db_client::macro_user::MacroUser,
+ fusionauth_user_id: String,
user_ids: Vec<String>,
) -> anyhow::Result<()> {
tracing::info!("deleting user");
+ // Enqueue email link deletion via the link manager queue
+ tokio::spawn({
+ let sqs_client = ctx.sqs_client.clone();
+ let fusionauth_user_id = fusionauth_user_id.clone();
+ async move {
+ let message = LinkManagerMessage::DeleteUser {
+ fusionauth_user_id: fusionauth_user_id.clone(),
+ };
+ if let Err(e) = sqs_client
+ .enqueue_link_manager_notification(message)
+ .await
+ {
+ tracing::error!(error=?e, fusionauth_user_id, "unable to enqueue email link deletion");
+ }
+ }
+ }.in_current_span());
+
tokio::spawn({
let user_ids = user_ids.clone();
let sqs_client = ctx.sqs_client.clone();
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index 73a182c5c2..3c63f57f9f 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -60,6 +60,9 @@ pub struct Config {
/// The search event queue
pub search_event_queue: String,
+ /// The email link manager queue
+ pub link_manager_queue: String,
+
/// The github client id
pub github_client_id: String,
/// The github client secret
@@ -142,6 +145,9 @@ impl Config {
let search_event_queue =
std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
+ let link_manager_queue =
+ std::env::var("LINK_MANAGER_QUEUE").context("LINK_MANAGER_QUEUE must be provided")?;
+
let github_client_id =
std::env::var("GITHUB_CLIENT_ID").context("GITHUB_CLIENT_ID must be provided")?;
let github_client_secret = std::env::var("GITHUB_CLIENT_SECRET")
@@ -178,6 +184,7 @@ impl Config {
document_storage_service_url,
notification_queue,
search_event_queue,
+ link_manager_queue,
environment,
github_client_id,
github_client_secret,
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 8293890437..22dbeffa2f 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -186,7 +186,8 @@ async fn main() -> anyhow::Result<()> {
let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(
&macro_aws_config::get_macro_aws_config().await,
))
- .search_event_queue(&config.search_event_queue);
+ .search_event_queue(&config.search_event_queue)
+ .email_link_manager_queue(&config.link_manager_queue);
tracing::trace!("initialized sqs client");
// Initialize analytics client with configured providers
diff --git a/rust/cloud-storage/email_refresh_handler/src/handler.rs b/rust/cloud-storage/email_refresh_handler/src/handler.rs
index b8f30fab52..0144827e70 100644
--- a/rust/cloud-storage/email_refresh_handler/src/handler.rs
+++ b/rust/cloud-storage/email_refresh_handler/src/handler.rs
@@ -7,7 +7,6 @@ use lambda_runtime::{
};
use macro_env::Environment;
use models_email::email::service::pubsub::LinkManagerMessage;
-use models_email::service::pubsub::LinkManagerOperation;
use sqlx::types::uuid;
use sqlx::{Pool, Postgres, Type};
@@ -70,10 +69,7 @@ async fn send_refresh_messages(ctx: &context::Context) -> Result<(), Error> {
);
for link_id in link_ids {
- let notif = LinkManagerMessage {
- link_id,
- operation: LinkManagerOperation::Refresh,
- };
+ let notif = LinkManagerMessage::Refresh { link_id };
ctx.sqs_client
.enqueue_link_manager_notification(notif)
.await
@@ -106,10 +102,7 @@ async fn send_delete_messages(ctx: &context::Context) -> Result<(), Error> {
);
for link_id in inactive_links {
- let notif = LinkManagerMessage {
- link_id,
- operation: LinkManagerOperation::Delete,
- };
+ let notif = LinkManagerMessage::DeleteLink { link_id };
ctx.sqs_client
.enqueue_link_manager_notification(notif)
.await
diff --git a/rust/cloud-storage/email_service/src/api/email/sync/disable.rs b/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
index 76cb6a2513..55b841d50e 100644
--- a/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
+++ b/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
@@ -7,7 +7,6 @@ use model::response::{EmptyResponse, ErrorResponse};
use model::user::UserContext;
use models_email::email::service::link::Link;
use models_email::email::service::pubsub::LinkManagerMessage;
-use models_email::service::pubsub::LinkManagerOperation;
use strum_macros::AsRefStr;
use thiserror::Error;
@@ -56,10 +55,7 @@ pub async fn disable_handler(
tracing::info!(user_id = %user_context.user_id, "Disable called");
// Enqueue the delete operation to handle cleanup asynchronously
- let message = LinkManagerMessage {
- link_id: link.id,
- operation: LinkManagerOperation::Delete,
- };
+ let message = LinkManagerMessage::DeleteLink { link_id: link.id };
ctx.sqs_client
.enqueue_link_manager_notification(message)
diff --git a/rust/cloud-storage/email_service/src/api/internal/delete_user.rs b/rust/cloud-storage/email_service/src/api/internal/delete_user.rs
index b453ea5d0e..2ca294ea23 100644
--- a/rust/cloud-storage/email_service/src/api/internal/delete_user.rs
+++ b/rust/cloud-storage/email_service/src/api/internal/delete_user.rs
@@ -5,7 +5,6 @@ use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use model::response::ErrorResponse;
use models_email::email::service::pubsub::LinkManagerMessage;
-use models_email::service::pubsub::LinkManagerOperation;
#[tracing::instrument(skip(ctx))]
pub async fn handler(
@@ -31,10 +30,7 @@ pub async fn handler(
})?;
for link in links {
- let message = LinkManagerMessage {
- link_id: link.id,
- operation: LinkManagerOperation::Delete,
- };
+ let message = LinkManagerMessage::DeleteLink { link_id: link.id };
ctx.sqs_client
.enqueue_link_manager_notification(message)
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.rs
index caaca39f34..a90a8ca830 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
@@ -7,7 +7,6 @@ use anyhow::{Context, anyhow};
use models_email::email::service::pubsub::LinkManagerMessage;
use models_email::service::cache::TokenCacheKey;
use models_email::service::link::{Link, UserProvider};
-use models_email::service::pubsub::LinkManagerOperation;
use sqs_client::search::SearchQueueMessage;
use sqs_client::search::email::EmailLinkMessage;
use sqs_worker::cleanup_message;
@@ -17,23 +16,13 @@ pub async fn process_message(
ctx: LinkManagerContext,
message: &aws_sdk_sqs::types::Message,
) -> anyhow::Result<()> {
- // Step 1: Parse the incoming message
let notification_data = extract_message(message)?;
- // Step 2: Fetch the user's link details from the database
- let link =
- email_db_client::links::get::fetch_link_by_id(&ctx.db, notification_data.link_id).await?;
+ match notification_data {
+ LinkManagerMessage::Refresh { link_id } => {
+ let link = get_link_or_skip(&ctx, message, link_id).await?;
+ let Some(link) = link else { return Ok(()) };
- let Some(link) = link else {
- tracing::debug!(link_id=%notification_data.link_id, "Link not found - skipping");
- cleanup_message(&ctx.sqs_worker, message).await?;
- return Ok(());
- };
-
- // Step 3: Execute the appropriate operation
- match notification_data.operation {
- LinkManagerOperation::Refresh => {
- // Access token is required for refresh - fail if we can't get it
let gmail_access_token = fetch_token_or_delete_on_revocation(
&link,
&ctx.redis_client,
@@ -43,9 +32,10 @@ pub async fn process_message(
.await?;
handle_refresh(&ctx, &link, &gmail_access_token).await?;
}
- LinkManagerOperation::Delete => {
- // Access token is optional for delete - we still want to clean up the database
- // even if the user has revoked access. don't delete on revocation -> infinite loop
+ LinkManagerMessage::DeleteLink { link_id } => {
+ 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,
@@ -55,14 +45,29 @@ pub async fn process_message(
.ok();
handle_delete(&ctx, &link, gmail_access_token.as_deref()).await?;
}
+ LinkManagerMessage::DeleteUser { fusionauth_user_id } => {
+ handle_delete_all_user_links(&ctx, &fusionauth_user_id).await?;
+ }
}
- // Step 4: Cleanup the message from the queue
cleanup_message(&ctx.sqs_worker, message).await?;
-
Ok(())
}
+/// Fetches a link by ID, cleaning up the message and returning `None` if not found.
+async fn get_link_or_skip(
+ ctx: &LinkManagerContext,
+ message: &aws_sdk_sqs::types::Message,
+ link_id: uuid::Uuid,
+) -> anyhow::Result<Option<Link>> {
+ let link = email_db_client::links::get::fetch_link_by_id(&ctx.db, link_id).await?;
+ if link.is_none() {
+ tracing::debug!(link_id=%link_id, "Link not found - skipping");
+ cleanup_message(&ctx.sqs_worker, message).await?;
+ }
+ Ok(link)
+}
+
/// 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(
@@ -100,6 +105,42 @@ async fn handle_refresh(
Ok(())
}
+/// Fetches all links for a user and deletes each one via the existing delete handler.
+#[tracing::instrument(skip(ctx), err)]
+async fn handle_delete_all_user_links(
+ ctx: &LinkManagerContext,
+ fusionauth_user_id: &str,
+) -> anyhow::Result<()> {
+ let links =
+ email_db_client::links::get::fetch_links_by_fusionauth_user_id(&ctx.db, fusionauth_user_id)
+ .await
+ .context("Failed to fetch links by fusionauth_user_id")?;
+
+ if links.is_empty() {
+ tracing::info!(fusionauth_user_id, "No email links found for user");
+ return Ok(());
+ }
+
+ tracing::info!(
+ fusionauth_user_id,
+ link_count = links.len(),
+ "Deleting all email links for user"
+ );
+
+ for link in &links {
+ let gmail_access_token =
+ fetch_gmail_access_token_from_link(link, &ctx.redis_client, &ctx.auth_service_client)
+ .await
+ .ok();
+
+ if let Err(e) = handle_delete(ctx, link, gmail_access_token.as_deref()).await {
+ tracing::error!(error=?e, link_id=?link.id, "Failed to delete link during user cleanup");
+ }
+ }
+
+ Ok(())
+}
+
/// notifies downstream dependencies of link deletion, and deletes link (and all data) from database
#[tracing::instrument(skip(ctx, gmail_access_token), fields(link = ?link), err)]
async fn handle_delete(
diff --git a/rust/cloud-storage/email_service/src/util/gmail/auth.rs b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
index 3b472aed97..29826d6f61 100644
--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs
+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
@@ -10,7 +10,7 @@ use model::user::UserContext;
use models_email::email::service::cache::TokenCacheKey;
use models_email::email::service::link::Link;
use models_email::email::service::link::UserProvider;
-use models_email::email::service::pubsub::{LinkManagerMessage, LinkManagerOperation};
+use models_email::email::service::pubsub::LinkManagerMessage;
use models_email::gmail::inbox_sync::KeyMap;
use sqs_client::SQS;
use std::sync::Arc;
@@ -35,9 +35,8 @@ pub async fn fetch_token_or_delete_on_revocation(
);
sqs_client
- .enqueue_link_manager_notification(LinkManagerMessage {
+ .enqueue_link_manager_notification(LinkManagerMessage::DeleteLink {
link_id: link.id,
- operation: LinkManagerOperation::Delete,
})
.await
.inspect_err(|e| {
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260326153502_insights_backfill_cascade.sql b/rust/cloud-storage/macro_db_client/migrations/20260326153502_insights_backfill_cascade.sql
new file mode 100644
index 0000000000..1414ce136b
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260326153502_insights_backfill_cascade.sql
@@ -0,0 +1,6 @@
+-- Add migration script here
+ALTER TABLE public."EmailInsightsBackfillJob"
+ DROP CONSTRAINT "EmailInsightsBackfillJob_userId_fkey",
+ ADD CONSTRAINT "EmailInsightsBackfillJob_userId_fkey"
+ FOREIGN KEY ("userId") REFERENCES public."User"(id)
+ ON UPDATE CASCADE ON DELETE CASCADE;
\ No newline at end of file
diff --git a/rust/cloud-storage/models_email/src/email/service/pubsub.rs b/rust/cloud-storage/models_email/src/email/service/pubsub.rs
index 10cb20bfee..66048288a4 100644
--- a/rust/cloud-storage/models_email/src/email/service/pubsub.rs
+++ b/rust/cloud-storage/models_email/src/email/service/pubsub.rs
@@ -39,22 +39,17 @@ pub enum FailureReason {
InvalidData,
}
-/// The message we send from the email_refresh_handler lambda to the service via SQS to refresh
-/// a user's inbox subscription
+/// The message sent to the link manager SQS queue.
#[derive(Debug, Serialize, Deserialize)]
-pub struct LinkManagerMessage {
- pub link_id: Uuid,
- pub operation: LinkManagerOperation,
-}
-
-/// The operations that can be performed by the LinkManager.
-#[derive(Debug, Serialize, Deserialize)]
-pub enum LinkManagerOperation {
+#[serde(tag = "operation")]
+pub enum LinkManagerMessage {
/// Triggers a contact sync and refreshes the Gmail watch subscription to continue receiving
/// inbox notifications for the user.
- Refresh,
- /// Delete the link from the database.
- Delete,
+ Refresh { link_id: Uuid },
+ /// Delete a single link from the database.
+ DeleteLink { link_id: Uuid },
+ /// Delete all links for a user, identified by fusionauth_user_id.
+ DeleteUser { fusionauth_user_id: String },
}
/// The message we send from the email_scheduled_handler lambda to the service via SQS to trigger
diff --git a/rust/cloud-storage/sqs_client/src/email.rs b/rust/cloud-storage/sqs_client/src/email.rs
index 8f1541d980..81d0a4f8ff 100644
--- a/rust/cloud-storage/sqs_client/src/email.rs
+++ b/rust/cloud-storage/sqs_client/src/email.rs
@@ -1,7 +1,7 @@
use crate::SQS;
use email::domain::ports::EmailMessageEnqueuer;
use models_email::email::service::backfill::BackfillPubsubMessage;
-use models_email::email::service::pubsub::LinkManagerMessage;
+pub use models_email::email::service::pubsub::LinkManagerMessage;
use models_email::service::pubsub::{SFSUploaderMessage, ScheduledPubsubMessage};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
diff --git a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip
index 07bab21e51..e8312a9e46 100644
Binary files a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip differ