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): typed NO_GMAIL_GRANT init error, stop conflating it with 400s (#4630)

gbirmandc752282346b
diff --git a/js/app/packages/core/email-link/index.ts b/js/app/packages/core/email-link/index.ts
index d01349ebe4..c5e13f709d 100644
--- a/js/app/packages/core/email-link/index.ts
+++ b/js/app/packages/core/email-link/index.ts
@@ -6,7 +6,12 @@ import { getNativeMobilePlatform } from '@core/util/platform';
import { useInitGmailLink } from '@queries/auth';
import { invalidateUserInfo } from '@queries/auth/user-info';
import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';
-import { emailClient, SHARED_INBOX_CONFLICT_CODE } from '@service-email/client';
+import {
+ ALREADY_INITIALIZED_CODE,
+ emailClient,
+ NO_GMAIL_GRANT_CODE,
+ SHARED_INBOX_CONFLICT_CODE,
+} from '@service-email/client';
import type {
ListLinksResponse,
ResyncResponse,
@@ -38,6 +43,8 @@ export function useEmailLinksStatus() {
type EmailInitError =
/** The email link has already been initialized*/
| { tag: 'AlreadyInitialized' }
+ /** No Gmail grant to provision from — scope declined at consent or grant removed. */
+ | { tag: 'NoGmailGrant' }
/** The mailbox is already connected by another user; confirm to share it. */
| { tag: 'SharedInboxConflict'; emailAddress: string; ownerEmail: string }
| { tag: 'FailedToInitialize'; message: string };
@@ -90,11 +97,12 @@ function initEmailLink(args?: {
};
return err<void, EmailInitError>(conflictError);
}
- const badRequestError = initResult.error.find(
- // TODO: this is cope but seems like error.code not being set correctly
- (e) => e.message.includes('400')
- );
- const error: EmailInitError = badRequestError
+ if (initResult.error.some((e) => e.code === NO_GMAIL_GRANT_CODE)) {
+ return err<void, EmailInitError>({ tag: 'NoGmailGrant' });
+ }
+ const error: EmailInitError = initResult.error.some(
+ (e) => e.code === ALREADY_INITIALIZED_CODE
+ )
? { tag: 'AlreadyInitialized' }
: { tag: 'FailedToInitialize', message: 'Failed to initialize' };
return err<void, EmailInitError>(error);
diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.ts
index 189e92f0bf..06386998d9 100644
--- a/js/app/packages/service-clients/service-email/client.ts
+++ b/js/app/packages/service-clients/service-email/client.ts
@@ -72,6 +72,21 @@ function emailFetch<T extends ObjectLike = never>(
*/
export const SHARED_INBOX_CONFLICT_CODE = 'SHARED_INBOX_CONFLICT' as const;
+/** Error code `init` returns (HTTP 400) when the inbox is already provisioned. */
+export const ALREADY_INITIALIZED_CODE = 'ALREADY_INITIALIZED' as const;
+
+/**
+ * Error code `init` returns (HTTP 400) when the user holds no Gmail grant to
+ * provision from — the Gmail scope was declined at consent or the grant was
+ * removed. The add-inbox flow re-runs consent and clears it.
+ */
+export const NO_GMAIL_GRANT_CODE = 'NO_GMAIL_GRANT' as const;
+
+type InitErrorCode =
+ | typeof SHARED_INBOX_CONFLICT_CODE
+ | typeof ALREADY_INITIALIZED_CODE
+ | typeof NO_GMAIL_GRANT_CODE;
+
/**
* Error code `patchSettings` returns (HTTP 422) when a signature has images that
* couldn't be fetched/rehosted and would render broken for recipients. The whole
@@ -89,33 +104,43 @@ export const emailClient = {
const query = params.toString();
const path = query ? `/email/init?${query}` : '/email/init';
- return fetchWithToken<EmptyResponse, typeof SHARED_INBOX_CONFLICT_CODE>(
- `${emailHost}${path}`,
- {
- method: 'POST',
- // A custom handler replaces safeFetch's default status mapping, so non-409
- // statuses fall back to the same HTTP_ERROR shape callers already branch on.
- errorResponseHandler: async (response) => {
- if (response.status === 409) {
- const body = (await response
- .json()
- .catch(() => null)) as SharedInboxConflictResponse | null;
- return {
- code: SHARED_INBOX_CONFLICT_CODE,
- // The caller formats the prompt; the fields it needs ride along as JSON.
- message: JSON.stringify({
- emailAddress: body?.email_address ?? '',
- existingOwnerEmail: body?.existing_owner_email ?? '',
- }),
- };
- }
+ return fetchWithToken<EmptyResponse, InitErrorCode>(`${emailHost}${path}`, {
+ method: 'POST',
+ // A custom handler replaces safeFetch's default status mapping. 409 carries
+ // the shared-inbox conflict fields and 400 a machine-readable code; other
+ // statuses fall back to the same HTTP_ERROR shape callers already branch on.
+ errorResponseHandler: async (response) => {
+ if (response.status === 409) {
+ const body = (await response
+ .json()
+ .catch(() => null)) as SharedInboxConflictResponse | null;
return {
- code: 'HTTP_ERROR',
- message: `HTTP error! status: ${response.status}`,
+ code: SHARED_INBOX_CONFLICT_CODE,
+ // The caller formats the prompt; the fields it needs ride along as JSON.
+ message: JSON.stringify({
+ emailAddress: body?.email_address ?? '',
+ existingOwnerEmail: body?.existing_owner_email ?? '',
+ }),
};
- },
- }
- );
+ }
+ if (response.status === 400) {
+ const body = (await response.json().catch(() => null)) as {
+ code?: string;
+ message?: string;
+ } | null;
+ if (
+ body?.code === ALREADY_INITIALIZED_CODE ||
+ body?.code === NO_GMAIL_GRANT_CODE
+ ) {
+ return { code: body.code, message: body.message ?? '' };
+ }
+ }
+ return {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ };
+ },
+ });
},
async getThread(args: {
offset?: number;
diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.ts
index 1afb2a8058..d6bc950296 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -28,6 +28,7 @@ import type {
GetThreadMessagesHandlerParams,
GetThreadParams,
GetThreadResponse,
+ InitErrorCodeResponse,
InitResponse,
InitUserParams,
ListBackfillJobsResponse,
@@ -1485,7 +1486,7 @@ export type initUserResponse200 = {
};
export type initUserResponse400 = {
- data: ErrorResponse;
+ data: InitErrorCodeResponse;
status: 400;
};
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
index 4cea6e2435..eeac0afe76 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
@@ -175,6 +175,7 @@ export * from './getScheduledResponse';
export * from './getThreadMessagesHandlerParams';
export * from './getThreadParams';
export * from './getThreadResponse';
+export * from './initErrorCodeResponse';
export * from './initResponse';
export * from './initResponseBackfillJobId';
export * from './initUserParams';
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/initErrorCodeResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/initErrorCodeResponse.ts
new file mode 100644
index 0000000000..40dba95ad2
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/initErrorCodeResponse.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Structured 400 body carrying a machine-readable code. Clients branch on
+`code` instead of parsing the human message.
+ */
+export interface InitErrorCodeResponse {
+ /** Stable machine-readable error code. */
+ code: string;
+ /** Human-readable explanation. */
+ message: string;
+}
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index f029e02eff..ce931d3867 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -1357,7 +1357,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/InitErrorCodeResponse"
}
}
}
@@ -4137,6 +4137,21 @@
}
}
},
+ "InitErrorCodeResponse": {
+ "type": "object",
+ "description": "Structured 400 body carrying a machine-readable code. Clients branch on\n`code` instead of parsing the human message.",
+ "required": ["code", "message"],
+ "properties": {
+ "code": {
+ "type": "string",
+ "description": "Stable machine-readable error code."
+ },
+ "message": {
+ "type": "string",
+ "description": "Human-readable explanation."
+ }
+ }
+ },
"InitResponse": {
"type": "object",
"required": ["link_id"],
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 6ed3582d49..16f24a4b75 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -1,6 +1,7 @@
use crate::api::ApiContext;
use crate::utils::extract_email_with_response;
use anyhow::Context;
+use authentication_service_client::error::AuthServiceClientError;
use axum::{
extract::{Query, State},
http::StatusCode,
@@ -25,11 +26,17 @@ use thiserror::Error;
use utoipa::ToSchema;
use uuid::Uuid;
+#[cfg(test)]
+mod test;
+
#[derive(Debug, Error, AsRefStr)]
pub enum InitError {
#[error("User is already initialized")]
AlreadyInitialized,
+ #[error("No Gmail grant available to provision from")]
+ NoGmailGrant,
+
#[error("Job limit exceeded")]
TooManyJobs,
@@ -56,12 +63,29 @@ pub enum InitError {
},
}
+/// Stable machine-readable code for [`InitError::AlreadyInitialized`].
+pub const ALREADY_INITIALIZED_CODE: &str = "ALREADY_INITIALIZED";
+
+/// Stable machine-readable code for [`InitError::NoGmailGrant`].
+pub const NO_GMAIL_GRANT_CODE: &str = "NO_GMAIL_GRANT";
+
+/// Structured 400 body carrying a machine-readable code. Clients branch on
+/// `code` instead of parsing the human message.
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct InitErrorCodeResponse {
+ /// Stable machine-readable error code.
+ pub code: String,
+ /// Human-readable explanation.
+ pub message: String,
+}
+
impl IntoResponse for InitError {
fn into_response(self) -> Response {
let status_code = match &self {
- InitError::AlreadyInitialized | InitError::BadRequest(_) | InitError::Parse(_) => {
- StatusCode::BAD_REQUEST
- }
+ InitError::AlreadyInitialized
+ | InitError::NoGmailGrant
+ | InitError::BadRequest(_)
+ | InitError::Parse(_) => StatusCode::BAD_REQUEST,
InitError::TooManyJobs => StatusCode::TOO_MANY_REQUESTS,
InitError::EnqueueError | InitError::DatabaseError(_) | InitError::GmailError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
@@ -83,6 +107,22 @@ impl IntoResponse for InitError {
}),
)
.into_response(),
+ InitError::AlreadyInitialized => (
+ status_code,
+ Json(InitErrorCodeResponse {
+ code: ALREADY_INITIALIZED_CODE.to_string(),
+ message: InitError::AlreadyInitialized.to_string(),
+ }),
+ )
+ .into_response(),
+ InitError::NoGmailGrant => (
+ status_code,
+ Json(InitErrorCodeResponse {
+ code: NO_GMAIL_GRANT_CODE.to_string(),
+ message: InitError::NoGmailGrant.to_string(),
+ }),
+ )
+ .into_response(),
other => (status_code, other.to_string()).into_response(),
}
}
@@ -137,7 +177,7 @@ pub struct InitParams {
operation_id = "init_user",
responses(
(status = 200, body=InitResponse),
- (status = 400, body=ErrorResponse),
+ (status = 400, body=InitErrorCodeResponse),
(status = 401, body=ErrorResponse),
(status = 409, body=SharedInboxConflictResponse),
(status = 500, body=ErrorResponse),
@@ -504,13 +544,8 @@ pub async fn handler(
enforce_backfill_rate_limit(&ctx.db, &user_context.fusion_user_id, &email).await?;
- let gmail_token = email_service::util::gmail::auth::fetch_gmail_token_no_cache(
- &user_context,
- &ctx.redis_client,
- &ctx.auth_service_client,
- )
- .await
- .map_err(|_| InitError::BadRequest("Failed to fetch Gmail token".to_string()))?;
+ let gmail_token =
+ fetch_gmail_token_for_email(&ctx, &user_context.fusion_user_id, &email).await?;
let watch_response = register_watch_recovering(&ctx.gmail_client, &gmail_token).await?;
@@ -682,12 +717,27 @@ async fn register_watch_recovering(
.stop_watch(access_token)
.await
.context("Failed to stop stale Gmail watch before retry")?;
- Ok(client.register_watch(access_token).await?)
+ client
+ .register_watch(access_token)
+ .await
+ .map_err(classify_watch_error)
}
- Err(e) => Err(e.into()),
+ Err(e) => Err(classify_watch_error(e)),
}
}
+/// Maps a watch-registration failure to its init error. Google refreshes tokens
+/// regardless of granted scopes, so a grant missing the Gmail scope passes the
+/// token fetch and is first rejected here with a 403 — an expected outcome
+/// (scope declined at consent), logged at debug so it doesn't page.
+fn classify_watch_error(e: GmailError) -> InitError {
+ if matches!(e, GmailError::Forbidden) {
+ tracing::debug!("gmail watch rejected for insufficient scope, no usable gmail grant");
+ return InitError::NoGmailGrant;
+ }
+ e.into()
+}
+
/// Fetches a Gmail access token scoped to a specific linked email. Use this instead
/// of going through the `UserContext`-keyed path when the target inbox is not the
/// JWT subject's primary email.
@@ -707,10 +757,22 @@ async fn fetch_gmail_token_for_email(
email::outbound::fetch_gmail_access_token_no_cache(&key, &conn, &ctx.auth_service_client)
.await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to fetch gmail token for linked email");
- InitError::BadRequest("Failed to fetch Gmail token for linked email".to_string())
- })
+ .map_err(classify_token_fetch_error)
+}
+
+/// Maps a token-fetch failure to its init error. A 404 from the auth service
+/// means no Gmail grant exists for the requested inbox — an expected outcome
+/// (scope declined or grant removed), logged at debug so it doesn't page.
+fn classify_token_fetch_error(e: anyhow::Error) -> InitError {
+ if matches!(
+ e.downcast_ref::<AuthServiceClientError>(),
+ Some(AuthServiceClientError::NotFound)
+ ) {
+ tracing::debug!(error=?e, "no gmail grant for requested inbox");
+ return InitError::NoGmailGrant;
+ }
+ tracing::error!(error=?e, "unable to fetch gmail token for requested inbox");
+ InitError::BadRequest("Failed to fetch Gmail token".to_string())
}
/// Upserts the `email_links` row and seeds the gmail history entry for an already-registered
diff --git a/rust/cloud-storage/email_service/src/api/email/init/test.rs b/rust/cloud-storage/email_service/src/api/email/init/test.rs
new file mode 100644
index 0000000000..735162f4ee
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/init/test.rs
@@ -0,0 +1,70 @@
+use super::*;
+use anyhow::anyhow;
+
+async fn body_json(response: Response) -> serde_json::Value {
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ serde_json::from_slice(&bytes).unwrap()
+}
+
+#[tokio::test]
+async fn no_gmail_grant_is_a_coded_400() {
+ let response = InitError::NoGmailGrant.into_response();
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let body = body_json(response).await;
+ assert_eq!(body["code"], NO_GMAIL_GRANT_CODE);
+}
+
+#[tokio::test]
+async fn already_initialized_is_a_coded_400() {
+ let response = InitError::AlreadyInitialized.into_response();
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ let body = body_json(response).await;
+ assert_eq!(body["code"], ALREADY_INITIALIZED_CODE);
+}
+
+#[test]
+fn auth_service_not_found_classifies_as_no_gmail_grant() {
+ let err = anyhow::Error::new(AuthServiceClientError::NotFound)
+ .context("Failed to get Google access token from auth service");
+ assert!(matches!(
+ classify_token_fetch_error(err),
+ InitError::NoGmailGrant
+ ));
+}
+
+#[test]
+fn other_token_fetch_failures_stay_bad_request() {
+ for err in [
+ anyhow!("connection refused"),
+ anyhow::Error::new(AuthServiceClientError::Unauthorized),
+ ] {
+ assert!(matches!(
+ classify_token_fetch_error(err),
+ InitError::BadRequest(_)
+ ));
+ }
+}
+
+#[test]
+fn watch_forbidden_classifies_as_no_gmail_grant() {
+ assert!(matches!(
+ classify_watch_error(GmailError::Forbidden),
+ InitError::NoGmailGrant
+ ));
+}
+
+#[test]
+fn other_watch_failures_stay_gmail_errors() {
+ for err in [
+ GmailError::Unauthorized,
+ GmailError::RateLimitExceeded,
+ GmailError::ApiError("(500): boom".to_string()),
+ ] {
+ assert!(matches!(
+ classify_watch_error(err),
+ InitError::GmailError(_)
+ ));
+ }
+}
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index 2c41588ccc..678fea66ca 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -14,7 +14,7 @@ use crate::api::email::drafts::add_attachment::{
use crate::api::email::drafts::add_forwarded_attachment::{
AddForwardedAttachmentRequest, AddForwardedAttachmentResponse,
};
-use crate::api::email::init::{InitResponse, SharedInboxConflictResponse};
+use crate::api::email::init::{InitErrorCodeResponse, InitResponse, SharedInboxConflictResponse};
use crate::api::email::labels::create::CreateLabelRequest;
use crate::api::email::labels::create::CreateLabelResponse;
use crate::api::email::links::list::ListLinksResponse;
@@ -126,6 +126,7 @@ use utoipa::OpenApi;
AddForwardedAttachmentRequest,
AddForwardedAttachmentResponse,
// Init types
+ InitErrorCodeResponse,
InitResponse,
SharedInboxConflictResponse,
// Label types
diff --git a/rust/cloud-storage/email_service/src/util/gmail/auth.rs b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
index c317721d5e..be1ae40921 100644
--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs
+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
@@ -212,61 +212,6 @@ pub async fn fetch_gmail_token_usercontext_response(
})
}
-/// Fetches a user's gmail token directly from the auth service, bypassing the Redis cache.
-/// Used by the init endpoint where we always want a fresh token. Resolves to the JWT
-/// subject's primary inbox.
-#[tracing::instrument(skip(user_context, redis_client, auth_service_client))]
-pub async fn fetch_gmail_token_no_cache(
- user_context: &UserContext,
- redis_client: &RedisClient,
- auth_service_client: &AuthServiceClient,
-) -> Result<String, Response> {
- let key = TokenCacheKey::new(
- &user_context.fusion_user_id,
- MacroUserIdStr::parse_from_str(&user_context.user_id)
- .map(|id| id.email_str().to_string())
- .map_err(|e| {
- tracing::error!(error=?e, user_id=%user_context.user_id, "unable to derive email from user id");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to get gmail access token".into(),
- }),
- )
- .into_response()
- })?,
- UserProvider::Gmail.as_str(),
- );
-
- let conn = redis_client
- .inner
- .get_multiplexed_async_connection()
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to connect to redis");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to get gmail access token".into(),
- }),
- )
- .into_response()
- })?;
-
- email::outbound::fetch_gmail_access_token_no_cache(&key, &conn, auth_service_client)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get gmail access token from auth service");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to get gmail access token".into(),
- }),
- )
- .into_response()
- })
-}
-
/// Fetches the gmail access token, first looking in the redis cache then hitting the auth service.
///
/// Delegates to [`email::outbound::fetch_gmail_access_token`].
diff --git a/rust/cloud-storage/gmail_client/src/watch.rs b/rust/cloud-storage/gmail_client/src/watch.rs
index 90f92f91b8..bf531d40c0 100644
--- a/rust/cloud-storage/gmail_client/src/watch.rs
+++ b/rust/cloud-storage/gmail_client/src/watch.rs
@@ -51,6 +51,13 @@ pub(crate) async fn register_watch(
return Err(GmailError::Conflict(error_body));
}
+ // An access token minted from a grant without the Gmail scope is rejected
+ // with a 403. Typed so callers can treat it as a missing grant, matching
+ // the 403 mapping elsewhere in this client.
+ if status == reqwest::StatusCode::FORBIDDEN {
+ return Err(GmailError::Forbidden);
+ }
+
return Err(GmailError::ApiError(format!(
"({}): {}",
status, error_body