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
feat(auth): refuse Google consents that leave out email and explain the retry (#9136)
gbirmanb2897b58511a
diff --git a/Cargo.lock b/Cargo.lockindex 51de83d2ea..6ce8782f9b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2208,6 +2208,7 @@ dependencies = ["model","model-entity","model_notifications",+ "models_email","models_permissions","native_app_service","non_empty",diff --git a/apps/web/src/features/auth/EmailAuth.test.tsx b/apps/web/src/features/auth/EmailAuth.test.tsxindex 0717dc9deb..968162037a 100644--- a/apps/web/src/features/auth/EmailAuth.test.tsx+++ b/apps/web/src/features/auth/EmailAuth.test.tsx@@ -22,6 +22,9 @@ const mocks = vi.hoisted(() => ({track: vi.fn(),openAddInbox: vi.fn(),fetchProviders: vi.fn(),+ peek: vi.fn(),+ custom: vi.fn(),+ dismiss: vi.fn(),}));vi.mock('@solidjs/router', () => ({useNavigate: () => mocks.navigate,@@ -46,13 +49,19 @@ vi.mock('@app/lib/analytics/analytics-context', () => ({useAnalytics: () => ({ pageView: vi.fn(), track: mocks.track }),}));vi.mock('@core/component/Toast/Toast', () => ({- toast: { success: mocks.success, failure: mocks.failure },+ toast: {+ success: mocks.success,+ failure: mocks.failure,+ custom: mocks.custom,+ dismiss: mocks.dismiss,+ },}));vi.mock('@core/constant/SettingsState', () => ({restoreSettingsReturnTo: vi.fn(),}));vi.mock('@core/email-link/return-layout', () => ({consumeInboxLinkReturn: mocks.restore,+ readInboxLinkReturn: mocks.peek,}));vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));vi.mock('@core/mobile/isNativeMobilePlatform', () => ({@@ -118,6 +127,11 @@ beforeEach(() => {});mocks.refetch.mockResolvedValue({});mocks.restore.mockReturnValue({ url: '/calendar/week' });+ mocks.peek.mockReturnValue({+ url: '/calendar/week',+ scopes: 'gmail_and_calendar',+ });+ mocks.custom.mockReturnValue(7);mocks.init.mockReturnValue(okAsync(undefined));});afterEach(cleanup);@@ -263,6 +277,56 @@ describe('consent that ended without a grant', () => {expect(screen.getByRole('status').textContent).toBe('loading');});+ it('explains a consent that left out email with a prompt that retries the same request', async () => {+ mocks.searchParams = {+ link_id: 'oauth-link',+ email_link_error: 'gmail_not_granted',+ provider: 'gmail',+ };+ render(() => <EmailLinkCallback />);+ await waitFor(() => expect(mocks.custom).toHaveBeenCalledOnce());+ const [prompt, options] = mocks.custom.mock.calls[0] as [+ { title: string; actions: Array<{ label: string; onClick: () => void }> },+ { persistent: boolean; region: string },+ ];+ expect(prompt.title).toBe('Email access required');+ expect(options).toEqual({ persistent: true, region: 'prompt-region' });+ expect(mocks.init).not.toHaveBeenCalled();+ expect(mocks.failure).not.toHaveBeenCalled();+ expect(mocks.navigate).toHaveBeenCalledWith('/calendar/week', {+ replace: true,+ });+ expect(mocks.track).toHaveBeenCalledExactlyOnceWith(+ 'email_link_callback_result',+ { outcome: 'gmail_not_granted' }+ );++ expect(prompt.actions.map((action) => action.label)).toEqual(['Try again']);+ prompt.actions[0].onClick();+ expect(mocks.dismiss).toHaveBeenCalledWith(7);+ expect(mocks.openAddInbox).toHaveBeenCalledExactlyOnceWith({+ scopes: 'gmail_and_calendar',+ });+ });++ it('retries with email alone when the refused flow left no stash', async () => {+ mocks.peek.mockReturnValue(undefined);+ mocks.searchParams = {+ link_id: 'oauth-link',+ email_link_error: 'gmail_not_granted',+ provider: 'gmail',+ };+ render(() => <EmailLinkCallback />);+ await waitFor(() => expect(mocks.custom).toHaveBeenCalledOnce());+ const [prompt] = mocks.custom.mock.calls[0] as [+ { actions: Array<{ onClick: () => void }> },+ ];+ prompt.actions[0].onClick();+ expect(mocks.openAddInbox).toHaveBeenCalledExactlyOnceWith({+ scopes: undefined,+ });+ });+it('returns quietly when the user cancelled on the consent screen', async () => {mocks.searchParams = {link_id: 'oauth-link',diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsxindex 3c00045880..09d2cfcf8b 100644--- a/apps/web/src/features/auth/EmailAuth.tsx+++ b/apps/web/src/features/auth/EmailAuth.tsx@@ -12,7 +12,10 @@ import { LoadingBlock } from '@core/component/LoadingBlock';import { toast } from '@core/component/Toast/Toast';import { settingsTabToSlug } from '@core/constant/settingsTabsConfig';import { useEmailLinks } from '@core/email-link';-import { consumeInboxLinkReturn } from '@core/email-link/return-layout';+import {+ consumeInboxLinkReturn,+ readInboxLinkReturn,+} from '@core/email-link/return-layout';import { isMobile } from '@core/mobile/isMobile';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { fireAndForget } from '@core/util/fireAndForget';@@ -24,6 +27,7 @@ import {invalidateAllAfterLogin,useUserInfoQuery,} from '@queries/auth/user-info';+import type { ConsentScopes } from '@service-auth/client';import { useNavigate, useSearchParams } from '@solidjs/router';import { Button } from '@ui';import {@@ -132,23 +136,57 @@ const ADMIN_CONSENT_GRANTED_NOTICE = 'admin_consent_granted';/*** The `email_link_error` values the auth service redirects back with when a- * consent screen ends without a grant. Anything else is a generic failure.+ * consent screen ends without a usable grant. Anything else is a generic+ * failure.*/const ADMIN_CONSENT_REQUIRED_ERROR = 'admin_consent_required';const CONSENT_CANCELLED_ERROR = 'cancelled';+/** Google's consent came back without the email permissions; nothing was connected. */+const GMAIL_NOT_GRANTED_ERROR = 'gmail_not_granted';const stringParam = (value: string | string[] | undefined) =>typeof value === 'string' ? value : null;+/**+ * Google's consent left the email permissions unchecked, so nothing was+ * connected and the partial grant was revoked. The prompt outlives the+ * callback page and stays until the person dismisses it or tries again with+ * the permissions the flow asked for.+ */+function promptForEmailAccess(scopes: ConsentScopes | undefined) {+ const toastId = toast.custom(+ {+ title: 'Email access required',+ content: () =>+ "Macro connects an account's email and calendar together, so keep the email permissions checked. The account was not connected.",+ actions: [+ {+ label: 'Try again',+ onClick: () => {+ toast.dismiss(toastId);+ openAddInboxDialog({ scopes });+ },+ },+ ],+ },+ {+ persistent: true,+ region: isMobile() ? 'mobile-prompt-region' : 'prompt-region',+ }+ );+}+/*** Handles the OAuth callback after an already-authenticated user adds another* inbox via /link/gmail or /link/outlook. Reads `link_id` from the query string* and invokes init to provision the second `email_links` row. Falls back to a* toast on failure.*- * A consent screen that ended without a grant arrives with `email_link_error`- * instead: a cancel goes straight back, a tenant that needs admin approval- * gets the dialog with the approval link, and anything else gets a toast.+ * A consent screen that ended without a usable grant arrives with+ * `email_link_error` instead: a cancel goes straight back, a tenant that needs+ * admin approval gets the dialog with the approval link, a Google consent that+ * left out the email permissions gets a prompt that stays until dismissed and+ * retries the same request, and anything else gets a toast.* An administrator who approved the tenant arrives with `email_link_notice`.** Web consent navigates the page; desktop returns from the system browser via@@ -288,6 +326,16 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {navigateAfterLink(linkId);return;}+ if (error === GMAIL_NOT_GRANTED_ERROR) {+ trackOutcome('gmail_not_granted');+ // The retry asks for what this flow asked for: a calendar entry point+ // wants email and calendar together, not email alone.+ promptForEmailAccess(+ linkId ? readInboxLinkReturn(linkId)?.scopes : undefined+ );+ navigateAfterLink(linkId);+ return;+ }if (error !== ADMIN_CONSENT_REQUIRED_ERROR) {toast.failure('Failed to connect your account. Please try again.');navigateAfterLink(linkId);diff --git a/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx b/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsxindex 8d097b5c23..cd3224215c 100644--- a/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx+++ b/apps/web/src/features/calendar/components/CalendarSettingsDropdown.tsx@@ -342,8 +342,11 @@ function DesktopCalendarSettings(props: {onSelect={controls.connectAnotherAccount}><PlusIcon class="size-3.5 shrink-0 text-ink-muted" />- <span class="min-w-0 flex-1 truncate">- Connect another account+ <span class="flex min-w-0 flex-1 flex-col">+ <span class="truncate">Connect another account</span>+ <span class="truncate text-xs text-ink-muted">+ Email and calendar together+ </span></span></Dropdown.Item></Show>@@ -551,8 +554,11 @@ function MobileCalendarSettings(props: {}}><PlusIcon class="size-4 shrink-0 text-ink-muted" />- <span class="min-w-0 flex-1 truncate">- Connect another account+ <span class="flex min-w-0 flex-1 flex-col">+ <span class="truncate">Connect another account</span>+ <span class="truncate text-xs text-ink-muted">+ Email and calendar together+ </span></span></MobileDrawer.Item></Show>diff --git a/apps/web/src/features/inbox/AddInboxDialog.tsx b/apps/web/src/features/inbox/AddInboxDialog.tsxindex ddf15288f5..2f97002659 100644--- a/apps/web/src/features/inbox/AddInboxDialog.tsx+++ b/apps/web/src/features/inbox/AddInboxDialog.tsx@@ -1,9 +1,15 @@import { useAddInboxFlow } from '@core/email-link';import { EmailProviderDialog } from '@core/email-link/ProviderDialog';import { fetchEmailConnectionProviders } from '@queries/auth/outlook-link';+import type { ConsentScopes } from '@service-auth/client';import { createEffect, createSignal, onCleanup } from 'solid-js';-const [isOpen, setIsOpen] = createSignal(false);+type AddInboxRequest = {+ /** The permissions to ask consent for; the mailbox alone when omitted. */+ scopes?: ConsentScopes;+};++const [request, setRequest] = createSignal<AddInboxRequest | null>(null);/*** Requests the add-inbox confirmation dialog. Rendered at the app root@@ -15,9 +21,10 @@ const [isOpen, setIsOpen] = createSignal(false);* multi-inbox paywall — so callers can invoke the add-inbox flow directly* without a client-side gate that would have to mirror the backend's rule.*/-export const openAddInboxDialog = () => setIsOpen(true);+export const openAddInboxDialog = (options?: AddInboxRequest) =>+ setRequest({ scopes: options?.scopes });-export const isAddInboxDialogOpen = isOpen;+export const isAddInboxDialogOpen = () => request() !== null;/*** Confirmation step before the add-inbox OAuth redirect. Confirming kicks off@@ -28,7 +35,7 @@ export function AddInboxDialog() {const [pending, setPending] = createSignal(false);const [outlookAvailable, setOutlookAvailable] = createSignal(false);createEffect(() => {- if (!isOpen()) return;+ if (!isAddInboxDialogOpen()) return;let current = true;setOutlookAvailable(false);void fetchEmailConnectionProviders()@@ -41,7 +48,7 @@ export function AddInboxDialog() {});});- onCleanup(() => setIsOpen(false));+ onCleanup(() => setRequest(null));const handleConfirm = async (provider: 'GMAIL' | 'OUTLOOK') => {if (pending()) return;@@ -49,17 +56,19 @@ export function AddInboxDialog() {// On web this navigates away; on native iOS the OAuth completes in place// and resolves, so the dialog dismisses itself.try {- await addInbox({ provider });+ await addInbox({ provider, scopes: request()?.scopes });} finally {setPending(false);- setIsOpen(false);+ setRequest(null);}};return (<EmailProviderDialog- open={isOpen()}- onOpenChange={setIsOpen}+ open={isAddInboxDialogOpen()}+ onOpenChange={(open) => {+ if (!open) setRequest(null);+ }}onSelect={handleConfirm}disabled={pending()}outlookAvailable={outlookAvailable()}diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.tsindex 93074ae462..0f50f0508b 100644--- a/apps/web/src/lib/analytics/app-events.ts+++ b/apps/web/src/lib/analytics/app-events.ts@@ -234,6 +234,7 @@ export type AppEvents = {| 'shared_inbox_conflict'| 'payment_required'| 'no_gmail_grant'+ | 'gmail_not_granted'| 'failed'| 'exception'| 'missing_link_id';diff --git a/apps/web/src/lib/core/email-link/ProviderDialog.tsx b/apps/web/src/lib/core/email-link/ProviderDialog.tsxindex 19ae831060..d24e8964c1 100644--- a/apps/web/src/lib/core/email-link/ProviderDialog.tsx+++ b/apps/web/src/lib/core/email-link/ProviderDialog.tsx@@ -35,6 +35,10 @@ export function EmailProviderDialog(<Dialog.Description class="text-ink-muted text-sm/tight">Connect Gmail, Outlook.com, or an individual Microsoft 365 account.</Dialog.Description>+ <p class="text-ink-muted text-sm/tight">+ Macro connects an account's email and calendar together, so keep the+ email permissions checked on the provider's screen.+ </p><Buttonvariant="secondary"disabled={props.disabled}diff --git a/apps/web/src/lib/core/email-link/index.ts b/apps/web/src/lib/core/email-link/index.tsindex 118aadbc93..333c67a0b2 100644--- a/apps/web/src/lib/core/email-link/index.ts+++ b/apps/web/src/lib/core/email-link/index.ts@@ -369,6 +369,7 @@ export function useAddInboxFlow() {// Preserve the layout so either callback can put it back.rememberInboxLinkReturn(result.value.link_id, {url: `${toBaseRelative(window.location.pathname)}${window.location.search}${window.location.hash}`,+ scopes,});const authorizationUrl = inboxAuthorizationUrl(result.value.authorization_url,diff --git a/apps/web/src/lib/core/email-link/native-link.test.ts b/apps/web/src/lib/core/email-link/native-link.test.tsindex e0435f2aa7..de7789d5e7 100644--- a/apps/web/src/lib/core/email-link/native-link.test.ts+++ b/apps/web/src/lib/core/email-link/native-link.test.ts@@ -122,6 +122,7 @@ describe('desktop account linking', () => {);expect(consumeInboxLinkReturn('pending-link')).toEqual({url: '/home/~/settings/connections?view=all#selection',+ scopes,});expect(window.location.href).toBe(originalLocation);expect(mocks.authenticate).not.toHaveBeenCalled();@@ -158,6 +159,7 @@ describe('desktop account linking', () => {);expect(consumeInboxLinkReturn('outlook-link')).toEqual({url: '/home/~/settings/connections?view=all#selection',+ scopes,});expect(window.location.href).toBe(originalLocation);expect(mocks.authenticate).not.toHaveBeenCalled();diff --git a/apps/web/src/lib/core/email-link/return-layout.test.ts b/apps/web/src/lib/core/email-link/return-layout.test.tsindex 5b29bba47e..73eaccbd94 100644--- a/apps/web/src/lib/core/email-link/return-layout.test.ts+++ b/apps/web/src/lib/core/email-link/return-layout.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import {consumeInboxLinkReturn,+ readInboxLinkReturn,rememberInboxLinkReturn,} from './return-layout';@@ -22,6 +23,45 @@ describe('inbox link return layout', () => {});});+ it('round-trips the permissions the flow asked consent for', () => {+ rememberInboxLinkReturn(LINK_ID, {+ url: '/calendar/week',+ scopes: 'gmail_and_calendar',+ });++ expect(consumeInboxLinkReturn(LINK_ID)).toEqual({+ url: '/calendar/week',+ scopes: 'gmail_and_calendar',+ });+ });++ it('drops permissions it does not recognize', () => {+ sessionStorage.setItem(+ 'macro:inbox-link:return-layout',+ JSON.stringify({ linkId: LINK_ID, url: '/home', scopes: 'everything' })+ );++ expect(consumeInboxLinkReturn(LINK_ID)).toEqual({ url: '/home' });+ });++ it('reads without clearing, so the callback can look before it leaves', () => {+ rememberInboxLinkReturn(LINK_ID, { url: '/home', scopes: 'gmail' });++ expect(readInboxLinkReturn(LINK_ID)).toEqual({+ url: '/home',+ scopes: 'gmail',+ });+ expect(readInboxLinkReturn(LINK_ID)).toEqual({+ url: '/home',+ scopes: 'gmail',+ });+ expect(readInboxLinkReturn('other-link')).toBeUndefined();+ expect(consumeInboxLinkReturn(LINK_ID)).toEqual({+ url: '/home',+ scopes: 'gmail',+ });+ });+it('clears the stash so a second read finds nothing', () => {rememberInboxLinkReturn(LINK_ID, { url: '/home' });diff --git a/apps/web/src/lib/core/email-link/return-layout.ts b/apps/web/src/lib/core/email-link/return-layout.tsindex 6ccde66da1..938d0b66a4 100644--- a/apps/web/src/lib/core/email-link/return-layout.ts+++ b/apps/web/src/lib/core/email-link/return-layout.ts@@ -1,5 +1,13 @@+import type { ConsentScopes } from '@service-auth/client';+const RETURN_LAYOUT_KEY = 'macro:inbox-link:return-layout';+const CONSENT_SCOPES: ReadonlyArray<ConsentScopes> = [+ 'gmail',+ 'gmail_and_calendar',+ 'calendar',+];+/** Where the app should land once the inbox consent round trip comes back. */export type InboxLinkReturn = {/**@@ -8,6 +16,12 @@ export type InboxLinkReturn = {* survives with it.*/url: string;+ /**+ * The permissions the flow asked consent for, so a refused consent can be+ * retried with the same request (a calendar entry point asks for the+ * mailbox and calendar together).+ */+ scopes?: ConsentScopes;};type StoredInboxLinkReturn = InboxLinkReturn & { linkId: string };@@ -40,11 +54,11 @@ export function rememberInboxLinkReturn(}/**- * Read and clear the layout stashed by {@link rememberInboxLinkReturn} for- * this link. Returns undefined when nothing was stashed or the stash belongs- * to a different flow.+ * Read the layout stashed by {@link rememberInboxLinkReturn} for this link+ * without clearing it. Returns undefined when nothing was stashed or the stash+ * belongs to a different flow.*/-export function consumeInboxLinkReturn(+export function readInboxLinkReturn(linkId: string): InboxLinkReturn | undefined {let raw: string | null;@@ -62,15 +76,29 @@ export function consumeInboxLinkReturn(stored = undefined;}+ if (!stored || stored.linkId !== linkId || typeof stored.url !== 'string') {+ return undefined;+ }+ const scopes = CONSENT_SCOPES.find((value) => value === stored.scopes);+ return scopes ? { url: stored.url, scopes } : { url: stored.url };+}++/**+ * Read and clear the layout stashed by {@link rememberInboxLinkReturn} for+ * this link. Returns undefined when nothing was stashed or the stash belongs+ * to a different flow.+ */+export function consumeInboxLinkReturn(+ linkId: string+): InboxLinkReturn | undefined {+ const stored = readInboxLinkReturn(linkId);+// A stash that can't be matched is dead weight either way, so drop it.try {sessionStorage.removeItem(RETURN_LAYOUT_KEY);} catch {- // Nothing to do — the read already succeeded.+ // Nothing to do — the read already happened.}- if (!stored || stored.linkId !== linkId || typeof stored.url !== 'string') {- return undefined;- }- return { url: stored.url };+ return stored;}diff --git a/crates/fusionauth/src/google.rs b/crates/fusionauth/src/google.rsindex a93df2cd7a..44e72dd8ed 100644--- a/crates/fusionauth/src/google.rs+++ b/crates/fusionauth/src/google.rs@@ -6,7 +6,17 @@ use crate::{/// Google OAuth token operations.pub mod oauth;+#[cfg(test)]+mod test;+impl FusionAuthClient {+ /// Revokes a Google grant at Google, so the account's next consent screen+ /// starts from nothing. `token` is an access or refresh token of the grant.+ #[tracing::instrument(name = "google.revoke_grant", skip(self, token), err)]+ pub async fn revoke_google_grant(&self, token: &str) -> Result<()> {+ oauth::revoke_token(&self.unauth_client, oauth::GOOGLE_REVOKE_URL, token).await+ }+/// Refreshes a Google OAuth2 access token using a refresh token.#[tracing::instrument(skip(self, refresh_token), fields(client_id=%self.client_id))]pub async fn refresh_google_token(diff --git a/crates/fusionauth/src/google/oauth.rs b/crates/fusionauth/src/google/oauth.rsindex 67eb056b13..7960da43d1 100644--- a/crates/fusionauth/src/google/oauth.rs+++ b/crates/fusionauth/src/google/oauth.rs@@ -108,6 +108,9 @@ pub(crate) async fn refresh_google_token(#[derive(Debug, serde::Deserialize)]/// Response from exchanging a Google authorization code for tokens.pub struct GoogleExchangeTokenResponse {+ /// The access token.+ #[serde(default)]+ pub access_token: String,/// The refresh token.#[serde(default)]pub refresh_token: String,@@ -118,6 +121,48 @@ pub struct GoogleExchangeTokenResponse {pub scope: String,}+/// Google's token revocation endpoint. Revoking either token of a grant+/// revokes the whole grant, so the next consent screen lists every scope again.+/// See https://developers.google.com/identity/protocols/oauth2/web-server#tokenrevoke+pub(crate) const GOOGLE_REVOKE_URL: &str = "https://oauth2.googleapis.com/revoke";++/// Revokes the grant behind `token` (an access or refresh token) at `endpoint`.+/// Google answers an unknown or already revoked token with 400 `invalid_token`,+/// which counts as revoked so the call is safe to repeat.+pub(crate) async fn revoke_token(+ client: &UnauthedClient,+ endpoint: &str,+ token: &str,+) -> Result<()> {+ let response = client+ .client()+ .post(endpoint)+ .form(&[("token", token)])+ .timeout(Duration::from_secs(10))+ .send()+ .await+ .map_err(|e| {+ FusionAuthClientError::Generic(GenericErrorResponse {+ message: e.to_string(),+ })+ })?;++ match response.status() {+ reqwest::StatusCode::OK | reqwest::StatusCode::BAD_REQUEST => Ok(()),+ status => {+ let body = response.text().await.map_err(|e| {+ FusionAuthClientError::Generic(GenericErrorResponse {+ message: e.to_string(),+ })+ })?;+ tracing::error!(%status, body=%body, "unexpected response from the Google revocation endpoint");+ Err(FusionAuthClientError::Generic(GenericErrorResponse {+ message: format!("Google token revocation failed with status {status}: {body}"),+ }))+ }+ }+}+#[derive(Debug, serde::Serialize)]struct TokenExchangeRequest {client_id: String,diff --git a/crates/fusionauth/src/google/test.rs b/crates/fusionauth/src/google/test.rsnew file mode 100644index 0000000000..543c12800a--- /dev/null+++ b/crates/fusionauth/src/google/test.rs@@ -0,0 +1,72 @@+use wiremock::matchers::{body_string, header, method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++use crate::{UnauthedClient, error::FusionAuthClientError};++use super::oauth::revoke_token;++#[tokio::test]+async fn revoke_token_posts_the_token_form_encoded() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/revoke"))+ .and(header("content-type", "application/x-www-form-urlencoded"))+ .and(body_string("token=partial-grant-refresh-token"))+ .respond_with(ResponseTemplate::new(200))+ .expect(1)+ .mount(&server)+ .await;++ revoke_token(+ &UnauthedClient::new(),+ &format!("{}/revoke", server.uri()),+ "partial-grant-refresh-token",+ )+ .await+ .expect("revocation should succeed");+}++#[tokio::test]+async fn revoke_token_treats_an_invalid_token_as_revoked() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/revoke"))+ .respond_with(ResponseTemplate::new(400).set_body_string(r#"{"error":"invalid_token"}"#))+ .expect(1)+ .mount(&server)+ .await;++ revoke_token(+ &UnauthedClient::new(),+ &format!("{}/revoke", server.uri()),+ "already-revoked",+ )+ .await+ .expect("an invalid token is already revoked");+}++#[tokio::test]+async fn revoke_token_reports_a_server_error() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/revoke"))+ .respond_with(ResponseTemplate::new(503).set_body_string("unavailable"))+ .expect(1)+ .mount(&server)+ .await;++ let error = revoke_token(+ &UnauthedClient::new(),+ &format!("{}/revoke", server.uri()),+ "token",+ )+ .await+ .expect_err("a server error must surface");++ match error {+ FusionAuthClientError::Generic(response) => {+ assert!(response.message.contains("503"), "{}", response.message);+ }+ other => panic!("expected a generic error, got {other:?}"),+ }+}diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex fceee970eb..a1516ec087 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -483,7 +483,15 @@ Events require connecting a Google account (`Connect calendar`). Thesection listing each connected account with a per-account `Enable` (grant calendar),`Reconnect` (expired Google authorization), or `Turn off` action, plus`Connect another account` to connect a new Google account-(email + calendar).+(email + calendar; the item and the `Connect email` dialog both say the email+and calendar connect together). A Google consent that leaves the email+permissions unchecked connects nothing: the callback returns to the calendar+with a persistent `Email access required` prompt whose `Try again` reopens+`Connect email` asking for the same permissions. The auth service also tries+to revoke the partial grant at Google, unless an inbox for that address still+works on it; when the revocation succeeds, Google lists every permission again+on the retry instead of folding the earlier calendar grant into an "already+has some access" notice.`Turn off` keeps its confirmation open with `Turning off…` until removal finishes;re-enabling is not offered while the old calendar is still being deleted. Reconnectingdiff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.mdindex 74e776b79a..28ca8a157c 100644--- a/docs/agent-guide/login.md+++ b/docs/agent-guide/login.md@@ -36,6 +36,16 @@ connected, that returning from consent shows the second account, and thatcanceling leaves the app usable. iOS and Android continue to use their nativeauthentication sessions.+A consent that ends without a usable grant returns to the callback with+`email_link_error` instead of a provisionable `link_id`: `cancelled` returns+quietly, `admin_consent_required` shows the Microsoft approval dialog,+`gmail_not_granted` (the email permissions were left unchecked on Google's+screen, so nothing was connected and the auth service tried, best effort, to+revoke the partial grant at Google unless an inbox for that address still+works on it) shows a persistent `Email access required`+prompt whose `Try again` reopens `Connect email`, and anything else shows a+failure toast.+## Temporary open signup in DevelopOnce the temporary authentication-service override is deployed, Develop acceptsdiff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.mdindex e7c3ddae41..9b5d2384da 100644--- a/services/authentication_service/AGENTS.md+++ b/services/authentication_service/AGENTS.md@@ -104,6 +104,16 @@ inputs cannot select an agent, and ordinary user credentials remain unattributedcode redirects a link flow to its `original_url` with `email_link_error`(`admin_consent_required`, `cancelled`, `failed`); only the `AADSTS` codefrom `error_description` is logged, never the description.+- A Google consent that asked for the mailbox but came back without+ `gmail.modify` (the user left the Gmail boxes unchecked) is refused in the+ Google callback before any identity-provider link is written or replaced:+ the pending row is deleted, the partial grant is revoked at Google so the+ next consent screen lists every scope again, and the flow returns with+ `email_link_error=gmail_not_granted`. Google's revocation drops the account's+ whole grant to Macro, so it is skipped when an inbox for that address still+ works (`needs_reauth` false); the refusal stands either way. Mirrors+ Outlook's required-scope check in `src/domain/microsoft.rs`; Macro has no+ mailbox-less link for either provider.- `/oauth/redirect` without a code answers "Sign-in failed" and logs`auth_handoff_failure=missing_code` with FusionAuth's error. `invalid_origin`("Invalid origin uri <origin>") means the page that sent the browser todiff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.tomlindex a0561a2f2f..075b0e4b9a 100644--- a/services/authentication_service/Cargo.toml+++ b/services/authentication_service/Cargo.toml@@ -136,6 +136,7 @@ maud = { version = "0.27.0" }miniserde = "0.1.45"microsoft_oauth_grant_db_utils = { path = "../../crates/microsoft_oauth_grant_db_utils" }mobile_welcome_email_db_client = { path = "../../crates/mobile_welcome_email_db_client" }+models_email = { path = "../../crates/models_email" }mockall = { workspace = true }model = { path = "../../crates/model" }model-entity = { path = "../../crates/model-entity" }diff --git a/services/authentication_service/src/api/link/gmail.rs b/services/authentication_service/src/api/link/gmail.rsindex d2024469ec..1431649e6a 100644--- a/services/authentication_service/src/api/link/gmail.rs+++ b/services/authentication_service/src/api/link/gmail.rs@@ -27,7 +27,19 @@ mod test;const GOOGLE_AUTHORIZATION_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";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";+/// The scope that makes a Google account a mailbox Macro can read and send+/// from. A consent that leaves it out cannot provision an inbox, so the+/// callback refuses it (`api::oauth2::google`).+pub(crate) const GMAIL_MAILBOX_SCOPE: &str = "https://www.googleapis.com/auth/gmail.modify";+const GMAIL_SCOPES: [&str; 7] = [+ "openid",+ "profile",+ "email",+ GMAIL_MAILBOX_SCOPE,+ "https://www.googleapis.com/auth/contacts.readonly",+ "https://www.googleapis.com/auth/contacts.other.readonly",+ "https://www.googleapis.com/auth/gmail.settings.basic",+];/// The identity scopes every consent needs: the callback resolves the account/// that consented from the `sub` and `email` claims on Google's id_token, and/// Google only mints one when `openid` is requested.@@ -221,14 +233,15 @@ pub async fn init_gmail_link_handler(/// consent, which is what it would have gotten before calendar existed.fn gmail_authorization_scopes(calendar_scope_enabled: bool, scopes: ConsentScopes) -> String {let calendar = google_calendar_scope_parameter();+ let mailbox = GMAIL_SCOPES.join(" ");match scopes {ConsentScopes::Calendar if calendar_scope_enabled => {format!("{IDENTITY_SCOPES} {calendar}")}ConsentScopes::GmailAndCalendar if calendar_scope_enabled => {- format!("{GMAIL_SCOPES} {calendar}")+ format!("{mailbox} {calendar}")}- _ => GMAIL_SCOPES.to_string(),+ _ => mailbox,}}diff --git a/services/authentication_service/src/api/link/gmail/test.rs b/services/authentication_service/src/api/link/gmail/test.rsindex 6a5fb24a60..87dc80534a 100644--- a/services/authentication_service/src/api/link/gmail/test.rs+++ b/services/authentication_service/src/api/link/gmail/test.rs@@ -12,7 +12,7 @@ fn has_calendar(scopes: &str) -> bool {fn has_mailbox(scopes: &str) -> bool {GMAIL_SCOPES- .split_ascii_whitespace()+ .iter().all(|scope| contains_scope(scopes, scope))}diff --git a/services/authentication_service/src/api/oauth2/google.rs b/services/authentication_service/src/api/oauth2/google.rsindex f2564c30b8..2f2069b80b 100644--- a/services/authentication_service/src/api/oauth2/google.rs+++ b/services/authentication_service/src/api/oauth2/google.rs@@ -6,33 +6,97 @@ use axum::{Json,response::{IntoResponse, Response},};+use calendar_events::domain::models::GoogleScopeSet;use model::response::ErrorResponse;use reqwest::StatusCode;use tower_cookies::Cookies;+use uuid::Uuid;-use crate::api::{- context::ApiContext,- oauth2::{- OAuthState,- account_link::{- build_callback_redirect, cleanup_pending_link, replace_identity_provider_grant,+use crate::{+ account_link_state::LinkProvider,+ api::{+ context::ApiContext,+ link::gmail::GMAIL_MAILBOX_SCOPE,+ oauth2::{+ OAuthState,+ account_link::{+ build_callback_redirect, build_return_redirect, cleanup_pending_link,+ replace_identity_provider_grant,+ },+ format_redirect_uri,+ login::{self},+ provider_query_value,},- format_redirect_uri,- login::{self},},};use fusionauth::error::FusionAuthClientError;+use fusionauth::google::oauth::GoogleExchangeTokenResponse;use fusionauth::identity_provider::{IdentityProviderLink, LinkUserRequest};+use models_email::service::link::UserProvider;#[cfg(test)]mod test;+/// The `email_link_error` query value the app reads when Google's consent+/// left out the mailbox permissions.+const GMAIL_NOT_GRANTED_ERROR: &str = "gmail_not_granted";++/// How a Google account-link callback ended.+#[derive(Debug, PartialEq, Eq)]+enum GoogleLinkOutcome {+ /// The grant is attached to the account's FusionAuth identity and recorded+ /// on the pending link for `/email/init` to apply.+ Linked,+ /// The consent asked for the mailbox but Google's grant lacks it, so the+ /// account cannot become an inbox. Nothing was attached, and the grant was+ /// revoked at Google unless an inbox already works on it.+ MailboxNotGranted,+}++/// What to do with the grant behind a refused consent.+#[derive(Debug, PartialEq, Eq)]+enum PartialGrantDisposition {+ /// Revoke it at Google, so the next consent screen lists every scope again.+ Revoke,+ /// Leave it alone: an inbox already works on it.+ Keep,+}++/// Google's revocation endpoint revokes the account's whole grant to Macro,+/// not only the token it is handed. An inbox that still works on that+/// account's grant would lose its mail and calendar sync, so its grant is kept+/// and only the refusal stands. An inbox whose grant already stopped yielding+/// tokens has nothing to lose, and revoking lets the retry start from a clean+/// consent screen.+fn partial_grant_disposition(existing_inbox_needs_reauth: Option<bool>) -> PartialGrantDisposition {+ match existing_inbox_needs_reauth {+ Some(false) => PartialGrantDisposition::Keep,+ Some(true) | None => PartialGrantDisposition::Revoke,+ }+}++/// Whether a consent that asked for the mailbox came back without it.+///+/// Google's granular consent lets the user leave any box unchecked. A+/// calendar upgrade (`ConsentScopes::Calendar`) never asks for the mailbox, so+/// its grant is not judged here.+fn mailbox_grant_missing(requested: &[String], granted: &[String]) -> bool {+ requested.iter().any(|scope| scope == GMAIL_MAILBOX_SCOPE)+ && !granted.iter().any(|scope| scope == GMAIL_MAILBOX_SCOPE)+}++#[tracing::instrument(+ name = "email.link.google.complete",+ skip_all,+ fields(link_id = %link_id, outcome = tracing::field::Empty),+ err(Debug)+)]async fn link_user(ctx: &ApiContext,identity_provider_id: &str,code: &str,- link_id: &uuid::Uuid,-) -> Result<(), (StatusCode, String)> {+ link_id: &Uuid,+) -> Result<GoogleLinkOutcome, (StatusCode, String)> {let in_progress =macro_db_client::in_progress_user_link::get_in_progress_user_link(&ctx.db, link_id).await@@ -75,6 +139,48 @@ async fn link_user()})?;+ // Google's actual grant may be a subset of what was requested. Without the+ // mailbox scope `/email/init` cannot provision the inbox, so the grant is+ // refused here, before it is attached to anyone's identity. Consent+ // requests carry `include_granted_scopes=true`, so a partial grant left+ // behind would ride into every later consent and Google would stop+ // listing its scopes, leaving the user no way to add the mailbox on a+ // retry; it is revoked unless an inbox already works on the account's+ // grant (see `partial_grant_disposition`).+ let requested_scopes = in_progress.requested_google_scopes;+ let granted_scopes = resolved_granted_scopes(&token_response.scope, requested_scopes.clone());+ if mailbox_grant_missing(&requested_scopes, &granted_scopes) {+ let calendar_granted =+ GoogleScopeSet::from_scopes(granted_scopes.iter().cloned()).has_calendar_capability();+ // A failed lookup keeps the grant: refusing is still right, and a+ // revocation that might hit a working inbox is not worth the risk.+ let disposition = match email_db_client::links::get::fetch_link_by_email(+ &ctx.db,+ &user_info_email,+ UserProvider::Gmail,+ )+ .await+ {+ Ok(existing_inbox) => {+ partial_grant_disposition(existing_inbox.map(|inbox| inbox.needs_reauth))+ }+ Err(error) => {+ tracing::warn!(error = ?error, "unable to look up the inbox of a refused Google grant; keeping the grant");+ PartialGrantDisposition::Keep+ }+ };+ tracing::info!(+ calendar_granted,+ revoke = disposition == PartialGrantDisposition::Revoke,+ "Google consent left out the mailbox scope; refusing the link"+ );+ if disposition == PartialGrantDisposition::Revoke {+ revoke_partial_grant(ctx, &token_response).await;+ }+ tracing::Span::current().record("outcome", GMAIL_NOT_GRANTED_ERROR);+ return Ok(GoogleLinkOutcome::MailboxNotGranted);+ }+// The IdP link doubles as the linked email's LOGIN identity: a Google identity binds to// exactly one FusionAuth user, and sign-in resolves through that link. When the linked// email belongs to an existing macro user, the link must therefore live on THAT user's FA@@ -137,8 +243,6 @@ async fn link_user(// Stash the linked identity and Google's actual grant (which may be a// subset of what was requested). /email/init applies these capabilities// atomically to the durable link and schedules any newly unlocked work.- let granted_scopes =- resolved_granted_scopes(&token_response.scope, in_progress.requested_google_scopes);macro_db_client::in_progress_user_link::set_linked_google_grant(&ctx.db,link_id,@@ -153,14 +257,61 @@ async fn link_user()})?;- Ok(())+ tracing::Span::current().record("outcome", "linked");+ Ok(GoogleLinkOutcome::Linked)+}++/// Best effort: a partial grant that stays behind only hides its scopes on the+/// next consent screen; the refusal itself does not depend on the revocation.+async fn revoke_partial_grant(ctx: &ApiContext, token_response: &GoogleExchangeTokenResponse) {+ let token = if token_response.refresh_token.is_empty() {+ &token_response.access_token+ } else {+ &token_response.refresh_token+ };+ if token.is_empty() {+ tracing::warn!("Google returned no token to revoke the partial grant with");+ return;+ }+ ctx.auth_client+ .revoke_google_grant(token)+ .await+ .inspect_err(|error| {+ tracing::warn!(error = ?error, "failed to revoke the partial Google grant");+ })+ .ok();}fn resolved_granted_scopes(returned: &str, requested: Vec<String>) -> Vec<String> {if returned.trim().is_empty() {requested} else {- calendar_events::domain::models::GoogleScopeSet::parse(returned).into_vec()+ GoogleScopeSet::parse(returned).into_vec()+ }+}++/// Sends a refused consent back to the page that started it, which explains+/// the outcome and offers a retry. A link flow without a return URL gets the+/// explanation as the response body instead.+fn mailbox_not_granted_response(original_url: Option<&str>, link_id: &Uuid) -> Response {+ match original_url {+ Some(original_url) => build_return_redirect(+ original_url,+ &[+ ("link_id", &link_id.to_string()),+ ("email_link_error", GMAIL_NOT_GRANTED_ERROR),+ ("provider", provider_query_value(LinkProvider::Google)),+ ],+ )+ .unwrap_or_else(IntoResponse::into_response),+ None => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "Gmail access was not granted; allow the Gmail permissions and try again"+ .into(),+ }),+ )+ .into_response(),}}@@ -179,7 +330,7 @@ pub(in crate::api::oauth2) async fn handler(cleanup_pending_link(ctx, link_id).await;}- link_result.map_err(|(status_code, error)| {+ let outcome = link_result.map_err(|(status_code, error)| {tracing::error!(error=?error, "unable to link user");(status_code,@@ -190,6 +341,14 @@ pub(in crate::api::oauth2) async fn handler(.into_response()})?;+ if outcome == GoogleLinkOutcome::MailboxNotGranted {+ cleanup_pending_link(ctx, link_id).await;+ return Ok(mailbox_not_granted_response(+ state.original_url.as_deref(),+ link_id,+ ));+ }+if let Some(original_url) = &state.original_url {return build_callback_redirect(original_url, link_id).map_err(IntoResponse::into_response);diff --git a/services/authentication_service/src/api/oauth2/google/test.rs b/services/authentication_service/src/api/oauth2/google/test.rsindex d7e9feb795..aca19e3f3c 100644--- a/services/authentication_service/src/api/oauth2/google/test.rs+++ b/services/authentication_service/src/api/oauth2/google/test.rs@@ -1,11 +1,19 @@-use super::resolved_granted_scopes;+use axum::http::header::LOCATION;+use reqwest::StatusCode;+use url::Url;+use uuid::Uuid;++use super::{+ PartialGrantDisposition, mailbox_grant_missing, mailbox_not_granted_response,+ partial_grant_disposition, resolved_granted_scopes,+};++const GMAIL: &str = "https://www.googleapis.com/auth/gmail.modify";+const CALENDAR: &str = "https://www.googleapis.com/auth/calendar.events";#[test]fn uses_requested_scopes_when_google_omits_an_unchanged_scope_field() {- let requested = vec![- "https://www.googleapis.com/auth/gmail.modify".to_string(),- "https://www.googleapis.com/auth/calendar.events".to_string(),- ];+ let requested = vec![GMAIL.to_string(), CALENDAR.to_string()];assert_eq!(resolved_granted_scopes("", requested.clone()), requested);}@@ -19,3 +27,76 @@ fn uses_google_scope_field_when_the_grant_differs_from_the_request() {vec!["calendar".to_string(), "gmail".to_string()]);}++#[test]+fn a_consent_that_asked_for_the_mailbox_must_grant_it() {+ let requested = vec![GMAIL.to_string(), CALENDAR.to_string()];++ assert!(mailbox_grant_missing(&requested, &[CALENDAR.to_string()]));+ assert!(mailbox_grant_missing(&requested, &[]));+ assert!(!mailbox_grant_missing(+ &requested,+ &[CALENDAR.to_string(), GMAIL.to_string()]+ ));+ assert!(+ !mailbox_grant_missing(&[CALENDAR.to_string()], &[CALENDAR.to_string()]),+ "a calendar upgrade never asks for the mailbox"+ );+}++#[test]+fn a_refused_consent_returns_to_the_app_with_the_error() {+ let link_id = Uuid::parse_str("0192b8a0-6a2e-7c3e-9b1f-4d5e6f708192").unwrap();++ let response = mailbox_not_granted_response(+ Some("https://macro.com/app/inbox-link-callback?view=all&email_link_error=cancelled"),+ &link_id,+ );++ assert_eq!(response.status(), StatusCode::SEE_OTHER);+ let location = response.headers()[LOCATION].to_str().unwrap().to_owned();+ let query: Vec<(String, String)> = Url::parse(&location)+ .unwrap()+ .query_pairs()+ .into_owned()+ .collect();+ assert_eq!(+ query,+ vec![+ ("view".into(), "all".into()),+ ("link_id".into(), link_id.to_string()),+ ("email_link_error".into(), "gmail_not_granted".into()),+ ("provider".into(), "gmail".into()),+ ]+ );+}++#[test]+fn a_refused_consent_without_a_return_url_keeps_the_error_body() {+ let response = mailbox_not_granted_response(None, &Uuid::now_v7());++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+}++#[test]+fn a_refused_grant_is_revoked_when_no_inbox_works_on_it() {+ assert_eq!(+ partial_grant_disposition(None),+ PartialGrantDisposition::Revoke,+ "an account with no inbox loses nothing"+ );+ assert_eq!(+ partial_grant_disposition(Some(true)),+ PartialGrantDisposition::Revoke,+ "an inbox whose grant already stopped yielding tokens loses nothing"+ );+}++#[test]+fn a_refused_grant_keeps_a_working_inbox_grant() {+ assert_eq!(+ partial_grant_disposition(Some(false)),+ PartialGrantDisposition::Keep,+ "revoking would take the whole grant, and with it the inbox's mail and calendar sync"+ );+}diff --git a/services/email_service/src/api/email/init.rs b/services/email_service/src/api/email/init.rsindex eff3d7ae5a..f002c6e999 100644--- a/services/email_service/src/api/email/init.rs+++ b/services/email_service/src/api/email/init.rs@@ -255,7 +255,10 @@ pub async fn handler(}// 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.+ // classified here, inside the span, where user fields still attach. An+ // already initialized inbox is the everyday case and stays at debug; any+ // other decline is rare and names its outcome so a failed connect can be+ // found by link id.let link_id = query.link_id;let owner = authorization.authorization@@ -269,8 +272,10 @@ pub async fn handler(let status = e.status_code();if status.is_server_error() {tracing::error!(error = ?e, "init failed");- } else {+ } else if matches!(e, InitError::AlreadyInitialized) {tracing::debug!(error = %e, "init declined");+ } else {+ tracing::info!(?link_id, status = status.as_u16(), outcome = %e, "init declined");}cleanup_in_progress_link_on_failure(&db, link_id, &owner, e).await;}