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.

fix: remove_link unlinks correct FA IdP link for secondary inboxes (#3814)

gbirman07437e176f36
diff --git a/rust/cloud-storage/authentication_service/src/api/internal/remove_link.rs b/rust/cloud-storage/authentication_service/src/api/internal/remove_link.rs
index 405f9f7760..0ef93b2fae 100644
--- a/rust/cloud-storage/authentication_service/src/api/internal/remove_link.rs
+++ b/rust/cloud-storage/authentication_service/src/api/internal/remove_link.rs
@@ -1,5 +1,6 @@
use crate::api::context::ApiContext;
use fusionauth::error::FusionAuthClientError;
+use fusionauth::identity_provider::Link;
use axum::{
Json,
@@ -10,13 +11,25 @@ use axum::{
use macro_middleware::auth::internal_access::ValidInternalKey;
use model::response::{EmptyResponse, ErrorResponse};
+#[cfg(test)]
+mod test;
+
#[derive(serde::Deserialize, Debug)]
pub struct RemoveLinkQueryParams {
pub fusionauth_user_id: String,
- pub macro_id: String,
+ pub linked_email: String,
pub idp_name: String,
}
+/// Selects the IdP link to remove by matching its display name against the linked email.
+///
+/// A FusionAuth user can hold several links to the same identity provider, one per email
+/// address (e.g. a primary inbox plus delegated/secondary inboxes), so the link must be
+/// selected by the linked email rather than derived from the owner's macro_id.
+fn find_idp_link(links: Vec<Link>, linked_email: &str) -> Option<Link> {
+ links.into_iter().find(|l| l.display_name == linked_email)
+}
+
/// Removes a link for a user by the idp name
#[utoipa::path(
delete,
@@ -34,7 +47,7 @@ pub async fn handler(
_valid_access: ValidInternalKey,
extract::Query(RemoveLinkQueryParams {
fusionauth_user_id,
- macro_id,
+ linked_email,
idp_name,
}): extract::Query<RemoveLinkQueryParams>,
) -> Result<Response, Response> {
@@ -83,27 +96,18 @@ pub async fn handler(
.into_response()
})?;
- let email = macro_id.replace("macro|", "");
-
// a fusionauth user can have multiple links to the same identity provider with different email
// addresses, but can only have one link with a given email
- let link = links
- .into_iter()
- .find(|l| l.display_name == email)
- .ok_or_else(|| {
- tracing::error!(
- "link not found for user id {} and idp id {}",
- fusionauth_user_id,
- idp_id.as_str()
- );
- (
- StatusCode::NOT_FOUND,
- Json(ErrorResponse {
- message: format!("No {} link found for this user", idp_name).into(),
- }),
- )
- .into_response()
- })?;
+ let Some(link) = find_idp_link(links, &linked_email) else {
+ // the link is already gone; treat removal as an idempotent no-op so retries don't wedge
+ tracing::warn!(
+ "no {} link found for user id {} and email {}; treating remove as no-op",
+ idp_name,
+ fusionauth_user_id,
+ linked_email
+ );
+ return Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response());
+ };
ctx.auth_client
.unlink_user(
diff --git a/rust/cloud-storage/authentication_service/src/api/internal/remove_link/test.rs b/rust/cloud-storage/authentication_service/src/api/internal/remove_link/test.rs
new file mode 100644
index 0000000000..3a81d834c7
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/internal/remove_link/test.rs
@@ -0,0 +1,64 @@
+use super::*;
+use axum::extract::{self, FromRequestParts};
+use axum::http::Request;
+use url::Url;
+
+fn link(display_name: &str, idp_user_id: &str) -> Link {
+ Link {
+ display_name: display_name.to_string(),
+ identity_provider_id: "idp".to_string(),
+ identity_provider_name: "google_gmail".to_string(),
+ identity_provider_type: "Google".to_string(),
+ identity_provider_user_id: idp_user_id.to_string(),
+ insert_instant: 0,
+ last_login_instant: 0,
+ tenant_id: "tenant".to_string(),
+ token: "token".to_string(),
+ user_id: "user".to_string(),
+ }
+}
+
+#[test]
+fn find_idp_link_selects_secondary_inbox_not_owner_primary() {
+ let links = vec![
+ link("[email protected]", "google-primary"),
+ link("[email protected]", "google-secondary"),
+ ];
+
+ let found =
+ find_idp_link(links, "[email protected]").expect("secondary inbox link should be found");
+
+ assert_eq!(found.display_name, "[email protected]");
+ assert_eq!(found.identity_provider_user_id, "google-secondary");
+}
+
+#[test]
+fn find_idp_link_returns_none_when_absent() {
+ let links = vec![link("[email protected]", "google-primary")];
+
+ assert!(find_idp_link(links, "[email protected]").is_none());
+}
+
+#[tokio::test]
+async fn it_deserializes_linked_email_query_param() {
+ let mut url: Url = "https://test.com".parse().unwrap();
+ url.query_pairs_mut()
+ .append_pair("fusionauth_user_id", "fa-user-1")
+ .append_pair("linked_email", "[email protected]")
+ .append_pair("idp_name", "google_gmail");
+
+ let (mut parts, ()) = Request::builder()
+ .uri(url.as_str())
+ .body(())
+ .unwrap()
+ .into_parts();
+
+ let extract::Query(params) =
+ extract::Query::<RemoveLinkQueryParams>::from_request_parts(&mut parts, &())
+ .await
+ .expect("query params should deserialize");
+
+ assert_eq!(params.fusionauth_user_id, "fa-user-1");
+ assert_eq!(params.linked_email, "[email protected]");
+ assert_eq!(params.idp_name, "google_gmail");
+}
diff --git a/rust/cloud-storage/authentication_service_client/src/unlink.rs b/rust/cloud-storage/authentication_service_client/src/unlink.rs
index b1ee377625..cb8ce8ea96 100644
--- a/rust/cloud-storage/authentication_service_client/src/unlink.rs
+++ b/rust/cloud-storage/authentication_service_client/src/unlink.rs
@@ -7,14 +7,14 @@ impl AuthServiceClient {
pub async fn remove_link(
&self,
fusionauth_user_id: &str,
- macro_id: &str,
+ linked_email: &str,
idp_name: &str,
) -> Result<(), AuthServiceClientError> {
let res = self
.client
.delete(format!("{}/internal/remove_link", self.url))
.query(&[("fusionauth_user_id", fusionauth_user_id)])
- .query(&[("macro_id", macro_id)])
+ .query(&[("linked_email", linked_email)])
.query(&[("idp_name", idp_name)])
.send()
.await
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 3cbeded2e2..00324f3f5c 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
@@ -197,18 +197,17 @@ async fn handle_delete(
tracing::debug!("Skipping Gmail stop_watch - no access token available");
}
- // remove google fusionauth link with gmail inbox permissions
- let _ = ctx
- .auth_service_client
+ // remove google fusionauth link with gmail inbox permissions. must succeed before we delete
+ // the email_links row below, otherwise a failure leaves a stale FA IdP link with no macrodb
+ // counterpart (and the message is retried instead).
+ ctx.auth_service_client
.remove_link(
&link.fusionauth_user_id,
- link.macro_id.as_ref(),
+ link.email_address.0.as_ref(),
"google_gmail",
)
.await
- .inspect_err(|e| {
- tracing::error!(error=?e, "unable to unlink idp");
- });
+ .context("Failed to remove FusionAuth IdP link")?;
// inform search of deletion so it can wipe the email records from OS
ctx.sqs_client