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): ask only for calendar access when upgrading a connected inbox (#5638)
gbirman9d135077da91
diff --git a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx b/apps/web/src/features/auth/CalendarPermissionPrompt.tsxindex a7d391417d..ae30f3a5a0 100644--- a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx+++ b/apps/web/src/features/auth/CalendarPermissionPrompt.tsx@@ -13,8 +13,9 @@ import { useEmailLinksQuery } from '@queries/email/link';* re-shows Google consent for the linked account and applies the upgraded* grant to the existing link, which kicks off the calendar backfill.*- * Inboxes that also need a full reconnect are skipped: the reconnect prompt- * covers them, and reconnecting records the calendar grant anyway.+ * Inboxes that also need a full reconnect are skipped so the two prompts don't+ * stack. Reconnecting restores the mailbox without calendar access, which+ * leaves `needs_calendar_permission` set and brings this prompt back.** Gated per form factor: `enable-calendar-prompt-web` on desktop/web and* `enable-calendar-prompt-mobile` on phones, where the toast layout can't@@ -46,7 +47,7 @@ export function CalendarPermissionPrompt() {// Suppress re-prompting until the grant upgrades; on native the// page stays mounted while the OAuth flow runs.dismiss();- startAddInbox({ includeCalendar: true });+ startAddInbox({ scopes: 'calendar' });},},],diff --git a/apps/web/src/features/calendar/CalendarSetupStatus.tsx b/apps/web/src/features/calendar/CalendarSetupStatus.tsxindex 35e827f5e0..08bd19e6b3 100644--- a/apps/web/src/features/calendar/CalendarSetupStatus.tsx+++ b/apps/web/src/features/calendar/CalendarSetupStatus.tsx@@ -68,6 +68,13 @@ export function CalendarSetupStatus() {() => SETUP_MESSAGES[setupState() ?? 'connect']);+ // Only the permission state has a working mailbox already; connecting and+ // reconnecting both need the mailbox scopes alongside calendar.+ const startSetup = () =>+ void startAddInbox({+ scopes: setupState() === 'permission' ? 'calendar' : 'gmail_and_calendar',+ });+return (<Show when={setupState() !== undefined}><Show@@ -79,7 +86,7 @@ export function CalendarSetupStatus() {variant="active"size="sm"label={setupMessage().action}- onClick={() => void startAddInbox({ includeCalendar: true })}+ onClick={startSetup}>{setupMessage().action}</Button>@@ -99,7 +106,7 @@ export function CalendarSetupStatus() {variant="active"size="sm"label={setupMessage().action}- onClick={() => void startAddInbox({ includeCalendar: true })}+ onClick={startSetup}>{setupMessage().action}</Button>diff --git a/apps/web/src/features/settings/Email.tsx b/apps/web/src/features/settings/Email.tsxindex 792611aa63..601d7b2cd5 100644--- a/apps/web/src/features/settings/Email.tsx+++ b/apps/web/src/features/settings/Email.tsx@@ -179,6 +179,9 @@ export function EmailCard() {resyncing={resyncingIds().has(primary().id)}onResync={() => handleResyncInbox(primary().id)}onReconnect={() => void startAddInbox()}+ onEnableCalendar={() =>+ void startAddInbox({ scopes: 'calendar' })+ }onRemove={() =>setRemoveTarget({id: primary().id,@@ -205,6 +208,9 @@ export function EmailCard() {resyncing={resyncingIds().has(link.id)}onResync={() => handleResyncInbox(link.id)}onReconnect={() => void startAddInbox()}+ onEnableCalendar={() =>+ void startAddInbox({ scopes: 'calendar' })+ }onRemove={() =>setRemoveTarget({id: link.id,@@ -384,6 +390,7 @@ function InboxRow(props: {resyncing: boolean;onResync: () => void;onReconnect: () => void;+ onEnableCalendar: () => void;onRemove: () => void;}) {const emailSignaturesFlag = useFeatureFlag(ENABLE_EMAIL_SIGNATURES_FLAG, {@@ -481,8 +488,9 @@ function InboxRow(props: {Reconnect</Button></Show>- {/* Reconnecting re-runs consent with the calendar scope, so a link- that already shows Reconnect doesn't need a second button. */}+ {/* A link that needs a full reconnect gets calendar access on the+ pass after it: Reconnect restores the mailbox, then this button+ appears to add the calendar scope. */}<Showwhen={calendarUiEnabled() &&@@ -494,7 +502,7 @@ function InboxRow(props: {variant="active"size="sm"depth={3}- onClick={props.onReconnect}+ onClick={props.onEnableCalendar}aria-label={`Enable calendar for ${props.link.email_address}`}>Enable calendardiff --git a/apps/web/src/lib/core/email-link/index.ts b/apps/web/src/lib/core/email-link/index.tsindex ed66af62f0..a7ea3af699 100644--- a/apps/web/src/lib/core/email-link/index.ts+++ b/apps/web/src/lib/core/email-link/index.ts@@ -6,6 +6,7 @@ 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 type { ConsentScopes } from '@service-auth/client';import {ALREADY_INITIALIZED_CODE,emailClient,@@ -215,9 +216,10 @@ const TOO_MANY_PENDING_LINKS_MESSAGE =* navigates the browser to the OAuth consent page. The callback returns to* `/inbox-link-callback`, which provisions the new link.*- * `includeCalendar` adds the Google Calendar scope to the consent request and- * must only be passed from calendar entry points — plain Gmail connects must- * not ask for calendar access.+ * `scopes` selects which permissions the consent screen asks for. Only calendar+ * entry points may request calendar access, and they pass `calendar` for an+ * inbox that is already connected so the user isn't shown mailbox permissions+ * they have already granted.** On native iOS the OAuth runs inline in an `ASWebAuthenticationSession` via* the Tauri auth plugin (the app never navigates away), and the link is@@ -254,10 +256,10 @@ export function useAddInboxFlow() {);};- const startNativeFlow = async (includeCalendar: boolean) => {+ const startNativeFlow = async (scopes: ConsentScopes) => {const result = await initGmailLink.mutateAsync({originalUrl: 'macro://inbox-link-callback',- includeCalendar,+ scopes,});if (result.isErr()) {if (isPaymentRequired(result.error)) {@@ -297,17 +299,17 @@ export function useAddInboxFlow() {await completeNativeLink(result.value.link_id, false);};- return async (options?: { includeCalendar?: boolean }) => {- const includeCalendar = options?.includeCalendar ?? false;+ return async (options?: { scopes?: ConsentScopes }) => {+ const scopes = options?.scopes ?? 'gmail';if (getNativeMobilePlatform() === 'ios') {- await startNativeFlow(includeCalendar);+ await startNativeFlow(scopes);return;}const callbackUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}inbox-link-callback`;const result = await initGmailLink.mutateAsync({originalUrl: callbackUrl,- includeCalendar,+ scopes,});if (result.isOk()) {window.location.href = result.value.authorization_url;diff --git a/apps/web/src/lib/queries/auth/gmail-link.ts b/apps/web/src/lib/queries/auth/gmail-link.tsindex 08187a911d..d2cc475503 100644--- a/apps/web/src/lib/queries/auth/gmail-link.ts+++ b/apps/web/src/lib/queries/auth/gmail-link.ts@@ -1,21 +1,21 @@-import { authServiceClient } from '@service-auth/client';+import { authServiceClient, type ConsentScopes } from '@service-auth/client';import { useMutation } from '@tanstack/solid-query';/*** Mutation that asks auth-service for the Google OAuth authorization URL for* adding a Gmail inbox to the already-authenticated user. Callers consume the- * `authorization_url` and navigate the browser to it. `includeCalendar` adds- * the Google Calendar scope to the consent request; only calendar entry- * points should pass it.+ * `authorization_url` and navigate the browser to it. `scopes` selects which+ * permissions the consent screen asks for; only calendar entry points may+ * request calendar access.*/export function useInitGmailLink() {return useMutation(() => ({mutationFn: async (params: {originalUrl: string;- includeCalendar?: boolean;+ scopes?: ConsentScopes;}) => {return authServiceClient.initGmailLink(params.originalUrl, {- includeCalendar: params.includeCalendar,+ scopes: params.scopes,});},}));diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex f8c02aab73..f7ab177dd8 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -55,6 +55,12 @@ import type { UserTokensResponse } from './generated/schemas/userTokensResponse'const authHost = SERVER_HOSTS['auth-service'];+/**+ * Which permissions a Google consent screen asks for. `calendar` covers an+ * inbox that is already connected, so the screen lists calendar access alone.+ */+export type ConsentScopes = 'gmail' | 'gmail_and_calendar' | 'calendar';+const authApiFetch = <T extends ObjectLike>(input: string,init?: SafeFetchInit@@ -555,20 +561,21 @@ export const authServiceClient = {* After Google consent, the user is redirected back to `originalUrl` with `?link_id=<uuid>`* appended; the frontend then calls `emailClient.init({ linkId })` to provision the inbox.*- * Pass `includeCalendar` only from calendar entry points: it adds the Google- * Calendar scope to the consent request, and plain Gmail connects must not- * ask for calendar access.+ * `scopes` selects which permissions the consent screen asks for. Only+ * calendar entry points may request calendar access, and an inbox that is+ * already connected should ask for `calendar` alone so the user isn't+ * re-consenting to mailbox access they have already granted.*/async initGmailLink(originalUrl?: string,- options?: { includeCalendar?: boolean }+ options?: { scopes?: ConsentScopes }) {const params = new URLSearchParams();if (originalUrl) {params.set('original_url', encodeURIComponent(originalUrl));}- if (options?.includeCalendar) {- params.set('include_calendar', 'true');+ if (options?.scopes) {+ params.set('scopes', options.scopes);}const query = params.toString();const url = querydiff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/initGmailLinkParams.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/initGmailLinkParams.tsindex f533bf3864..b05b32d11b 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/initGmailLinkParams.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/initGmailLinkParams.ts@@ -11,7 +11,7 @@ export type InitGmailLinkParams = {*/original_url: string;/**- * **OPTIONAL**. Also request the Google Calendar scope. Only honored when the deployment allows calendar scope requests; pass it from calendar entry points only, since the extra scope changes the Google consent screen.+ * **OPTIONAL**. Which capabilities to request consent for: `gmail` (default), `gmail_and_calendar`, or `calendar`. The calendar variants are only honored when the deployment allows calendar scope requests.*/- include_calendar?: boolean;+ scopes?: string;};diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex da2bdcb59d..146c67288f 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -626,12 +626,12 @@}},{- "name": "include_calendar",+ "name": "scopes","in": "query",- "description": "**OPTIONAL**. Also request the Google Calendar scope. Only honored when the deployment allows calendar scope requests; pass it from calendar entry points only, since the extra scope changes the Google consent screen.",+ "description": "**OPTIONAL**. Which capabilities to request consent for: `gmail` (default), `gmail_and_calendar`, or `calendar`. The calendar variants are only honored when the deployment allows calendar scope requests.","required": false,"schema": {- "type": "boolean"+ "type": "string"}}],diff --git a/services/authentication_service/src/api/link/gmail.rs b/services/authentication_service/src/api/link/gmail.rsindex c605d304b0..2d83645d7b 100644--- a/services/authentication_service/src/api/link/gmail.rs+++ b/services/authentication_service/src/api/link/gmail.rs@@ -27,8 +27,28 @@ 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 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.+const IDENTITY_SCOPES: &str = "openid email";const FREE_INBOX_LIMIT: i64 = 2;+/// Which capabilities a consent request covers. Calendar surfaces ask for+/// [`ConsentScopes::Calendar`] when the mailbox is already connected, so the+/// consent screen lists the calendar permissions alone; Google's incremental+/// authorization carries the mailbox grant forward untouched.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub(crate) enum ConsentScopes {+ /// Connecting or reconnecting a mailbox.+ #[default]+ Gmail,+ /// Connecting a first mailbox from a calendar surface.+ GmailAndCalendar,+ /// Adding calendar access to a mailbox that is already connected.+ Calendar,+}+#[derive(serde::Deserialize, serde::Serialize, Debug, utoipa::ToSchema)]pub struct InitGmailLinkResponse {/// The OAuth authorization URL to redirect the user to@@ -81,7 +101,7 @@ pub(crate) struct InitGmailLinkQueryParams {/// `Option<Url>`original_url: Option<UrlEncoded<Url>>,#[serde(default)]- include_calendar: bool,+ scopes: ConsentScopes,}/// Initiates a Gmail link for a user@@ -91,7 +111,7 @@ pub(crate) struct InitGmailLinkQueryParams {path = "/link/gmail",params(("original_url" = String, Query, description = "**OPTIONAL**. The original url to redirect to."),- ("include_calendar" = Option<bool>, Query, description = "**OPTIONAL**. Also request the Google Calendar scope. Only honored when the deployment allows calendar scope requests; pass it from calendar entry points only, since the extra scope changes the Google consent screen.")+ ("scopes" = Option<String>, Query, description = "**OPTIONAL**. Which capabilities to request consent for: `gmail` (default), `gmail_and_calendar`, or `calendar`. The calendar variants are only honored when the deployment allows calendar scope requests.")),responses((status = 200, body=InitGmailLinkResponse),@@ -111,7 +131,7 @@ pub async fn init_gmail_link_handler() -> Result<Json<InitGmailLinkResponse>, InitGmailLinkError> {let Query(InitGmailLinkQueryParams {original_url,- include_calendar,+ scopes,}) = query;let authorization = &db_permissions.authorization;@@ -134,8 +154,7 @@ pub async fn init_gmail_link_handler(return Err(InitGmailLinkError::TooManyInProgressLinks);}- let authorization_scopes =- gmail_authorization_scopes(ctx.calendar_scope_enabled, include_calendar);+ let authorization_scopes = gmail_authorization_scopes(ctx.calendar_scope_enabled, scopes);let requested_google_scopes: Vec<String> = authorization_scopes.split_ascii_whitespace().map(ToOwned::to_owned)@@ -176,14 +195,21 @@ pub async fn init_gmail_link_handler(}))}-/// The calendar scope must never ride along on plain Gmail connects: it is-/// requested only when the caller explicitly opts in, and never when the-/// deployment-level `CALENDAR_SCOPE_ENABLED` kill switch is off.-fn gmail_authorization_scopes(calendar_scope_enabled: bool, include_calendar: bool) -> String {- if calendar_scope_enabled && include_calendar {- format!("{GMAIL_SCOPES} {}", google_calendar_scope_parameter())- } else {- GMAIL_SCOPES.to_string()+/// The calendar scopes must never ride along on plain Gmail connects: they are+/// requested only when the caller explicitly asks, and never when the+/// deployment-level `CALENDAR_SCOPE_ENABLED` kill switch is off. A caller whose+/// calendar request is vetoed by the kill switch falls back to the mailbox+/// 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();+ match scopes {+ ConsentScopes::Calendar if calendar_scope_enabled => {+ format!("{IDENTITY_SCOPES} {calendar}")+ }+ ConsentScopes::GmailAndCalendar if calendar_scope_enabled => {+ format!("{GMAIL_SCOPES} {calendar}")+ }+ _ => GMAIL_SCOPES.to_string(),}}diff --git a/services/authentication_service/src/api/link/gmail/test.rs b/services/authentication_service/src/api/link/gmail/test.rsindex ea1dc2910c..1156888fab 100644--- a/services/authentication_service/src/api/link/gmail/test.rs+++ b/services/authentication_service/src/api/link/gmail/test.rs@@ -79,41 +79,81 @@ async fn professional_features_skip_existing_inbox_check() {assert!(result.is_ok());}+fn contains_scope(scopes: &str, scope: &str) -> bool {+ scopes.split_ascii_whitespace().any(|value| value == scope)+}++fn has_calendar(scopes: &str) -> bool {+ calendar_events::domain::models::GOOGLE_CALENDAR_SCOPES+ .iter()+ .all(|scope| contains_scope(scopes, scope))+}++fn has_mailbox(scopes: &str) -> bool {+ GMAIL_SCOPES+ .split_ascii_whitespace()+ .all(|scope| contains_scope(scopes, scope))+}+#[test]-fn calendar_scope_requires_both_kill_switch_and_explicit_opt_in() {- let has_calendar = |scopes: &str| {- calendar_events::domain::models::GOOGLE_CALENDAR_SCOPES- .iter()- .all(|calendar_scope| {- scopes- .split_ascii_whitespace()- .any(|scope| scope == *calendar_scope)- })- };-- assert!(has_calendar(&gmail_authorization_scopes(true, true)));- assert!(!has_calendar(&gmail_authorization_scopes(true, false)));- assert!(!has_calendar(&gmail_authorization_scopes(false, true)));- assert!(!has_calendar(&gmail_authorization_scopes(false, false)));-- for (calendar_scope_enabled, include_calendar) in- [(true, true), (true, false), (false, true), (false, false)]- {- let scopes = gmail_authorization_scopes(calendar_scope_enabled, include_calendar);- for gmail_scope in GMAIL_SCOPES.split_ascii_whitespace() {- assert!(- scopes- .split_ascii_whitespace()- .any(|scope| scope == gmail_scope),- "gmail scope {gmail_scope} must always be requested"- );- }+fn calendar_scopes_require_both_the_kill_switch_and_an_asking_caller() {+ assert!(has_calendar(&gmail_authorization_scopes(+ true,+ ConsentScopes::Calendar+ )));+ assert!(has_calendar(&gmail_authorization_scopes(+ true,+ ConsentScopes::GmailAndCalendar+ )));+ assert!(!has_calendar(&gmail_authorization_scopes(+ true,+ ConsentScopes::Gmail+ )));++ for asking in [ConsentScopes::Calendar, ConsentScopes::GmailAndCalendar] {+ assert!(+ !has_calendar(&gmail_authorization_scopes(false, asking)),+ "the kill switch must veto calendar for {asking:?}"+ );+ }+}++#[test]+fn a_calendar_upgrade_asks_for_calendar_alone() {+ let scopes = gmail_authorization_scopes(true, ConsentScopes::Calendar);++ assert!(+ !has_mailbox(&scopes),+ "an inbox that is already connected must not re-consent to mailbox access"+ );+ for identity_scope in IDENTITY_SCOPES.split_ascii_whitespace() {+ assert!(+ contains_scope(&scopes, identity_scope),+ "{identity_scope} is required for the callback to identify the account"+ );+ }+}++#[test]+fn every_other_consent_keeps_the_mailbox_scopes() {+ for (calendar_scope_enabled, asking) in [+ (true, ConsentScopes::Gmail),+ (true, ConsentScopes::GmailAndCalendar),+ (false, ConsentScopes::Gmail),+ (false, ConsentScopes::GmailAndCalendar),+ // A vetoed calendar upgrade falls back to the mailbox consent.+ (false, ConsentScopes::Calendar),+ ] {+ assert!(+ has_mailbox(&gmail_authorization_scopes(calendar_scope_enabled, asking)),+ "mailbox scopes must be requested for {asking:?} (calendar enabled: {calendar_scope_enabled})"+ );}}#[test]fn authorization_url_requests_incremental_calendar_access() {- let scopes = gmail_authorization_scopes(true, true);+ let scopes = gmail_authorization_scopes(true, ConsentScopes::Calendar);let url = google_authorization_url("client-id","https://auth.example.com/oauth2/callback",