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): answer 403 for Google policy-blocked grants (#9801)
teo6345d5420be7
diff --git a/Cargo.lock b/Cargo.lockindex 63170703a9..dd24ba85d4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8600,6 +8600,7 @@ dependencies = ["serde","serde_json","serde_urlencoded",+ "strum 0.27.2","thiserror 2.0.18","tokio","tracing",diff --git a/crates/fusionauth/Cargo.toml b/crates/fusionauth/Cargo.tomlindex d752aabe9b..0df3ecb6cb 100644--- a/crates/fusionauth/Cargo.toml+++ b/crates/fusionauth/Cargo.toml@@ -12,6 +12,7 @@ reqwest = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }serde_urlencoded = { workspace = true }+strum = { workspace = true }thiserror = { workspace = true }tracing = { workspace = true }upstream_error = { path = "../upstream_error", default-features = false, features = [diff --git a/crates/fusionauth/src/error.rs b/crates/fusionauth/src/error.rsindex 4a2190eb66..f211b4195f 100644--- a/crates/fusionauth/src/error.rs+++ b/crates/fusionauth/src/error.rs@@ -59,6 +59,32 @@ pub enum FusionAuthClientError {/// The grant is invalid - user may have revoked access.#[error("Invalid grant - user may have revoked access")]InvalidGrant,+ /// The provider refused to refresh this user's grant by policy, such as a+ /// Google Workspace admin not approving Macro. Retrying will not help+ /// until the user's organization allows access.+ #[error("access blocked by the user's organization: {reason}")]+ GrantBlocked {+ /// The provider's OAuth error code.+ reason: GrantBlockReason,+ },+}++/// Google OAuth error codes for a grant the user's organization does not let+/// Macro use, such as a Workspace admin who has not approved the app. Only+/// that organization can lift them. `invalid_client` and `unauthorized_client`+/// are deliberately absent: they mean Macro's own OAuth client is broken.+#[derive(+ Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, strum::EnumString, strum::Display,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum GrantBlockReason {+ /// A Workspace admin has not reviewed and configured access for Macro.+ AccessNotConfigured,+ /// A Workspace admin policy forbids the requested scopes.+ AdminPolicyEnforced,+ /// The user or their organization denied access.+ AccessDenied,}impl FusionAuthClientError {diff --git a/crates/fusionauth/src/google/oauth.rs b/crates/fusionauth/src/google/oauth.rsindex 57add4b98b..d4d822b891 100644--- a/crates/fusionauth/src/google/oauth.rs+++ b/crates/fusionauth/src/google/oauth.rs@@ -2,7 +2,7 @@ use std::{collections::HashMap, time::Duration};use crate::{Result, UnauthedClient,- error::{FusionAuthClientError, GenericErrorResponse},+ error::{FusionAuthClientError, GenericErrorResponse, GrantBlockReason},};use base64::{Engine,@@ -103,17 +103,26 @@ async fn refresh_google_token_at(.text().await.unwrap_or_else(|_| "Unable to read error response".to_string());- tracing::error!(- status=?status,- error=?error_text,- "failed to refresh Google access token"- );// If the user revoked Macro's access to their account, we get an invalid_grant error hereif error_text.contains("invalid_grant") {+ tracing::warn!(status=?status, error=?error_text, "Google rejected the refresh token");return Err(FusionAuthClientError::InvalidGrant);}+ if let Some(reason) =+ grant_block_reason(&error_text).filter(|_| status.is_client_error())+ {+ tracing::warn!(status=?status, error=?error_text, "Google blocked the grant by policy");+ return Err(FusionAuthClientError::GrantBlocked { reason });+ }++ tracing::error!(+ status=?status,+ error=?error_text,+ "failed to refresh Google access token"+ );+if let Some(failure) = UpstreamFailure::from_status(status, &headers) {return Err(FusionAuthClientError::Upstream {service: GOOGLE,@@ -131,6 +140,17 @@ async fn refresh_google_token_at(}}+/// The reason in a Google OAuth error body, when it is a policy block.+fn grant_block_reason(body: &str) -> Option<GrantBlockReason> {+ #[derive(serde::Deserialize)]+ struct OAuthError {+ error: String,+ }++ let OAuthError { error } = serde_json::from_str(body).ok()?;+ error.parse().ok()+}+#[derive(Debug, serde::Deserialize)]/// Response from exchanging a Google authorization code for tokens.pub struct GoogleExchangeTokenResponse {diff --git a/crates/fusionauth/src/google/oauth/test.rs b/crates/fusionauth/src/google/oauth/test.rsindex 9c484a656c..582379fa99 100644--- a/crates/fusionauth/src/google/oauth/test.rs+++ b/crates/fusionauth/src/google/oauth/test.rs@@ -4,7 +4,10 @@ use wiremock::matchers::method;use wiremock::{Mock, MockServer, ResponseTemplate};use super::{GOOGLE, refresh_google_token_at};-use crate::{UnauthedClient, error::FusionAuthClientError};+use crate::{+ UnauthedClient,+ error::{FusionAuthClientError, GrantBlockReason},+};async fn refresh_answering(response: ResponseTemplate) -> FusionAuthClientError {let server = MockServer::start().await;@@ -49,3 +52,44 @@ async fn a_revoked_grant_is_still_invalid_grant() {assert!(matches!(error, FusionAuthClientError::InvalidGrant));}++#[tokio::test]+async fn an_unapproved_workspace_app_is_a_blocked_grant() {+ let error = refresh_answering(ResponseTemplate::new(400).set_body_json(json!({+ "error": "access_not_configured",+ "error_description": "You can't access this app until an admin at your institution reviews and configures access for it.",+ })))+ .await;++ assert!(matches!(+ error,+ FusionAuthClientError::GrantBlocked {+ reason: GrantBlockReason::AccessNotConfigured+ }+ ));+}++#[tokio::test]+async fn an_enforced_admin_policy_is_a_blocked_grant() {+ let error = refresh_answering(+ ResponseTemplate::new(400).set_body_json(json!({ "error": "admin_policy_enforced" })),+ )+ .await;++ assert!(matches!(+ error,+ FusionAuthClientError::GrantBlocked {+ reason: GrantBlockReason::AdminPolicyEnforced+ }+ ));+}++#[tokio::test]+async fn a_broken_macro_client_is_not_a_blocked_grant() {+ let error = refresh_answering(+ ResponseTemplate::new(401).set_body_json(json!({ "error": "invalid_client" })),+ )+ .await;++ assert!(matches!(error, FusionAuthClientError::Generic(_)));+}diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.mdindex fe0bbc37e3..a3d5b88376 100644--- a/services/authentication_service/AGENTS.md+++ b/services/authentication_service/AGENTS.md@@ -123,6 +123,12 @@ inputs cannot select an agent, and ordinary user credentials remain unattributedfailures remain server errors.Deploy grant-refresh support before releasing clients that omit the pre-OAuthdisconnect; older callbacks leave an existing grant unchanged.+- `/internal/google_access_token` answers 403 for every grant Google refuses+ for this user (`InvalidGrant`, and `GrantBlocked` for policy codes such as+ `access_not_configured`); email and calendar callers then mark the link for+ reauthorization instead of retrying. Keep it 4xx: a 500 makes callers retry+ and trips the HTTP server-errors monitor. Macro's own OAuth client failing+ (`invalid_client`) stays a 500.- FusionAuth reports a link owner that was deleted as `UserDoesNotExist`. Thatuser 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.diff --git a/services/authentication_service/src/api/internal/google_access_token.rs b/services/authentication_service/src/api/internal/google_access_token.rsindex f4268d11ca..15b9b0d419 100644--- a/services/authentication_service/src/api/internal/google_access_token.rs+++ b/services/authentication_service/src/api/internal/google_access_token.rs@@ -165,6 +165,12 @@ fn refresh_error_response(tracing::warn!(error=?error, "refresh token rejected for userid {}", fusionauth_user_id);StatusCode::FORBIDDEN}+ // The user's organization blocks Macro. Callers treat it like a+ // revoked grant, so they ask for reauthorization instead of retrying.+ FusionAuthClientError::GrantBlocked { reason } => {+ tracing::warn!(reason = %reason, "{} grant blocked by policy for userid {}", identity_provider_name, fusionauth_user_id);+ StatusCode::FORBIDDEN+ }_ => {tracing::error!(error=?error, "error fetching access token for userid {}", fusionauth_user_id);StatusCode::INTERNAL_SERVER_ERRORdiff --git a/services/authentication_service/src/api/internal/google_access_token/test.rs b/services/authentication_service/src/api/internal/google_access_token/test.rsindex 09a72c808c..f2ce17a236 100644--- a/services/authentication_service/src/api/internal/google_access_token/test.rs+++ b/services/authentication_service/src/api/internal/google_access_token/test.rs@@ -1,5 +1,5 @@use axum::http::StatusCode;-use fusionauth::error::{FusionAuthClientError, GenericErrorResponse};+use fusionauth::error::{FusionAuthClientError, GenericErrorResponse, GrantBlockReason};use upstream_error::UpstreamFailure;use super::*;@@ -42,6 +42,17 @@ fn a_revoked_grant_during_refresh_is_still_forbidden() {assert_eq!(response.status(), StatusCode::FORBIDDEN);}+#[test]+fn a_grant_blocked_by_the_users_organization_is_forbidden() {+ let error = FusionAuthClientError::GrantBlocked {+ reason: GrantBlockReason::AccessNotConfigured,+ };++ let response = refresh_error_response(error, USER, IDP);++ assert_eq!(response.status(), StatusCode::FORBIDDEN);+}+#[test]fn an_unknown_refresh_failure_is_still_internal() {let response = refresh_error_response(generic(), USER, IDP);