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-service): Delete link when user revokes Macro access to inbox (#941)

Evan Hutnik8cdccab990ef
diff --git a/rust/cloud-storage/authentication_service/src/api/internal/google_access_token.rs b/rust/cloud-storage/authentication_service/src/api/internal/google_access_token.rs
index 69c1579800..bd9a41efde 100644
--- a/rust/cloud-storage/authentication_service/src/api/internal/google_access_token.rs
+++ b/rust/cloud-storage/authentication_service/src/api/internal/google_access_token.rs
@@ -1,4 +1,5 @@
use authentication_service::service::fusionauth_client::FusionAuthClient;
+use authentication_service::service::fusionauth_client::error::FusionAuthClientError;
use axum::{
Json,
extract::{self, State},
@@ -93,14 +94,12 @@ async fn get_access_token(
.await
.map_err(|e| {
tracing::error!(error=?e, "error fetching access token for userid {}", fusionauth_user_id);
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: format!("unable to fetch {} access token", identity_provider_name)
- .as_str(),
- }),
- )
- .into_response()
+ let status_code = match &e {
+ FusionAuthClientError::InvalidGrant => StatusCode::FORBIDDEN,
+ _ => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ let message = format!("unable to fetch {} access token", identity_provider_name);
+ (status_code, Json(ErrorResponse { message: &message })).into_response()
})?;
Ok((
diff --git a/rust/cloud-storage/authentication_service/src/service/fusionauth_client/error.rs b/rust/cloud-storage/authentication_service/src/service/fusionauth_client/error.rs
index 5d81833668..2a4b53b402 100644
--- a/rust/cloud-storage/authentication_service/src/service/fusionauth_client/error.rs
+++ b/rust/cloud-storage/authentication_service/src/service/fusionauth_client/error.rs
@@ -19,6 +19,8 @@ pub enum FusionAuthClientError {
InvalidRefreshToken,
#[error("an unknown error occurred")]
Generic(GenericErrorResponse),
+ #[error("Invalid grant - user may have revoked access")]
+ InvalidGrant,
}
#[derive(serde::Serialize, Debug)]
diff --git a/rust/cloud-storage/authentication_service/src/service/fusionauth_client/google/oauth.rs b/rust/cloud-storage/authentication_service/src/service/fusionauth_client/google/oauth.rs
index dd88c73683..a485c256bd 100644
--- a/rust/cloud-storage/authentication_service/src/service/fusionauth_client/google/oauth.rs
+++ b/rust/cloud-storage/authentication_service/src/service/fusionauth_client/google/oauth.rs
@@ -83,6 +83,11 @@ pub(in crate::service::fusionauth_client) async fn refresh_google_token(
"failed to refresh Google access token"
);
+ // If the user revoked Macro's access to their account, we get an invalid_grant error here
+ if error_text.contains("invalid_grant") {
+ return Err(FusionAuthClientError::InvalidGrant);
+ }
+
Err(FusionAuthClientError::Generic(GenericErrorResponse {
message: format!(
"Google token refresh failed with status {}: {}",
diff --git a/rust/cloud-storage/authentication_service_client/src/error.rs b/rust/cloud-storage/authentication_service_client/src/error.rs
index db7fd740b5..dc5ca61919 100644
--- a/rust/cloud-storage/authentication_service_client/src/error.rs
+++ b/rust/cloud-storage/authentication_service_client/src/error.rs
@@ -3,6 +3,8 @@
pub enum AuthServiceClientError {
#[error("unauthorized")]
Unauthorized,
+ #[error("forbidden")]
+ Forbidden,
#[error("not found")]
NotFound,
#[error("internal server error: {details}")]
diff --git a/rust/cloud-storage/authentication_service_client/src/google_access_token.rs b/rust/cloud-storage/authentication_service_client/src/google_access_token.rs
index 72767310c5..8b039bcc88 100644
--- a/rust/cloud-storage/authentication_service_client/src/google_access_token.rs
+++ b/rust/cloud-storage/authentication_service_client/src/google_access_token.rs
@@ -32,16 +32,10 @@ impl AuthServiceClient {
Ok(result)
}
- reqwest::StatusCode::UNAUTHORIZED => {
- tracing::error!("unauthorized");
- Err(AuthServiceClientError::Unauthorized)
- }
- reqwest::StatusCode::NOT_FOUND => {
- tracing::error!("not found");
- Err(AuthServiceClientError::NotFound)
- }
+ reqwest::StatusCode::UNAUTHORIZED => Err(AuthServiceClientError::Unauthorized),
+ reqwest::StatusCode::FORBIDDEN => Err(AuthServiceClientError::Forbidden),
+ reqwest::StatusCode::NOT_FOUND => Err(AuthServiceClientError::NotFound),
reqwest::StatusCode::INTERNAL_SERVER_ERROR => {
- tracing::error!("internal server error");
let error_message = res.text().await.map_err(|e| {
AuthServiceClientError::Generic(GenericErrorResponse {
message: e.to_string(),
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 7bbd7e95e3..6c4398eda5 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -110,6 +110,7 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
"email",
"gmail",
"search",
+ "sfs_uploader",
] }
sqs_worker = { path = "../sqs_worker" }
static_file_service_client = { path = "../static_file_service_client" }
diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
index 3e2beb2e41..0e09d22135 100644
--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
@@ -93,7 +93,8 @@ async fn main() -> anyhow::Result<()> {
.email_backfill_queue(&config.backfill_queue)
.email_scheduled_queue(&config.email_scheduled_queue)
.sfs_uploader_queue(&config.sfs_uploader_queue)
- .contacts_queue(&config.contacts_queue);
+ .contacts_queue(&config.contacts_queue)
+ .email_link_manager_queue(&config.link_manager_queue);
let macro_notify_client = macro_notify::MacroNotify::new(
config.notification_queue.clone(),
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs
index 46b9509ad2..a1cd729d61 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs
@@ -3,7 +3,7 @@ use crate::pubsub::backfill::{
update_metadata,
};
use crate::pubsub::context::PubSubContext;
-use crate::util::gmail::auth::fetch_gmail_access_token_from_link;
+use crate::util::gmail::auth::fetch_token_or_delete_on_revocation;
use anyhow::Context;
use models_email::email::service::backfill::{
BackfillJobStatus, BackfillOperation, BackfillPubsubMessage,
@@ -92,15 +92,19 @@ async fn inner_process_message(
}
};
- let access_token =
- fetch_gmail_access_token_from_link(&link, &ctx.redis_client, &ctx.auth_service_client)
- .await
- .map_err(|e| {
- ProcessingError::NonRetryable(DetailedError {
- reason: FailureReason::AccessTokenFetchFailed,
- source: e.context("Failed to fetch access token from link"),
- })
- })?;
+ let access_token = fetch_token_or_delete_on_revocation(
+ &link,
+ &ctx.redis_client,
+ &ctx.auth_service_client,
+ &ctx.sqs_client,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::AccessTokenFetchFailed,
+ source: e.context("Failed to fetch access token from link"),
+ })
+ })?;
match &data.backfill_operation {
BackfillOperation::Init => {
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs
index a6f9dd8470..fdb14f6d4e 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs
@@ -6,8 +6,6 @@ use crate::pubsub::inbox_sync::operations::update_labels::update_labels;
use crate::pubsub::inbox_sync::operations::upsert_message::upsert_message;
use crate::util::redis::rate_limit::RateLimitArgs;
use anyhow::{Context, Result, anyhow};
-use models_email::email::service::cache;
-use models_email::email::service::link::UserProvider;
use models_email::gmail::inbox_sync::{InboxSyncOperation, InboxSyncPubsubMessage};
use models_email::gmail::operations::GmailApiOperation;
use models_email::service::link::Link;
@@ -131,16 +129,11 @@ pub async fn fetch_pubsub_gmail_token(
ctx: &PubSubContext,
link: &Link,
) -> result::Result<String, ProcessingError> {
- let cache_key = cache::TokenCacheKey::new(
- &link.fusionauth_user_id,
- link.macro_id.0.as_ref(),
- UserProvider::Gmail,
- );
-
- let gmail_access_token = crate::util::gmail::auth::fetch_gmail_access_token(
- &cache_key,
+ let gmail_access_token = crate::util::gmail::auth::fetch_token_or_delete_on_revocation(
+ link,
&ctx.redis_client,
&ctx.auth_service_client,
+ &ctx.sqs_client,
)
.await
.map_err(|e| {
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 71ab27fc31..14d6beaff4 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,5 +1,8 @@
use crate::pubsub::link_manager::context::LinkManagerContext;
-use crate::pubsub::util::{fetch_access_token_for_link, fetch_link};
+use crate::pubsub::util::fetch_link;
+use crate::util::gmail::auth::{
+ fetch_gmail_access_token_from_link, fetch_token_or_delete_on_revocation,
+};
use crate::util::sync_contacts::sync_contacts;
use anyhow::{Context, anyhow};
use models_email::email::service::pubsub::LinkManagerMessage;
@@ -24,18 +27,25 @@ pub async fn process_message(
match notification_data.operation {
LinkManagerOperation::Refresh => {
// Access token is required for refresh - fail if we can't get it
- let gmail_access_token =
- fetch_access_token_for_link(&ctx.redis_client, &ctx.auth_service_client, &link)
- .await?;
+ let gmail_access_token = fetch_token_or_delete_on_revocation(
+ &link,
+ &ctx.redis_client,
+ &ctx.auth_service_client,
+ &ctx.sqs_client,
+ )
+ .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
- let gmail_access_token =
- fetch_access_token_for_link(&ctx.redis_client, &ctx.auth_service_client, &link)
- .await
- .ok();
+ // even if the user has revoked access. don't delete on revocation -> infinite loop
+ let gmail_access_token = fetch_gmail_access_token_from_link(
+ &link,
+ &ctx.redis_client,
+ &ctx.auth_service_client,
+ )
+ .await
+ .ok();
handle_delete(&ctx, &link, gmail_access_token.as_deref()).await?;
}
}
diff --git a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
index 6f97e2d51b..dcfdeaabb0 100644
--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
@@ -1,5 +1,6 @@
use crate::pubsub::scheduled::context::ScheduledContext;
-use crate::pubsub::util::{fetch_access_token_for_link, fetch_link};
+use crate::pubsub::util::fetch_link;
+use crate::util::gmail::auth::fetch_gmail_access_token_from_link;
use crate::util::gmail::send::{
cleanup_draft_attachments, fetch_and_attach_draft_attachments, generate_email_threading_headers,
};
@@ -19,7 +20,8 @@ pub async fn process_message(
let link = fetch_link(&ctx.db, data.link_id).await?;
let gmail_access_token =
- fetch_access_token_for_link(&ctx.redis_client, &ctx.auth_service_client, &link).await?;
+ fetch_gmail_access_token_from_link(&link, &ctx.redis_client, &ctx.auth_service_client)
+ .await?;
// Get scheduled message from database
let scheduled_message =
diff --git a/rust/cloud-storage/email_service/src/pubsub/util.rs b/rust/cloud-storage/email_service/src/pubsub/util.rs
index 4d4dffc2cc..9dd2223a69 100644
--- a/rust/cloud-storage/email_service/src/pubsub/util.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/util.rs
@@ -1,13 +1,10 @@
-use crate::util::gmail::auth::fetch_gmail_access_token;
use crate::util::redis::RedisClient;
use crate::util::redis::rate_limit::RateLimitArgs;
use anyhow::anyhow;
-use authentication_service_client::AuthServiceClient;
use connection_gateway_client::client::ConnectionGatewayClient;
/// shared utils across different pubsub workers
use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
use models_email::gmail::operations::GmailApiOperation;
-use models_email::service::cache::TokenCacheKey;
use models_email::service::link::Link;
use sqlx::PgPool;
use uuid::Uuid;
@@ -95,26 +92,6 @@ pub async fn cg_refresh_email(client: &ConnectionGatewayClient, macro_id: &str,
}
}
-pub async fn fetch_access_token_for_link(
- redis_client: &RedisClient,
- auth_service_client: &AuthServiceClient,
- link: &Link,
-) -> anyhow::Result<String> {
- let cache_key = TokenCacheKey {
- fusion_user_id: link.fusionauth_user_id.clone(),
- macro_id: link.macro_id.to_string(),
- provider: link.provider,
- };
-
- fetch_gmail_access_token(&cache_key, redis_client, auth_service_client)
- .await
- .map_err(|e| {
- let error_message = "Unable to get Gmail access token";
- tracing::error!(error = ?e, cache_key = ?cache_key, error_message);
- anyhow!(error_message)
- })
-}
-
/// Fetches the Link details from the database using the link_id from the notification.
pub async fn fetch_link(db: &PgPool, link_id: Uuid) -> anyhow::Result<Link> {
email_db_client::links::get::fetch_link_by_id(db, link_id)
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 f1df922eaf..7f25b239ab 100644
--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs
+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
@@ -1,6 +1,6 @@
use crate::util::redis::RedisClient;
use anyhow::Context;
-use authentication_service_client::AuthServiceClient;
+use authentication_service_client::{AuthServiceClient, error::AuthServiceClientError};
use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
@@ -10,9 +10,75 @@ 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::gmail::inbox_sync::KeyMap;
+use sqs_client::SQS;
use std::sync::Arc;
+/// Fetches Gmail access token from link and triggers link deletion if access was revoked.
+/// This should be used by pubsub handlers where we want to automatically clean up revoked links.
+/// API handlers should use `fetch_gmail_access_token_from_link` directly instead.
+#[tracing::instrument(skip(redis_client, auth_service_client, sqs_client))]
+pub async fn fetch_token_or_delete_on_revocation(
+ link: &Link,
+ redis_client: &RedisClient,
+ auth_service_client: &AuthServiceClient,
+ sqs_client: &SQS,
+) -> anyhow::Result<String> {
+ match fetch_gmail_access_token_from_link(link, redis_client, auth_service_client).await {
+ Ok(token) => Ok(token),
+ Err(e) if is_forbidden_error(&e) => {
+ tracing::warn!(
+ link_id = %link.id,
+ fusionauth_user_id = %link.fusionauth_user_id,
+ "User revoked access to Gmail - enqueueing link deletion"
+ );
+
+ sqs_client
+ .enqueue_link_manager_notification(LinkManagerMessage {
+ link_id: link.id,
+ operation: LinkManagerOperation::Delete,
+ })
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, link_id=%link.id, "Failed to enqueue link deletion after detecting revoked access");
+ })
+ .ok();
+
+ Err(e)
+ }
+ Err(e) => Err(e),
+ }
+}
+
+/// Checks if an error chain contains a Forbidden error from the auth service
+fn is_forbidden_error(e: &anyhow::Error) -> bool {
+ e.chain().any(|cause| {
+ cause
+ .downcast_ref::<AuthServiceClientError>()
+ .map(|e| matches!(e, AuthServiceClientError::Forbidden))
+ .unwrap_or(false)
+ })
+}
+
+/// Creates a cache key using a link, then fetches access token. Returns error if access token can't
+/// be fetched.
+pub async fn fetch_gmail_access_token_from_link(
+ link: &Link,
+ redis_client: &RedisClient,
+ auth_service_client: &AuthServiceClient,
+) -> anyhow::Result<String> {
+ // Create the cache key using the extracted email
+ let key = TokenCacheKey::new(
+ &link.fusionauth_user_id,
+ link.macro_id.0.as_ref(),
+ link.provider,
+ );
+
+ fetch_gmail_access_token(&key, redis_client, auth_service_client).await
+}
+
+/// fetches a user's gmail token using the user_context from the API request
pub async fn fetch_gmail_token_usercontext_response(
user_context: &UserContext,
redis_client: &RedisClient,
@@ -39,22 +105,6 @@ pub async fn fetch_gmail_token_usercontext_response(
})
}
-/// Creates a cache key using a link, then fetches access token
-pub async fn fetch_gmail_access_token_from_link(
- link: &Link,
- redis_client: &RedisClient,
- auth_service_client: &AuthServiceClient,
-) -> anyhow::Result<String> {
- // Create the cache key using the extracted email
- let key = TokenCacheKey::new(
- &link.fusionauth_user_id,
- link.macro_id.0.as_ref(),
- link.provider,
- );
-
- fetch_gmail_access_token(&key, redis_client, auth_service_client).await
-}
-
/// Fetches the gmail access token, first looking in the redis cache then hitting the auth service
pub async fn fetch_gmail_access_token(
key: &TokenCacheKey,
@@ -74,10 +124,9 @@ pub async fn fetch_gmail_access_token(
let fetched_token = auth_service_client
.get_google_access_token(&key.fusion_user_id, &key.macro_id)
.await
- .map_err(|e| {
- anyhow::anyhow!(
- "Failed to get Google access token from auth service: {}. TokenCacheKey: {:?}",
- e,
+ .with_context(|| {
+ format!(
+ "Failed to get Google access token from auth service. TokenCacheKey: {:?}",
key
)
})?;
diff --git a/rust/cloud-storage/sqs_client/src/email.rs b/rust/cloud-storage/sqs_client/src/email.rs
index d1703e2560..b61193162d 100644
--- a/rust/cloud-storage/sqs_client/src/email.rs
+++ b/rust/cloud-storage/sqs_client/src/email.rs
@@ -19,6 +19,7 @@ impl SQS {
self
}
+ #[cfg(feature = "sfs_uploader")]
pub fn sfs_uploader_queue(mut self, email_sfs_uploader_queue: &str) -> Self {
self.email_sfs_uploader_queue = Some(email_sfs_uploader_queue.to_string());
self
@@ -62,6 +63,7 @@ impl SQS {
}
/// Sends a notification message to the email sfs uploader queue
+ #[cfg(feature = "sfs_uploader")]
#[tracing::instrument(skip(self))]
pub async fn enqueue_email_sfs_uploader_message(
&self,
@@ -134,6 +136,7 @@ pub async fn enqueue_scheduled_message(
Ok(())
}
+#[cfg(feature = "sfs_uploader")]
#[tracing::instrument(skip(sqs_client))]
pub async fn enqueue_sfs_uploader_message(
sqs_client: &aws_sdk_sqs::Client,