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): request Google Calendar scope only on explicit opt-in (#5602)
gbirman00ce2a40d00c
diff --git a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx b/apps/web/src/features/auth/CalendarPermissionPrompt.tsxindex 9b70980ca6..a7d391417d 100644--- a/apps/web/src/features/auth/CalendarPermissionPrompt.tsx+++ b/apps/web/src/features/auth/CalendarPermissionPrompt.tsx@@ -46,7 +46,7 @@ export function CalendarPermissionPrompt() {// Suppress re-prompting until the grant upgrades; on native the// page stays mounted while the OAuth flow runs.dismiss();- startAddInbox();+ startAddInbox({ includeCalendar: true });},},],diff --git a/apps/web/src/features/calendar/CalendarSetupStatus.tsx b/apps/web/src/features/calendar/CalendarSetupStatus.tsxindex 3c0df78a71..35e827f5e0 100644--- a/apps/web/src/features/calendar/CalendarSetupStatus.tsx+++ b/apps/web/src/features/calendar/CalendarSetupStatus.tsx@@ -79,7 +79,7 @@ export function CalendarSetupStatus() {variant="active"size="sm"label={setupMessage().action}- onClick={() => void startAddInbox()}+ onClick={() => void startAddInbox({ includeCalendar: true })}>{setupMessage().action}</Button>@@ -99,7 +99,7 @@ export function CalendarSetupStatus() {variant="active"size="sm"label={setupMessage().action}- onClick={() => void startAddInbox()}+ onClick={() => void startAddInbox({ includeCalendar: true })}>{setupMessage().action}</Button>diff --git a/apps/web/src/lib/core/email-link/index.ts b/apps/web/src/lib/core/email-link/index.tsindex 0ca45880e4..ed66af62f0 100644--- a/apps/web/src/lib/core/email-link/index.ts+++ b/apps/web/src/lib/core/email-link/index.ts@@ -215,6 +215,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.+ ** On native iOS the OAuth runs inline in an `ASWebAuthenticationSession` via* the Tauri auth plugin (the app never navigates away), and the link is* provisioned here directly with the `link_id` from the init response. A@@ -250,10 +254,11 @@ export function useAddInboxFlow() {);};- const startNativeFlow = async () => {- const result = await initGmailLink.mutateAsync(- 'macro://inbox-link-callback'- );+ const startNativeFlow = async (includeCalendar: boolean) => {+ const result = await initGmailLink.mutateAsync({+ originalUrl: 'macro://inbox-link-callback',+ includeCalendar,+ });if (result.isErr()) {if (isPaymentRequired(result.error)) {showPaywall(PaywallKey.MULTI_INBOX);@@ -292,14 +297,18 @@ export function useAddInboxFlow() {await completeNativeLink(result.value.link_id, false);};- return async () => {+ return async (options?: { includeCalendar?: boolean }) => {+ const includeCalendar = options?.includeCalendar ?? false;if (getNativeMobilePlatform() === 'ios') {- await startNativeFlow();+ await startNativeFlow(includeCalendar);return;}const callbackUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}inbox-link-callback`;- const result = await initGmailLink.mutateAsync(callbackUrl);+ const result = await initGmailLink.mutateAsync({+ originalUrl: callbackUrl,+ includeCalendar,+ });if (result.isOk()) {window.location.href = result.value.authorization_url;} else if (isPaymentRequired(result.error)) {diff --git a/apps/web/src/lib/queries/auth/gmail-link.ts b/apps/web/src/lib/queries/auth/gmail-link.tsindex 14d6ead65c..08187a911d 100644--- a/apps/web/src/lib/queries/auth/gmail-link.ts+++ b/apps/web/src/lib/queries/auth/gmail-link.ts@@ -4,12 +4,19 @@ 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.+ * `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.*/export function useInitGmailLink() {return useMutation(() => ({- mutationFn: async (originalUrl: string) => {- return authServiceClient.initGmailLink(originalUrl);+ mutationFn: async (params: {+ originalUrl: string;+ includeCalendar?: boolean;+ }) => {+ return authServiceClient.initGmailLink(params.originalUrl, {+ includeCalendar: params.includeCalendar,+ });},}));}diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex 14871b261c..f8c02aab73 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -554,10 +554,25 @@ export const authServiceClient = {* Returns the OAuth authorization URL to redirect the browser to.* 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.*/- async initGmailLink(originalUrl?: string) {- const url = originalUrl- ? `${authHost}/link/gmail?original_url=${encodeURIComponent(originalUrl)}`+ async initGmailLink(+ originalUrl?: string,+ options?: { includeCalendar?: boolean }+ ) {+ const params = new URLSearchParams();+ if (originalUrl) {+ params.set('original_url', encodeURIComponent(originalUrl));+ }+ if (options?.includeCalendar) {+ params.set('include_calendar', 'true');+ }+ const query = params.toString();+ const url = query+ ? `${authHost}/link/gmail?${query}`: `${authHost}/link/gmail`;return (await fetchWithAuth<diff --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 f2276675fd..f533bf3864 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@@ -10,4 +10,8 @@ export type InitGmailLinkParams = {* **OPTIONAL**. The original url to redirect to.*/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.+ */+ include_calendar?: boolean;};diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 7e0f962549..7bb832ad8a 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -624,6 +624,15 @@"schema": {"type": "string"}+ },+ {+ "name": "include_calendar",+ "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.",+ "required": false,+ "schema": {+ "type": "boolean"+ }}],"responses": {diff --git a/services/authentication_service/src/api/link/gmail.rs b/services/authentication_service/src/api/link/gmail.rsindex 4ff9b54cd5..c605d304b0 100644--- a/services/authentication_service/src/api/link/gmail.rs+++ b/services/authentication_service/src/api/link/gmail.rs@@ -80,6 +80,8 @@ pub(crate) struct InitGmailLinkQueryParams {/// Once the frontend is update to NOT 2x urlencode this then this should be changed to/// `Option<Url>`original_url: Option<UrlEncoded<Url>>,+ #[serde(default)]+ include_calendar: bool,}/// Initiates a Gmail link for a user@@ -88,7 +90,8 @@ pub(crate) struct InitGmailLinkQueryParams {operation_id = "init_gmail_link",path = "/link/gmail",params(- ("original_url" = String, Query, description = "**OPTIONAL**. The original url to redirect to.")+ ("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.")),responses((status = 200, body=InitGmailLinkResponse),@@ -106,7 +109,10 @@ pub async fn init_gmail_link_handler(ip_context: ClientIp,db_permissions: DbPermissionsExtractor,) -> Result<Json<InitGmailLinkResponse>, InitGmailLinkError> {- let Query(InitGmailLinkQueryParams { original_url }) = query;+ let Query(InitGmailLinkQueryParams {+ original_url,+ include_calendar,+ }) = query;let authorization = &db_permissions.authorization;enforce_inbox_paywall(@@ -128,11 +134,8 @@ pub async fn init_gmail_link_handler(return Err(InitGmailLinkError::TooManyInProgressLinks);}- let authorization_scopes = if ctx.calendar_scope_enabled {- format!("{GMAIL_SCOPES} {}", google_calendar_scope_parameter())- } else {- GMAIL_SCOPES.to_string()- };+ let authorization_scopes =+ gmail_authorization_scopes(ctx.calendar_scope_enabled, include_calendar);let requested_google_scopes: Vec<String> = authorization_scopes.split_ascii_whitespace().map(ToOwned::to_owned)@@ -173,6 +176,17 @@ 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()+ }+}+fn google_authorization_url(client_id: &str,redirect_uri: &str,diff --git a/services/authentication_service/src/api/link/gmail/test.rs b/services/authentication_service/src/api/link/gmail/test.rsindex 67db87bba8..ea1dc2910c 100644--- a/services/authentication_service/src/api/link/gmail/test.rs+++ b/services/authentication_service/src/api/link/gmail/test.rs@@ -79,9 +79,41 @@ async fn professional_features_skip_existing_inbox_check() {assert!(result.is_ok());}+#[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"+ );+ }+ }+}+#[test]fn authorization_url_requests_incremental_calendar_access() {- let scopes = format!("{GMAIL_SCOPES} {}", google_calendar_scope_parameter());+ let scopes = gmail_authorization_scopes(true, true);let url = google_authorization_url("client-id","https://auth.example.com/oauth2/callback",