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): deactivate shared-mailbox FusionAuth stubs and align their ids (#4006)

gbirmaned451b0e833b
diff --git a/rust/cloud-storage/authentication_service/src/api/internal/delete_inbox_grant_user.rs b/rust/cloud-storage/authentication_service/src/api/internal/delete_inbox_grant_user.rs
new file mode 100644
index 0000000000..3f73495914
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/internal/delete_inbox_grant_user.rs
@@ -0,0 +1,80 @@
+use axum::{
+ Json,
+ extract::{self, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use fusionauth::error::FusionAuthClientError;
+use macro_middleware::auth::internal_access::ValidInternalKey;
+use model::response::{EmptyResponse, ErrorResponse};
+
+use crate::api::context::ApiContext;
+
+#[derive(serde::Deserialize, Debug)]
+pub struct DeleteInboxGrantUserQueryParams {
+ /// The dedicated FusionAuth user minted for a shared mailbox.
+ pub fusionauth_user_id: String,
+}
+
+/// Hard-deletes the dedicated FusionAuth user minted for a shared mailbox, once the
+/// mailbox itself has been torn down, so the stub doesn't squat the address forever.
+///
+/// Refuses to delete an **active** user: relocated mailbox stubs are always deactivated,
+/// while real accounts are active, so the state doubles as a guard against a caller bug
+/// pointing this at a human's account. Idempotent on an already-deleted user.
+#[tracing::instrument(skip(ctx, _valid_access))]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ _valid_access: ValidInternalKey,
+ extract::Query(DeleteInboxGrantUserQueryParams { fusionauth_user_id }): extract::Query<
+ DeleteInboxGrantUserQueryParams,
+ >,
+) -> Result<Response, Response> {
+ match ctx.auth_client.get_user_active(&fusionauth_user_id).await {
+ Ok(false) => {}
+ Ok(true) => {
+ tracing::error!(
+ %fusionauth_user_id,
+ "delete_inbox_grant_user: refusing to delete an active user"
+ );
+ return Err((
+ StatusCode::CONFLICT,
+ Json(ErrorResponse {
+ message: "user is active; only deactivated mailbox stubs may be deleted".into(),
+ }),
+ )
+ .into_response());
+ }
+ Err(FusionAuthClientError::UserDoesNotExist) => {
+ return Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response());
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "delete_inbox_grant_user: failed to read user state");
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to read user state".into(),
+ }),
+ )
+ .into_response());
+ }
+ }
+
+ match ctx.auth_client.delete_user(&fusionauth_user_id).await {
+ // Already gone (possibly deleted between the state check above and here) — the
+ // endpoint is idempotent, so treat as success.
+ Ok(()) | Err(FusionAuthClientError::UserDoesNotExist) => {}
+ Err(e) => {
+ tracing::error!(error=?e, "delete_inbox_grant_user: failed to delete user");
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to delete user".into(),
+ }),
+ )
+ .into_response());
+ }
+ }
+
+ Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())
+}
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 1a60e9afa6..702cf91ef5 100644
--- a/rust/cloud-storage/authentication_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/internal/mod.rs
@@ -8,6 +8,7 @@ use crate::api::ApiContext;
use super::user::post_get_names;
// needs to be public in api crate for swagger
+mod delete_inbox_grant_user;
mod google_access_token;
mod post_get_existing_users;
mod relocate_inbox_grant;
@@ -20,4 +21,8 @@ pub fn router() -> Router<ApiContext> {
.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))
+ .route(
+ "/delete_inbox_grant_user",
+ delete(delete_inbox_grant_user::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
index 502671f6b3..864b48d358 100644
--- 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
@@ -21,6 +21,10 @@ pub struct RelocateInboxGrantRequest {
pub email: String,
/// The connector whose FusionAuth user currently holds the mailbox's Google grant.
pub owner_fusionauth_user_id: String,
+ /// When set, the dedicated user is created with this id, keeping the FusionAuth id
+ /// aligned with the mailbox's minted `macro_user.id`.
+ #[serde(default)]
+ pub desired_user_id: Option<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
@@ -36,6 +40,13 @@ pub struct RelocateInboxGrantResponse {
/// 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.
+///
+/// The dedicated user ends up **deactivated**: it exists only to hold the grant (token
+/// refresh reads the stored link directly and never authenticates the user), so leaving
+/// it active would expose unintended sign-in paths — Google login, passwordless, and
+/// password reset all resolve to it by email/identity. Links are only ever created while
+/// the user is active, so an existing deactivated stub is reactivated for the duration
+/// of the relink and deactivated again afterwards.
#[tracing::instrument(skip(ctx, _valid_access))]
pub async fn handler(
State(ctx): State<ApiContext>,
@@ -43,6 +54,7 @@ pub async fn handler(
extract::Json(RelocateInboxGrantRequest {
email,
owner_fusionauth_user_id,
+ desired_user_id,
}): extract::Json<RelocateInboxGrantRequest>,
) -> Result<Response, Response> {
let auth = &ctx.auth_client;
@@ -66,31 +78,58 @@ pub async fn handler(
// 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.
+ // Stripe customer is provisioned. Freshly created users start active; they are
+ // deactivated once the grant is in place.
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| {
+ Err(fusionauth::error::FusionAuthClientError::UserDoesNotExist) => {
+ let user = fusionauth::user::create::User {
+ email: Cow::Borrowed(&email),
+ password: Cow::Owned(uuid::Uuid::new_v4().to_string()),
+ username: Some(Cow::Borrowed(&email)),
+ };
+ let created = match &desired_user_id {
+ Some(id) => {
+ auth.create_user_with_id(id, user, true, IpAddr::V4(Ipv4Addr::LOCALHOST))
+ .await
+ }
+ None => {
+ auth.create_user(user, true, IpAddr::V4(Ipv4Addr::LOCALHOST))
+ .await
+ }
+ };
+ created.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.
+ // Deliberately best-effort: by the time this runs the grant has already moved to the
+ // stub, and the caller re-homes the link's fusionauth_user_id only on a success
+ // response. Failing the request here would skip that re-home and break token
+ // resolution for the inbox — a hard failure — whereas an active stub merely retains
+ // the pre-deactivation security posture until the next relocation converges it.
+ let ensure_deactivated = |user_id: String| async move {
+ match auth.get_user_active(&user_id).await {
+ Ok(false) => {}
+ Ok(true) => {
+ if let Err(e) = auth.deactivate_user(&user_id).await {
+ tracing::error!(error=?e, %user_id, "relocate_inbox_grant: failed to deactivate shared mailbox user");
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e, %user_id, "relocate_inbox_grant: failed to read shared mailbox user state");
+ }
+ }
+ };
+
+ // Idempotent: if the grant already lives on the shared user, just converge it to the
+ // deactivated end-state.
let shared_links = auth
.get_links(&shared_user_id, Some(idp_id.clone()))
.await
@@ -99,6 +138,7 @@ pub async fn handler(
server_error("unable to read shared user links")
})?;
if shared_links.iter().any(|l| l.display_name == email) {
+ ensure_deactivated(shared_user_id.clone()).await;
return Ok((
StatusCode::OK,
Json(RelocateInboxGrantResponse {
@@ -108,6 +148,22 @@ pub async fn handler(
.into_response());
}
+ // Links are only created against active users; a pre-existing stub from an earlier
+ // partial relocation may be deactivated, so reactivate it for the relink.
+ match auth.get_user_active(&shared_user_id).await {
+ Ok(true) => {}
+ Ok(false) => {
+ auth.reactivate_user(&shared_user_id).await.map_err(|e| {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to reactivate shared mailbox user");
+ server_error("unable to reactivate shared mailbox user")
+ })?;
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "relocate_inbox_grant: failed to read shared mailbox user state");
+ return Err(server_error("unable to read shared mailbox user state"));
+ }
+ }
+
// Capture the grant from the owner before moving it.
let owner_links = auth
.get_links(&owner_fusionauth_user_id, Some(idp_id.clone()))
@@ -157,9 +213,13 @@ pub async fn handler(
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");
}
+ // Don't leave an active, grant-less stub squatting the mailbox email.
+ ensure_deactivated(shared_user_id).await;
return Err(server_error("unable to link grant to shared user"));
}
+ ensure_deactivated(shared_user_id.clone()).await;
+
Ok((
StatusCode::OK,
Json(RelocateInboxGrantResponse {
diff --git a/rust/cloud-storage/authentication_service_client/src/delete_inbox_grant_user.rs b/rust/cloud-storage/authentication_service_client/src/delete_inbox_grant_user.rs
new file mode 100644
index 0000000000..12c02267f7
--- /dev/null
+++ b/rust/cloud-storage/authentication_service_client/src/delete_inbox_grant_user.rs
@@ -0,0 +1,37 @@
+use crate::AuthServiceClient;
+use crate::error::{AuthServiceClientError, GenericErrorResponse};
+
+impl AuthServiceClient {
+ /// Hard-deletes the dedicated FusionAuth user minted for a shared mailbox after the
+ /// mailbox is torn down. The server refuses active users, so this cannot remove a
+ /// real account. Idempotent on an already-deleted user.
+ #[tracing::instrument(skip(self), err)]
+ pub async fn delete_inbox_grant_user(
+ &self,
+ fusionauth_user_id: &str,
+ ) -> Result<(), AuthServiceClientError> {
+ let res = self
+ .client
+ .delete(format!("{}/internal/delete_inbox_grant_user", self.url))
+ .query(&[("fusionauth_user_id", fusionauth_user_id)])
+ .send()
+ .await
+ .map_err(|e| AuthServiceClientError::RequestBuildError {
+ details: e.to_string(),
+ })?;
+
+ match res.status() {
+ reqwest::StatusCode::OK => Ok(()),
+ _ => {
+ 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/authentication_service_client/src/lib.rs b/rust/cloud-storage/authentication_service_client/src/lib.rs
index 10814a87e2..4e66b61424 100644
--- a/rust/cloud-storage/authentication_service_client/src/lib.rs
+++ b/rust/cloud-storage/authentication_service_client/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod delete_inbox_grant_user;
pub mod error;
pub mod google_access_token;
pub mod relocate_inbox_grant;
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
index 875d29ff72..631b428377 100644
--- a/rust/cloud-storage/authentication_service_client/src/relocate_inbox_grant.rs
+++ b/rust/cloud-storage/authentication_service_client/src/relocate_inbox_grant.rs
@@ -5,6 +5,7 @@ use crate::error::{AuthServiceClientError, GenericErrorResponse};
struct RelocateInboxGrantRequest<'a> {
email: &'a str,
owner_fusionauth_user_id: &'a str,
+ desired_user_id: &'a str,
}
#[derive(serde::Deserialize)]
@@ -13,14 +14,17 @@ struct RelocateInboxGrantResponse {
}
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.
+ /// Provisions a dedicated (deactivated) FusionAuth user for a shared mailbox and
+ /// relocates the mailbox's Google grant onto it (off `owner_fusionauth_user_id`).
+ /// `desired_user_id` is used as the created user's id so it can match the mailbox's
+ /// minted `macro_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,
+ desired_user_id: &str,
) -> Result<String, AuthServiceClientError> {
let res = self
.client
@@ -28,6 +32,7 @@ impl AuthServiceClient {
.json(&RelocateInboxGrantRequest {
email,
owner_fusionauth_user_id,
+ desired_user_id,
})
.send()
.await
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 7b7526c223..da8bc8cfa8 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -393,7 +393,11 @@ pub async fn handler(
// 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)
+ .relocate_inbox_grant(
+ &linked_email,
+ &existing_link.fusionauth_user_id,
+ &promoted.mailbox_fusion_id.to_string(),
+ )
.await
{
Ok(shared_fusionauth_user_id) => {
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 6e648d61d4..47a689112c 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
@@ -291,13 +291,39 @@ async fn handle_delete(
// ordinary inboxes; best-effort, since the link and its data are already gone.
match ctx.db.acquire().await {
Ok(mut conn) => {
- if let Err(e) = macro_db_client::shared_inbox::delete_promoted_mailbox_user(
+ match macro_db_client::shared_inbox::delete_promoted_mailbox_user(
&mut conn,
link.macro_id.as_ref(),
)
.await
{
- tracing::error!(error=?e, "Failed to delete minted user for promoted shared mailbox");
+ Ok(Some(minted_id)) => {
+ // The minted id is the authoritative stub id: grant relocation creates the
+ // mailbox's FusionAuth user with it, so it can never be a human connector's
+ // account. Deleting by it (rather than the link's fusionauth_user_id, which
+ // is stale when the post-relocation re-home failed) cleans the stub even in
+ // partial states; the endpoint no-ops when relocation never created the user
+ // and refuses active users as a second guard.
+ let minted_id = minted_id.to_string();
+ if link.fusionauth_user_id != minted_id {
+ tracing::warn!(
+ link_fusionauth_user_id = %link.fusionauth_user_id,
+ %minted_id,
+ "Promoted mailbox link did not point at its minted stub; deleting stub by minted id"
+ );
+ }
+ if let Err(e) = ctx
+ .auth_service_client
+ .delete_inbox_grant_user(&minted_id)
+ .await
+ {
+ tracing::error!(error=?e, "Failed to delete FusionAuth stub for promoted shared mailbox");
+ }
+ }
+ Ok(None) => {}
+ Err(e) => {
+ tracing::error!(error=?e, "Failed to delete minted user for promoted shared mailbox");
+ }
}
}
Err(e) => {
diff --git a/rust/cloud-storage/fusionauth/src/user/create.rs b/rust/cloud-storage/fusionauth/src/user/create.rs
index 1ebb6090b0..722711190f 100644
--- a/rust/cloud-storage/fusionauth/src/user/create.rs
+++ b/rust/cloud-storage/fusionauth/src/user/create.rs
@@ -49,18 +49,26 @@ pub(crate) struct CreateUserResponse<'a> {
pub user: UserResponse<'a>,
}
-/// Creates a user in fusionauth
+/// Creates a user in fusionauth. When `user_id` is provided the user is created with
+/// that id (`POST /api/user/{id}`), letting callers align the FusionAuth id with an
+/// externally minted identifier.
/// https://fusionauth.io/docs/apis/users#create-a-user
/// Valid respones: 200, 400, 401, 500, 503, 504
pub(crate) async fn create_user(
client: &AuthedClient,
base_url: &str,
+ user_id: Option<&str>,
request: CreateUserRequest<'_>,
client_ip: IpAddr,
) -> Result<String> {
+ let url = match user_id {
+ Some(id) => format!("{base_url}/api/user/{id}"),
+ None => format!("{base_url}/api/user"),
+ };
+
let res = client
.client()
- .post(format!("{base_url}/api/user"))
+ .post(url)
.header("X-Forwarded-For", &client_ip.to_string())
.json(&request)
.send()
diff --git a/rust/cloud-storage/fusionauth/src/user/delete.rs b/rust/cloud-storage/fusionauth/src/user/delete.rs
index 8cabaaf976..c0fade35d9 100644
--- a/rust/cloud-storage/fusionauth/src/user/delete.rs
+++ b/rust/cloud-storage/fusionauth/src/user/delete.rs
@@ -27,6 +27,86 @@ pub(crate) async fn delete_user(
tracing::trace!("user deleted");
Ok(())
}
+ reqwest::StatusCode::NOT_FOUND => Err(FusionAuthClientError::UserDoesNotExist),
+ _ => {
+ let body = res.text().await.map_err(|e| {
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+
+ tracing::error!(body=%body, "unexpected response from fusionauth");
+
+ Err(FusionAuthClientError::Generic(GenericErrorResponse {
+ message: body,
+ }))
+ }
+ }
+}
+
+/// Deactivates (soft-deletes) a user in fusionauth. The user can no longer authenticate,
+/// but their identity provider links remain readable via the Link API.
+/// https://fusionauth.io/docs/apis/users#delete-a-user
+pub(crate) async fn deactivate_user(
+ client: &AuthedClient,
+ base_url: &str,
+ user_id: &str,
+) -> Result<()> {
+ let res = client
+ .client()
+ .delete(format!("{base_url}/api/user/{user_id}"))
+ .send()
+ .await
+ .map_err(|e| {
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+
+ match res.status() {
+ reqwest::StatusCode::OK => {
+ tracing::trace!("user deactivated");
+ Ok(())
+ }
+ _ => {
+ let body = res.text().await.map_err(|e| {
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+
+ tracing::error!(body=%body, "unexpected response from fusionauth");
+
+ Err(FusionAuthClientError::Generic(GenericErrorResponse {
+ message: body,
+ }))
+ }
+ }
+}
+
+/// Reactivates a previously deactivated user.
+/// https://fusionauth.io/docs/apis/users#reactivate-a-user
+pub(crate) async fn reactivate_user(
+ client: &AuthedClient,
+ base_url: &str,
+ user_id: &str,
+) -> Result<()> {
+ let res = client
+ .client()
+ .put(format!("{base_url}/api/user/{user_id}?reactivate=true"))
+ .send()
+ .await
+ .map_err(|e| {
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+
+ match res.status() {
+ reqwest::StatusCode::OK => {
+ tracing::trace!("user reactivated");
+ Ok(())
+ }
_ => {
let body = res.text().await.map_err(|e| {
FusionAuthClientError::Generic(GenericErrorResponse {
diff --git a/rust/cloud-storage/fusionauth/src/user/get.rs b/rust/cloud-storage/fusionauth/src/user/get.rs
index e1a11e2142..c75fe7b69b 100644
--- a/rust/cloud-storage/fusionauth/src/user/get.rs
+++ b/rust/cloud-storage/fusionauth/src/user/get.rs
@@ -12,6 +12,8 @@ pub(crate) struct UserResponse<'a> {
pub id: Cow<'a, str>,
/// The email address of the user
pub email: Cow<'a, str>,
+ /// Whether the user may authenticate (false once deactivated)
+ pub active: Option<bool>,
/// The additional data associated with the user
pub data: Option<serde_json::Value>,
}
@@ -23,6 +25,52 @@ pub(crate) struct GetUserResponse<'a> {
pub user: UserResponse<'a>,
}
+/// Retrieves whether a user is active by id.
+/// https://fusionauth.io/docs/apis/users#retrieve-a-user
+pub(crate) async fn get_user_active(
+ client: &AuthedClient,
+ base_url: &str,
+ user_id: &str,
+) -> Result<bool> {
+ let res = client
+ .client()
+ .get(format!("{base_url}/api/user/{user_id}"))
+ .send()
+ .await
+ .map_err(|e| {
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+
+ let status_code = res.status();
+ match status_code {
+ reqwest::StatusCode::OK => {
+ let body = res.json::<GetUserResponse>().await.map_err(|e| {
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+
+ Ok(body.user.active.unwrap_or(true))
+ }
+ reqwest::StatusCode::NOT_FOUND => Err(FusionAuthClientError::UserDoesNotExist),
+ _ => {
+ let body = res.text().await.map_err(|e| {
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })?;
+
+ tracing::error!(body=%body, status=%status_code, "unexpected response from fusionauth");
+
+ Err(FusionAuthClientError::Generic(GenericErrorResponse {
+ message: body,
+ }))
+ }
+ }
+}
+
/// Retreives a user by email in fusionauth
/// https://fusionauth.io/docs/apis/users#retrieve-a-user
/// Valid respones: 200, 400, 401, 500, 503
diff --git a/rust/cloud-storage/fusionauth/src/user/mod.rs b/rust/cloud-storage/fusionauth/src/user/mod.rs
index f30149a1fe..ec9cdc1063 100644
--- a/rust/cloud-storage/fusionauth/src/user/mod.rs
+++ b/rust/cloud-storage/fusionauth/src/user/mod.rs
@@ -29,6 +29,32 @@ impl FusionAuthClient {
create::create_user(
&self.auth_client,
&self.fusion_auth_base_url,
+ None,
+ create::CreateUserRequest {
+ application_id: Cow::Borrowed(&self.client_id),
+ skip_verification,
+ user,
+ },
+ client_ip,
+ )
+ .await
+ }
+
+ /// Creates a new user in FusionAuth with a caller-specified id, so the FusionAuth id
+ /// can match an externally minted identifier. Triggers the create-user webhook like
+ /// [`Self::create_user`].
+ #[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
+ pub async fn create_user_with_id(
+ &self,
+ user_id: &str,
+ user: create::User<'_>,
+ skip_verification: bool,
+ client_ip: IpAddr,
+ ) -> Result<String> {
+ create::create_user(
+ &self.auth_client,
+ &self.fusion_auth_base_url,
+ Some(user_id),
create::CreateUserRequest {
application_id: Cow::Borrowed(&self.client_id),
skip_verification,
@@ -45,6 +71,25 @@ impl FusionAuthClient {
delete::delete_user(&self.auth_client, &self.fusion_auth_base_url, user_id).await
}
+ /// Deactivates (soft-deletes) a user. The user can no longer authenticate, but their
+ /// identity provider links remain readable, so stored grants keep working.
+ #[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
+ pub async fn deactivate_user(&self, user_id: &str) -> Result<()> {
+ delete::deactivate_user(&self.auth_client, &self.fusion_auth_base_url, user_id).await
+ }
+
+ /// Reactivates a previously deactivated user.
+ #[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
+ pub async fn reactivate_user(&self, user_id: &str) -> Result<()> {
+ delete::reactivate_user(&self.auth_client, &self.fusion_auth_base_url, user_id).await
+ }
+
+ /// Returns whether a user is active (deactivated users cannot authenticate).
+ #[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
+ pub async fn get_user_active(&self, user_id: &str) -> Result<bool> {
+ get::get_user_active(&self.auth_client, &self.fusion_auth_base_url, user_id).await
+ }
+
/// Registers a user to the application by looking up their email first.
#[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
pub async fn register_user_from_email(&self, email: &str) -> Result<()> {
diff --git a/rust/cloud-storage/macro_db_client/src/shared_inbox.rs b/rust/cloud-storage/macro_db_client/src/shared_inbox.rs
index 82f62e3e62..f9d9887b37 100644
--- a/rust/cloud-storage/macro_db_client/src/shared_inbox.rs
+++ b/rust/cloud-storage/macro_db_client/src/shared_inbox.rs
@@ -13,6 +13,9 @@ mod test;
pub struct PromotedSharedInbox {
/// The macro_id minted for the mailbox. The re-homed link and both edges point at it.
pub mailbox_macro_id: String,
+ /// The uuid minted as the mailbox's `macro_user.id`. Grant relocation creates the
+ /// mailbox's FusionAuth user with this same id, so the two stay aligned.
+ pub mailbox_fusion_id: Uuid,
/// The surviving (re-homed) `email_links` row — its id is unchanged, so the one
/// synced copy and its history are preserved.
pub link_id: Uuid,
@@ -114,6 +117,7 @@ pub async fn promote_link_to_shared(
Ok(PromotedSharedInbox {
mailbox_macro_id,
+ mailbox_fusion_id: fusionauth_user_id,
link_id: existing_link_id,
})
}
@@ -142,12 +146,14 @@ pub async fn is_promoted_shared_mailbox(
/// Deletes the macro user minted for a promoted shared mailbox once its single link has
/// been torn down. Removing the `User` row cascades its `macro_user_links` edges and the
/// `promoted_shared_mailboxes` marker; the backing `macro_user` row is removed explicitly.
-/// No-op when `macro_id` is not a promoted mailbox.
+/// No-op (returning `None`) when `macro_id` is not a promoted mailbox; otherwise returns
+/// the deleted `macro_user.id`, which callers can match against a link's
+/// `fusionauth_user_id` to recognize the mailbox's relocated FusionAuth stub.
#[tracing::instrument(skip(conn), err)]
pub async fn delete_promoted_mailbox_user(
conn: &mut sqlx::PgConnection,
macro_id: &str,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<Option<Uuid>> {
let row = sqlx::query!(
r#"
DELETE FROM "User"
@@ -160,11 +166,13 @@ pub async fn delete_promoted_mailbox_user(
.fetch_optional(&mut *conn)
.await?;
- if let Some(row) = row {
- sqlx::query!(r#"DELETE FROM macro_user WHERE id = $1"#, row.macro_user_id)
- .execute(&mut *conn)
- .await?;
- }
+ let Some(row) = row else {
+ return Ok(None);
+ };
+
+ sqlx::query!(r#"DELETE FROM macro_user WHERE id = $1"#, row.macro_user_id)
+ .execute(&mut *conn)
+ .await?;
- Ok(())
+ Ok(Some(row.macro_user_id))
}
diff --git a/rust/cloud-storage/macro_db_client/src/shared_inbox/test.rs b/rust/cloud-storage/macro_db_client/src/shared_inbox/test.rs
index 4871795ca6..dbc875b5a7 100644
--- a/rust/cloud-storage/macro_db_client/src/shared_inbox/test.rs
+++ b/rust/cloud-storage/macro_db_client/src/shared_inbox/test.rs
@@ -74,13 +74,16 @@ async fn promote_dedups_to_single_link_with_two_edges(pool: Pool<Postgres>) -> a
// is_primary is generated as `link.email == macro_id's email`. The minted macro_id
// embeds the mailbox email, so the promoted mailbox is a real shared user, not inbox-only.
+ // The returned fusion id is the minted macro_user.id, which grant relocation reuses as
+ // the FusionAuth stub's id.
let mailbox_user = sqlx::query!(
- r#"SELECT email FROM "User" WHERE id = $1"#,
+ r#"SELECT email, macro_user_id FROM "User" WHERE id = $1"#,
mailbox_macro_id
)
.fetch_one(&pool)
.await?;
assert_eq!(mailbox_user.email, MAILBOX_EMAIL);
+ assert_eq!(mailbox_user.macro_user_id, result.mailbox_fusion_id);
// Both the original owner and the new connector hold an edge to the mailbox.
let mut primaries =
@@ -162,7 +165,8 @@ async fn promote_marks_mailbox_and_teardown_removes_everything(
let link_id = insert_data_source_link(&pool, OWNER, MAILBOX_EMAIL).await;
let mut conn = pool.acquire().await?;
- promote_link_to_shared(&mut conn, link_id, OWNER, CONNECTOR, MAILBOX_EMAIL, None).await?;
+ let promoted =
+ promote_link_to_shared(&mut conn, link_id, OWNER, CONNECTOR, MAILBOX_EMAIL, None).await?;
let mailbox_macro_id = format!("macro|{MAILBOX_EMAIL}");
// Promotion marks the mailbox; a regular macro_id is not marked.
@@ -173,7 +177,10 @@ async fn promote_marks_mailbox_and_teardown_removes_everything(
sqlx::query!(r#"DELETE FROM email_links WHERE id = $1"#, link_id)
.execute(&pool)
.await?;
- delete_promoted_mailbox_user(&mut conn, &mailbox_macro_id).await?;
+ // Teardown reports the minted id so callers can recognize (and remove) the mailbox's
+ // FusionAuth stub, which relocation created under the same id.
+ let deleted = delete_promoted_mailbox_user(&mut conn, &mailbox_macro_id).await?;
+ assert_eq!(deleted, Some(promoted.mailbox_fusion_id));
// The minted User, its macro_user, the marker, and both edges are gone.
let user = sqlx::query!(r#"SELECT id FROM "User" WHERE id = $1"#, mailbox_macro_id)
@@ -199,7 +206,8 @@ async fn delete_promoted_mailbox_user_is_noop_for_real_account(
insert_user(&pool, OWNER, "[email protected]").await;
let mut conn = pool.acquire().await?;
- delete_promoted_mailbox_user(&mut conn, OWNER).await?;
+ let deleted = delete_promoted_mailbox_user(&mut conn, OWNER).await?;
+ assert_eq!(deleted, None, "no-op must report that nothing was deleted");
let user = sqlx::query!(r#"SELECT id FROM "User" WHERE id = $1"#, OWNER)
.fetch_optional(&pool)