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(auth): stop answering 500 for Gmail links of deleted FusionAuth users (#8411)
teocc512f966b34
diff --git a/Cargo.lock b/Cargo.lockindex 83b0829d1d..43cb4849e5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2154,6 +2154,7 @@ dependencies = ["utoipa","utoipa-swagger-ui","uuid",+ "wiremock","workspace-hack","zeroize",]diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.mdindex 25805e61f7..b6f0ed1ccd 100644--- a/services/authentication_service/AGENTS.md+++ b/services/authentication_service/AGENTS.md@@ -83,6 +83,9 @@ inputs cannot select an agent, and ordinary user credentials remain unattributedreauthentication, while infrastructure failures remain server errors.Deploy grant-refresh support before releasing clients that omit the pre-OAuthdisconnect; older callbacks leave an existing grant unchanged.+- FusionAuth reports a link owner that was deleted as `UserDoesNotExist`. That+ user has no links or grants left, so answer the route's "not linked" outcome+ (404 no grant, 200 for an idempotent removal), not a 500.- The signup allowlist has a temporary Develop-only bypass(`DEVELOPMENT_BYPASS_SIGNUP_ALLOWLIST`) that overrides the allowlist evenwhen present; see `README.md` before changing signup behavior.diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.tomlindex 2226145aa8..321305ebef 100644--- a/services/authentication_service/Cargo.toml+++ b/services/authentication_service/Cargo.toml@@ -190,6 +190,7 @@ database_env_vars = { path = "../../crates/database_env_vars" }cool_asserts = "2"macro_db_migrator = { path = "../../crates/macro_db_migrator" }serde_urlencoded = { workspace = true }+wiremock = { workspace = true }[package.metadata.cargo-machete]ignored = ["async-stripe"]diff --git a/services/authentication_service/src/api/internal.rs b/services/authentication_service/src/api/internal.rsindex 101e0de889..86e2fa8d19 100644--- a/services/authentication_service/src/api/internal.rs+++ b/services/authentication_service/src/api/internal.rs@@ -17,6 +17,9 @@ mod relocate_inbox_grant;mod remove_link;mod revoke_microsoft_grant;+#[cfg(test)]+mod fusionauth_fixture;+pub fn router() -> Router<ApiContext> {Router::new().route("/google_access_token", get(google_access_token::handler))diff --git a/services/authentication_service/src/api/internal/fusionauth_fixture.rs b/services/authentication_service/src/api/internal/fusionauth_fixture.rsnew file mode 100644index 0000000000..eb33c7f413--- /dev/null+++ b/services/authentication_service/src/api/internal/fusionauth_fixture.rs@@ -0,0 +1,42 @@+use fusionauth::FusionAuthClient;+use serde_json::json;+use wiremock::matchers::{method, path, query_param};+use wiremock::{Mock, MockServer, ResponseTemplate};++pub(super) const GMAIL_IDP_NAME: &str = "google_gmail";++/// A FusionAuth with a Gmail identity provider that answers every request about+/// `fusionauth_user_id` the way it does after that user is deleted.+pub(super) async fn without_user(fusionauth_user_id: &str) -> (MockServer, FusionAuthClient) {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/api/identity-provider/search"))+ .and(query_param("name", GMAIL_IDP_NAME))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "identityProviders": [{ "id": "gmail-idp", "name": GMAIL_IDP_NAME }],+ "total": 1+ })))+ .mount(&server)+ .await;+ Mock::given(path("/api/identity-provider/link"))+ .and(query_param("userId", fusionauth_user_id))+ .respond_with(ResponseTemplate::new(400).set_body_json(json!({+ "fieldErrors": { "userId": [{+ "code": "[invalid]userId",+ "message": format!("The [userId] property is not valid. No user exists with an Id [{fusionauth_user_id}].")+ }] },+ "generalErrors": []+ })))+ .mount(&server)+ .await;+ let client = FusionAuthClient::new(+ "api-key".into(),+ "application-id".into(),+ "client-secret".into(),+ server.uri(),+ "http://localhost/callback".into(),+ "google-client-id".into(),+ "google-client-secret".into(),+ );+ (server, client)+}diff --git a/services/authentication_service/src/api/internal/google_access_token.rs b/services/authentication_service/src/api/internal/google_access_token.rsindex 2cc6fc25f4..9c672c7cec 100644--- a/services/authentication_service/src/api/internal/google_access_token.rs+++ b/services/authentication_service/src/api/internal/google_access_token.rs@@ -13,6 +13,9 @@ use std::sync::Arc;use crate::api::context::AuthorizationService;+#[cfg(test)]+mod test;+#[derive(serde::Deserialize, Debug)]pub struct GoogleAccessTokenParams {fusionauth_user_id: String,@@ -54,14 +57,7 @@ async fn get_access_token(// a 500 would surface as a hard login failure.if matches!(e, FusionAuthClientError::NoIdentityProviderFound) {tracing::debug!(error=?e, "no {} identity provider configured", identity_provider_name);- return (- StatusCode::NOT_FOUND,- Json(ErrorResponse {- message: format!("No {} link found for this user", identity_provider_name)- .into(),- }),- )- .into_response();+ return no_link_response(identity_provider_name);}tracing::error!(error=?e, "unable to find idp id for {}", identity_provider_name);(@@ -78,6 +74,15 @@ async fn get_access_token(.get_links(fusionauth_user_id, Some(idp_id.clone())).await.map_err(|e| {+ // The grant's FusionAuth user is gone, so there is no grant.+ if matches!(e, FusionAuthClientError::UserDoesNotExist) {+ tracing::warn!(+ fusionauth_user_id,+ "no fusionauth user for {} grant",+ identity_provider_name+ );+ return no_link_response(identity_provider_name);+ }tracing::error!(error=?e, "error fetching links for userid {} and idp id {}", fusionauth_user_id, idp_id.as_str());(StatusCode::INTERNAL_SERVER_ERROR,@@ -101,14 +106,7 @@ async fn get_access_token(fusionauth_user_id,idp_id.as_str());- (- StatusCode::NOT_FOUND,- Json(ErrorResponse {- message: format!("No {} link found for this user", identity_provider_name)- .into(),- }),- )- .into_response()+ no_link_response(identity_provider_name)})?;// get access token using refresh token@@ -140,3 +138,14 @@ async fn get_access_token().into_response())}++/// The "no grant" answer: callers treat a 404 as a missing grant, not a fault.+fn no_link_response(identity_provider_name: &str) -> Response {+ (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: format!("No {} link found for this user", identity_provider_name).into(),+ }),+ )+ .into_response()+}diff --git a/services/authentication_service/src/api/internal/google_access_token/test.rs b/services/authentication_service/src/api/internal/google_access_token/test.rsnew file mode 100644index 0000000000..7313ad9ba8--- /dev/null+++ b/services/authentication_service/src/api/internal/google_access_token/test.rs@@ -0,0 +1,21 @@+use super::*;+use crate::api::internal::fusionauth_fixture;++#[tokio::test]+async fn a_deleted_user_has_no_google_grant() {+ let (_server, auth_client) = fusionauth_fixture::without_user("deleted-user").await;+ let params = GoogleAccessTokenParams {+ fusionauth_user_id: "deleted-user".into(),+ email: "[email protected]".into(),+ };++ let response = get_access_token(+ Arc::new(auth_client),+ ¶ms,+ fusionauth_fixture::GMAIL_IDP_NAME,+ )+ .await+ .expect_err("a deleted user has no grant to mint a token from");++ assert_eq!(response.status(), StatusCode::NOT_FOUND);+}diff --git a/services/authentication_service/src/api/internal/remove_link.rs b/services/authentication_service/src/api/internal/remove_link.rsindex 1d816315e6..f654a03f2d 100644--- a/services/authentication_service/src/api/internal/remove_link.rs+++ b/services/authentication_service/src/api/internal/remove_link.rs@@ -1,4 +1,5 @@use crate::api::context::{ApiContext, AuthorizationService};+use fusionauth::FusionAuthClient;use fusionauth::error::FusionAuthClientError;use fusionauth::identity_provider::Link;@@ -52,9 +53,23 @@ pub async fn handler(}): extract::Query<RemoveLinkQueryParams>,) -> Result<Response, Response> {tracing::info!("internal_remove_link");- let idp_id = ctx- .auth_client- .get_identity_provider_id_by_name(&idp_name)+ remove_link(+ &ctx.auth_client,+ &fusionauth_user_id,+ &linked_email,+ &idp_name,+ )+ .await+}++async fn remove_link(+ auth_client: &FusionAuthClient,+ fusionauth_user_id: &str,+ linked_email: &str,+ idp_name: &str,+) -> Result<Response, Response> {+ let idp_id = auth_client+ .get_identity_provider_id_by_name(idp_name).await.map_err(|e| match e {FusionAuthClientError::NoIdentityProviderFound => {@@ -81,40 +96,39 @@ pub async fn handler(tracing::trace!("removing link for idp id {}", idp_id);- let links = ctx- .auth_client- .get_links(&fusionauth_user_id, Some(idp_id.clone()))+ let links = match auth_client+ .get_links(fusionauth_user_id, Some(idp_id.clone())).await- .map_err(|e| {+ {+ Ok(links) => links,+ // Deleting a FusionAuth user deletes its links with it.+ Err(FusionAuthClientError::UserDoesNotExist) => Vec::new(),+ Err(e) => {tracing::error!(error=?e, "error fetching links for userid {} and idp id {}", fusionauth_user_id, idp_id.as_str());- (+ return Err((StatusCode::INTERNAL_SERVER_ERROR,Json(ErrorResponse {message: "unable to fetch links".into(),}),)- .into_response()- })?;+ .into_response());+ }+ };// 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 Some(link) = find_idp_link(links, &linked_email) else {+ 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 wedgetracing::warn!(- "no {} link found for user id {} and email {}; treating remove as no-op",+ "no {} link found for user id {}; treating remove as no-op",idp_name,- fusionauth_user_id,- linked_email+ fusionauth_user_id);return Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response());};- ctx.auth_client- .unlink_user(- &fusionauth_user_id,- &idp_id,- &link.identity_provider_user_id,- )+ auth_client+ .unlink_user(fusionauth_user_id, &idp_id, &link.identity_provider_user_id).await.map_err(|e| match e {FusionAuthClientError::NoIdentityProviderFound => {diff --git a/services/authentication_service/src/api/internal/remove_link/test.rs b/services/authentication_service/src/api/internal/remove_link/test.rsindex 3a81d834c7..6b8247f159 100644--- a/services/authentication_service/src/api/internal/remove_link/test.rs+++ b/services/authentication_service/src/api/internal/remove_link/test.rs@@ -1,4 +1,5 @@use super::*;+use crate::api::internal::fusionauth_fixture;use axum::extract::{self, FromRequestParts};use axum::http::Request;use url::Url;@@ -39,6 +40,22 @@ fn find_idp_link_returns_none_when_absent() {assert!(find_idp_link(links, "[email protected]").is_none());}+#[tokio::test]+async fn removing_a_deleted_users_link_succeeds() {+ let (_server, auth_client) = fusionauth_fixture::without_user("deleted-user").await;++ let response = remove_link(+ &auth_client,+ "deleted-user",+ "[email protected]",+ fusionauth_fixture::GMAIL_IDP_NAME,+ )+ .await+ .expect("a deleted user has no link left to remove");++ assert_eq!(response.status(), StatusCode::OK);+}+#[tokio::test]async fn it_deserializes_linked_email_query_param() {let mut url: Url = "https://test.com".parse().unwrap();