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(auth): fire first-inbox provisioning from the SSO redirect, not the direct-OAuth login (#4682)

gbirman46e4df3bdd84
diff --git a/rust/cloud-storage/authentication_service/src/api/link/gmail.rs b/rust/cloud-storage/authentication_service/src/api/link/gmail.rs
index 315163816e..5010e3e9a3 100644
--- a/rust/cloud-storage/authentication_service/src/api/link/gmail.rs
+++ b/rust/cloud-storage/authentication_service/src/api/link/gmail.rs
@@ -22,7 +22,7 @@ use crate::api::{
mod test;
const GOOGLE_AUTHORIZATION_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
-pub(in crate::api) const GMAIL_IDENTITY_PROVIDER_NAME: &str = "google_gmail";
+const GMAIL_IDENTITY_PROVIDER_NAME: &str = "google_gmail";
const GMAIL_SCOPES: &str = "openid profile email https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/contacts.other.readonly https://www.googleapis.com/auth/gmail.settings.basic";
const FREE_INBOX_LIMIT: i64 = 2;
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs b/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
index 0e8db96126..2c1ea33cff 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
@@ -4,6 +4,7 @@ use crate::api::{
utils::{
append_signed_up_param_if_new_user, create_access_token_cookie,
create_refresh_token_cookie, default_redirect_url, generate_session_code,
+ spawn_first_inbox_provision,
},
};
use axum::{
@@ -147,6 +148,8 @@ pub async fn handler(
cookies.add(create_access_token_cookie(&access_token));
cookies.add(create_refresh_token_cookie(&refresh_token));
+ spawn_first_inbox_provision(&ctx, &access_token);
+
Ok(html_redirect(&redirect_url).into_response())
}
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/login.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/login.rs
index 2a606a602d..dc89a47f49 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth2/login.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/login.rs
@@ -1,63 +1,20 @@
use crate::api::{
context::ApiContext,
- link::gmail::GMAIL_IDENTITY_PROVIDER_NAME,
oauth2::{OAuthState, format_redirect_uri},
utils::{
create_access_token_cookie, create_refresh_token_cookie, default_redirect_url,
- generate_session_code,
+ generate_session_code, spawn_first_inbox_provision,
},
};
use axum::{
Json,
response::{IntoResponse, Redirect, Response},
};
-use email::domain::ports::{FirstInboxProvisionOutcome, FirstInboxProvisioner};
use macro_env::Environment;
use model::response::ErrorResponse;
use reqwest::StatusCode;
use tower_cookies::Cookies;
-/// Provisions the user's primary inbox after a Gmail-scoped login, the moment
-/// the Google grant is minted or refreshed. Fire-and-forget so the login
-/// redirect is never delayed. Init is idempotent and recurs on every login, so
-/// a lost attempt only delays provisioning until the next one.
-fn spawn_first_inbox_provision(ctx: &ApiContext, identity_provider_id: &str, access_token: &str) {
- let auth_client = ctx.auth_client.clone();
- let email_service_client = ctx.email_service_client.clone();
- let identity_provider_id = identity_provider_id.to_string();
- let access_token = access_token.to_string();
-
- tokio::spawn(async move {
- let gmail_idp_id = match auth_client
- .get_identity_provider_id_by_name(GMAIL_IDENTITY_PROVIDER_NAME)
- .await
- {
- Ok(id) => id,
- Err(e) => {
- tracing::warn!(error=?e, "first-inbox provision: unable to resolve gmail idp id");
- return;
- }
- };
-
- if identity_provider_id != gmail_idp_id {
- return;
- }
-
- match email_service_client
- .provision_first_inbox(&access_token)
- .await
- {
- Ok(FirstInboxProvisionOutcome::Provisioned) => {
- tracing::info!("first-inbox provision: inbox initialized on login");
- }
- Ok(FirstInboxProvisionOutcome::Skipped) => {}
- Err(e) => {
- tracing::warn!(error=?e, "first-inbox provision: init failed");
- }
- }
- });
-}
-
/// Handles logging in through an identity provider
pub(in crate::api::oauth2) async fn handler(
ctx: &ApiContext,
@@ -153,7 +110,7 @@ pub(in crate::api::oauth2) async fn handler(
cookies.add(create_access_token_cookie(&access_token));
cookies.add(create_refresh_token_cookie(&refresh_token));
- spawn_first_inbox_provision(ctx, &state.identity_provider_id, &access_token);
+ spawn_first_inbox_provision(ctx, &access_token);
match environment {
Environment::Local => Ok(StatusCode::OK.into_response()), // We don't really care about redirect in local
diff --git a/rust/cloud-storage/authentication_service/src/api/utils.rs b/rust/cloud-storage/authentication_service/src/api/utils.rs
index 14d9de5355..7b69f2049e 100644
--- a/rust/cloud-storage/authentication_service/src/api/utils.rs
+++ b/rust/cloud-storage/authentication_service/src/api/utils.rs
@@ -1,4 +1,6 @@
+use crate::api::context::ApiContext;
use cookie::{Cookie, SameSite};
+use email::domain::ports::{FirstInboxProvisionOutcome, FirstInboxProvisioner};
use macro_auth::constant::{MACRO_ACCESS_TOKEN_COOKIE, MACRO_REFRESH_TOKEN_COOKIE};
use macro_env::Environment;
use macro_env_var::maybe_env_vars;
@@ -144,3 +146,28 @@ pub async fn append_signed_up_param_if_new_user(
}
}
}
+
+/// Provisions the user's primary inbox as a side effect of authentication,
+/// the moment a fresh access token exists. Fire-and-forget so the login
+/// response is never delayed. The email service arbitrates: a login without a
+/// usable Gmail grant is an expected no-op, and init is idempotent and recurs
+/// on every login, so a lost attempt only delays provisioning until the next one.
+pub fn spawn_first_inbox_provision(ctx: &ApiContext, access_token: &str) {
+ let email_service_client = ctx.email_service_client.clone();
+ let access_token = access_token.to_string();
+
+ tokio::spawn(async move {
+ match email_service_client
+ .provision_first_inbox(&access_token)
+ .await
+ {
+ Ok(FirstInboxProvisionOutcome::Provisioned) => {
+ tracing::info!("first-inbox provision: inbox initialized on login");
+ }
+ Ok(FirstInboxProvisionOutcome::Skipped) => {}
+ Err(e) => {
+ tracing::warn!(error=?e, "first-inbox provision: init failed");
+ }
+ }
+ });
+}
diff --git a/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs b/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
index 92e7273f7b..2d22ea3cb2 100644
--- a/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
+++ b/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
@@ -90,7 +90,7 @@ pub async fn fetch_gmail_access_token(
/// Fetches a Gmail access token directly from the auth service, bypassing the Redis cache for
/// reads but still caching the newly fetched token.
-#[tracing::instrument(skip(key, redis_conn, auth_service_client), err)]
+#[tracing::instrument(skip(key, redis_conn, auth_service_client), err(level = "debug"))]
pub async fn fetch_gmail_access_token_no_cache(
key: &TokenCacheKey,
redis_conn: &MultiplexedConnection,
@@ -119,7 +119,7 @@ async fn cache_token_in_redis(conn: &mut MultiplexedConnection, key: &TokenCache
}
/// Fetches a Gmail access token from the auth service.
-#[tracing::instrument(skip(key, auth_service_client), err)]
+#[tracing::instrument(skip(key, auth_service_client), err(level = "debug"))]
async fn fetch_token_from_auth_service(
key: &TokenCacheKey,
auth_service_client: &AuthServiceClient,
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 16f24a4b75..d2d15eee67 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -79,9 +79,9 @@ pub struct InitErrorCodeResponse {
pub message: String,
}
-impl IntoResponse for InitError {
- fn into_response(self) -> Response {
- let status_code = match &self {
+impl InitError {
+ fn status_code(&self) -> StatusCode {
+ match self {
InitError::AlreadyInitialized
| InitError::NoGmailGrant
| InitError::BadRequest(_)
@@ -91,7 +91,13 @@ impl IntoResponse for InitError {
StatusCode::INTERNAL_SERVER_ERROR
}
InitError::SharedInboxConflict { .. } => StatusCode::CONFLICT,
- };
+ }
+ }
+}
+
+impl IntoResponse for InitError {
+ fn into_response(self) -> Response {
+ let status_code = self.status_code();
match self {
InitError::SharedInboxConflict {
@@ -183,9 +189,31 @@ pub struct InitParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_extractor), fields(user_id=user_extractor.user_context.user_id, fusionauth_user_id=user_extractor.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, user_extractor), fields(user_id=user_extractor.user_context.user_id, fusionauth_user_id=user_extractor.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
+ query: Query<InitParams>,
+ user_extractor: MacroUserExtractor,
+) -> Result<Response, InitError> {
+ // Init runs on every authentication, so its expected no-op outcomes (400s)
+ // must not error-log. The span skips the auto err event and the result is
+ // classified here, inside the span, where user fields still attach.
+ let result = init_user(ctx, query, user_extractor).await;
+ if let Err(e) = &result {
+ let status = e.status_code();
+ if status.is_server_error() {
+ tracing::error!(error = ?e, "init failed");
+ } else if status == StatusCode::TOO_MANY_REQUESTS {
+ tracing::warn!(error = %e, "init rate limited");
+ } else {
+ tracing::debug!(error = %e, "init declined");
+ }
+ }
+ result
+}
+
+async fn init_user(
+ ctx: ApiContext,
Query(InitParams {
link_id,
force_share,