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): relocate shared-mailbox Google grant to a dedicated FusionAuth user (#3930)

gbirman0863e6f5d3e1
diff --git a/rust/cloud-storage/.sqlx/query-530eb488100308aa536dfd5e3f626422fd530b64ad8d067c736a9fbf6eba7001.json b/rust/cloud-storage/.sqlx/query-530eb488100308aa536dfd5e3f626422fd530b64ad8d067c736a9fbf6eba7001.json
new file mode 100644
index 0000000000..dcab6b9c64
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-530eb488100308aa536dfd5e3f626422fd530b64ad8d067c736a9fbf6eba7001.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE email_links\n SET fusionauth_user_id = $2, updated_at = NOW()\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "530eb488100308aa536dfd5e3f626422fd530b64ad8d067c736a9fbf6eba7001"
+}
diff --git a/rust/cloud-storage/authentication_service/src/api/internal/mod.rs b/rust/cloud-storage/authentication_service/src/api/internal/mod.rs
index 3f8403e340..1a60e9afa6 100644
--- a/rust/cloud-storage/authentication_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/internal/mod.rs
@@ -10,6 +10,7 @@ use super::user::post_get_names;
// needs to be public in api crate for swagger
mod google_access_token;
mod post_get_existing_users;
+mod relocate_inbox_grant;
mod remove_link;
pub fn router() -> Router<ApiContext> {
@@ -18,4 +19,5 @@ pub fn router() -> Router<ApiContext> {
.route("/get_names", post(post_get_names::handler_internal))
.route("/get_existing_users", get(post_get_existing_users::handler))
.route("/remove_link", delete(remove_link::handler))
+ .route("/relocate_inbox_grant", post(relocate_inbox_grant::handler))
}
diff --git a/rust/cloud-storage/authentication_service/src/api/internal/relocate_inbox_grant.rs b/rust/cloud-storage/authentication_service/src/api/internal/relocate_inbox_grant.rs
new file mode 100644
index 0000000000..502671f6b3
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/internal/relocate_inbox_grant.rs
@@ -0,0 +1,170 @@
+use std::borrow::Cow;
+use std::net::{IpAddr, Ipv4Addr};
+
+use axum::{
+ Json,
+ extract::{self, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use fusionauth::identity_provider::{IdentityProviderLink, LinkUserRequest};
+use macro_middleware::auth::internal_access::ValidInternalKey;
+use model::response::ErrorResponse;
+
+use crate::api::context::ApiContext;
+
+const GMAIL_IDP_NAME: &str = "google_gmail";
+
+#[derive(serde::Deserialize, Debug)]
+pub struct RelocateInboxGrantRequest {
+ /// The shared mailbox address whose grant should move to a dedicated user.
+ pub email: String,
+ /// The connector whose FusionAuth user currently holds the mailbox's Google grant.
+ pub owner_fusionauth_user_id: String,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
+pub struct RelocateInboxGrantResponse {
+ /// The dedicated FusionAuth user that now holds the mailbox grant.
+ pub shared_fusionauth_user_id: String,
+}
+
+/// Provisions a dedicated FusionAuth user for a shared mailbox and relocates the mailbox's
+/// Google grant onto it, so the inbox keeps syncing no matter which connector stays.
+///
+/// A Google identity binds to exactly one FusionAuth user, so the grant is moved by
+/// unlinking it from the owner and re-linking it to the shared user. If the re-link fails
+/// the owner is re-linked (rollback) so the inbox keeps syncing on the original grant.
+/// Idempotent: returns the shared user unchanged when the grant already lives there.
+#[tracing::instrument(skip(ctx, _valid_access))]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ _valid_access: ValidInternalKey,
+ extract::Json(RelocateInboxGrantRequest {
+ email,
+ owner_fusionauth_user_id,
+ }): extract::Json<RelocateInboxGrantRequest>,
+) -> Result<Response, Response> {
+ let auth = &ctx.auth_client;
+ let server_error = |message: &str| -> Response {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+ };
+
+ let idp_id = auth
+ .get_identity_provider_id_by_name(GMAIL_IDP_NAME)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to get identity provider id");
+ server_error("unable to get identity provider id")
+ })?;
+
+ // Get-or-create the dedicated mailbox user. The signup webhook no-ops here because the
+ // verified MacroDB User for this mailbox already exists (created during promotion), so no
+ // Stripe customer is provisioned.
+ let shared_user_id = match auth.get_user_id_by_email(&email).await {
+ Ok(id) => id,
+ Err(fusionauth::error::FusionAuthClientError::UserDoesNotExist) => auth
+ .create_user(
+ fusionauth::user::create::User {
+ email: Cow::Borrowed(&email),
+ password: Cow::Owned(uuid::Uuid::new_v4().to_string()),
+ username: Some(Cow::Borrowed(&email)),
+ },
+ true,
+ IpAddr::V4(Ipv4Addr::LOCALHOST),
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to create shared mailbox user");
+ server_error("unable to create shared mailbox user")
+ })?,
+ Err(e) => {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to look up shared mailbox user");
+ return Err(server_error("unable to look up shared mailbox user"));
+ }
+ };
+
+ // Idempotent: if the grant already lives on the shared user, nothing to do.
+ let shared_links = auth
+ .get_links(&shared_user_id, Some(idp_id.clone()))
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to read shared user links");
+ server_error("unable to read shared user links")
+ })?;
+ if shared_links.iter().any(|l| l.display_name == email) {
+ return Ok((
+ StatusCode::OK,
+ Json(RelocateInboxGrantResponse {
+ shared_fusionauth_user_id: shared_user_id,
+ }),
+ )
+ .into_response());
+ }
+
+ // Capture the grant from the owner before moving it.
+ let owner_links = auth
+ .get_links(&owner_fusionauth_user_id, Some(idp_id.clone()))
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to read owner links");
+ server_error("unable to read owner links")
+ })?;
+ let Some(owner_link) = owner_links.into_iter().find(|l| l.display_name == email) else {
+ tracing::error!(
+ email = %email,
+ owner = %owner_fusionauth_user_id,
+ "relocate_inbox_grant: owner holds no grant for mailbox"
+ );
+ return Err((
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: "owner holds no grant for mailbox".into(),
+ }),
+ )
+ .into_response());
+ };
+ let sub = owner_link.identity_provider_user_id;
+ let token = owner_link.token;
+
+ let link_to = |user_id: &str| LinkUserRequest {
+ identity_provider_link: IdentityProviderLink {
+ display_name: Cow::Owned(email.clone()),
+ identity_provider_id: Cow::Owned(idp_id.clone()),
+ identity_provider_user_id: Cow::Owned(sub.clone()),
+ user_id: Cow::Owned(user_id.to_string()),
+ token: Cow::Owned(token.clone()),
+ },
+ };
+
+ auth.unlink_user(&owner_fusionauth_user_id, &idp_id, &sub)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to unlink owner grant");
+ server_error("unable to unlink owner grant")
+ })?;
+
+ if let Err(e) = auth.link_user(link_to(&shared_user_id)).await {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to link grant to shared user; rolling back to owner");
+ // Roll back so the inbox keeps syncing on the owner's grant rather than ending up
+ // with the grant attached to no one.
+ if let Err(rollback) = auth.link_user(link_to(&owner_fusionauth_user_id)).await {
+ tracing::error!(error=?rollback, "relocate_inbox_grant: rollback re-link to owner also failed; grant is detached");
+ }
+ return Err(server_error("unable to link grant to shared user"));
+ }
+
+ Ok((
+ StatusCode::OK,
+ Json(RelocateInboxGrantResponse {
+ shared_fusionauth_user_id: shared_user_id,
+ }),
+ )
+ .into_response())
+}
diff --git a/rust/cloud-storage/authentication_service_client/src/lib.rs b/rust/cloud-storage/authentication_service_client/src/lib.rs
index 70afd6fcfa..10814a87e2 100644
--- a/rust/cloud-storage/authentication_service_client/src/lib.rs
+++ b/rust/cloud-storage/authentication_service_client/src/lib.rs
@@ -1,5 +1,6 @@
pub mod error;
pub mod google_access_token;
+pub mod relocate_inbox_grant;
pub mod unlink;
pub mod users;
diff --git a/rust/cloud-storage/authentication_service_client/src/relocate_inbox_grant.rs b/rust/cloud-storage/authentication_service_client/src/relocate_inbox_grant.rs
new file mode 100644
index 0000000000..875d29ff72
--- /dev/null
+++ b/rust/cloud-storage/authentication_service_client/src/relocate_inbox_grant.rs
@@ -0,0 +1,63 @@
+use crate::AuthServiceClient;
+use crate::error::{AuthServiceClientError, GenericErrorResponse};
+
+#[derive(serde::Serialize)]
+struct RelocateInboxGrantRequest<'a> {
+ email: &'a str,
+ owner_fusionauth_user_id: &'a str,
+}
+
+#[derive(serde::Deserialize)]
+struct RelocateInboxGrantResponse {
+ shared_fusionauth_user_id: String,
+}
+
+impl AuthServiceClient {
+ /// Provisions a dedicated FusionAuth user for a shared mailbox and relocates the
+ /// mailbox's Google grant onto it (off `owner_fusionauth_user_id`). Returns the shared
+ /// user's id so the caller can re-home the link's `fusionauth_user_id`. Idempotent.
+ #[tracing::instrument(skip(self), err)]
+ pub async fn relocate_inbox_grant(
+ &self,
+ email: &str,
+ owner_fusionauth_user_id: &str,
+ ) -> Result<String, AuthServiceClientError> {
+ let res = self
+ .client
+ .post(format!("{}/internal/relocate_inbox_grant", self.url))
+ .json(&RelocateInboxGrantRequest {
+ email,
+ owner_fusionauth_user_id,
+ })
+ .send()
+ .await
+ .map_err(|e| AuthServiceClientError::RequestBuildError {
+ details: e.to_string(),
+ })?;
+
+ match res.status() {
+ reqwest::StatusCode::OK => {
+ let result = res
+ .json::<RelocateInboxGrantResponse>()
+ .await
+ .map_err(|e| {
+ AuthServiceClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+ Ok(result.shared_fusionauth_user_id)
+ }
+ reqwest::StatusCode::NOT_FOUND => Err(AuthServiceClientError::NotFound),
+ _ => {
+ let body = res.text().await.map_err(|e| {
+ AuthServiceClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+ Err(AuthServiceClientError::Generic(GenericErrorResponse {
+ message: body,
+ }))
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/email_db_client/src/links/update.rs b/rust/cloud-storage/email_db_client/src/links/update.rs
index 60c448ce9d..8f8a355f76 100644
--- a/rust/cloud-storage/email_db_client/src/links/update.rs
+++ b/rust/cloud-storage/email_db_client/src/links/update.rs
@@ -1,6 +1,33 @@
use sqlx::PgPool;
use sqlx::types::Uuid;
+/// Re-homes a link's `fusionauth_user_id`. Used after a shared mailbox's Google grant is
+/// relocated onto a dedicated FusionAuth user so token resolution follows it there.
+#[tracing::instrument(skip(pool), err)]
+pub async fn update_link_fusionauth_user_id(
+ pool: &PgPool,
+ link_id: Uuid,
+ fusionauth_user_id: &str,
+) -> anyhow::Result<()> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE email_links
+ SET fusionauth_user_id = $2, updated_at = NOW()
+ WHERE id = $1
+ "#,
+ link_id,
+ fusionauth_user_id,
+ )
+ .execute(pool)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ anyhow::bail!("no email_links row found for link_id {link_id}");
+ }
+
+ Ok(())
+}
+
/// Updates the sync active status for a link by its ID.
/// Also updates the updated_at timestamp to the current time.
#[tracing::instrument(skip(pool), err)]
diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rs
index fbb3faa51d..cebf2e0bb6 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -385,6 +385,51 @@ pub async fn handler(
.await
.context("Failed to commit shared-inbox promotion transaction")?;
+ // Relocate the mailbox's Google grant onto a dedicated FusionAuth user so the
+ // inbox keeps syncing regardless of which connector stays. Done after the
+ // commit: if relocation fails the inbox keeps working under the original
+ // owner's grant (prior behavior) and the relocation can be retried. Once the
+ // grant has moved, the link row must point at the shared user or token
+ // fetches for this inbox fail, so the update is retried before giving up.
+ match ctx
+ .auth_service_client
+ .relocate_inbox_grant(&linked_email, &existing_link.fusionauth_user_id)
+ .await
+ {
+ Ok(shared_fusionauth_user_id) => {
+ const MAX_LINK_UPDATE_ATTEMPTS: u32 = 3;
+ for attempt in 1..=MAX_LINK_UPDATE_ATTEMPTS {
+ match email_db_client::links::update::update_link_fusionauth_user_id(
+ &ctx.db,
+ promoted.link_id,
+ &shared_fusionauth_user_id,
+ )
+ .await
+ {
+ Ok(()) => break,
+ Err(e) if attempt < MAX_LINK_UPDATE_ATTEMPTS => {
+ tracing::warn!(error=?e, attempt, "Retrying link fusionauth_user_id update after grant relocation");
+ tokio::time::sleep(std::time::Duration::from_millis(
+ 200 * u64::from(attempt),
+ ))
+ .await;
+ }
+ Err(e) => {
+ tracing::error!(
+ error=?e,
+ link_id=%promoted.link_id,
+ shared_fusionauth_user_id=%shared_fusionauth_user_id,
+ "Failed to re-home link fusionauth_user_id after grant relocation; inbox token fetches will fail until the link is re-homed to the shared user"
+ );
+ }
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "Failed to relocate shared-inbox grant; inbox keeps syncing under the original owner's grant");
+ }
+ }
+
return Ok((
StatusCode::OK,
Json(InitResponse {