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(auth): gate new Outlook connections per user with enable-outlook (#9343)

teoa2d04dd62662
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 31467df120..cc7f622d9d 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -2324,6 +2324,7 @@
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/favorites",
+ "crates/feature_flags",
"crates/fig_engine",
"crates/filter_ast",
"crates/folds/agent_fold",
diff --git a/Cargo.lock b/Cargo.lock
index 98b312ea3b..fe15fd2d10 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2169,6 +2169,7 @@ dependencies = [
"entity_access",
"entity_registry",
"favorites",
+ "feature_flags",
"foreign_entity",
"fusionauth",
"futures",
diff --git a/apps/web/src/features/inbox/AddInboxDialog.tsx b/apps/web/src/features/inbox/AddInboxDialog.tsx
index 2f97002659..0d60cbade9 100644
--- a/apps/web/src/features/inbox/AddInboxDialog.tsx
+++ b/apps/web/src/features/inbox/AddInboxDialog.tsx
@@ -33,16 +33,20 @@ export const isAddInboxDialogOpen = () => request() !== null;
export function AddInboxDialog() {
const addInbox = useAddInboxFlow();
const [pending, setPending] = createSignal(false);
- const [outlookAvailable, setOutlookAvailable] = createSignal(false);
+ // Undefined until the providers read settles. The dialog waits for it, so
+ // Outlook never flashes in for a user it isn't offered to, or pops in late.
+ const [outlookAvailable, setOutlookAvailable] = createSignal<boolean>();
createEffect(() => {
if (!isAddInboxDialogOpen()) return;
let current = true;
- setOutlookAvailable(false);
+ setOutlookAvailable(undefined);
void fetchEmailConnectionProviders()
.then((providers) => {
if (current) setOutlookAvailable(providers.outlook);
})
- .catch(() => {});
+ .catch(() => {
+ if (current) setOutlookAvailable(false);
+ });
onCleanup(() => {
current = false;
});
@@ -65,13 +69,13 @@ export function AddInboxDialog() {
return (
<EmailProviderDialog
- open={isAddInboxDialogOpen()}
+ open={isAddInboxDialogOpen() && outlookAvailable() !== undefined}
onOpenChange={(open) => {
if (!open) setRequest(null);
}}
onSelect={handleConfirm}
disabled={pending()}
- outlookAvailable={outlookAvailable()}
+ outlookAvailable={outlookAvailable() === true}
/>
);
}
diff --git a/apps/web/src/features/settings/Email.tsx b/apps/web/src/features/settings/Email.tsx
index 6d276e2806..50e3dc0444 100644
--- a/apps/web/src/features/settings/Email.tsx
+++ b/apps/web/src/features/settings/Email.tsx
@@ -27,7 +27,10 @@ import OutlookIcon from '@icon/outlook-color.svg';
import ArrowsClockwiseIcon from '@icon/system/regular/arrows-clockwise.svg?component-solid';
import CalendarSlashIcon from '@icon/system/regular/calendar-slash.svg?component-solid';
import { Telemetry } from '@macro-inc/observability';
-import { fetchEmailConnectionProviders } from '@queries/auth/outlook-link';
+import {
+ fetchEmailConnectionProviders,
+ useOutlookAvailable,
+} from '@queries/auth/outlook-link';
import {
type BackfillProgress,
estimateEtaSeconds,
@@ -84,7 +87,7 @@ export function useConnectInbox(): (provider?: EmailProvider) => void {
/**
* Connected inboxes, one row each, followed by rows to connect another Google
- * Workspace or Outlook account.
+ * Workspace account, or an Outlook account when the server offers Outlook.
*/
export function EmailCard(props: { class?: string } = {}) {
const email = useEmail();
@@ -126,6 +129,7 @@ export function EmailCard(props: { class?: string } = {}) {
});
const onConnectEmail = useConnectInbox();
+ const outlookOffered = useOutlookAvailable();
const hasInbox = () =>
Boolean(inboxes().primary) || inboxes().others.length > 0;
// Further inboxes are behind multi-inbox; the first is always offered.
@@ -278,19 +282,21 @@ export function EmailCard(props: { class?: string } = {}) {
/>
</IntegrationRow>
</SettingsSurface>
- <SettingsSurface>
- <IntegrationRow
- icon={<OutlookIcon />}
- title="Connect an Outlook account"
- description="Sync an Outlook.com or Microsoft 365 inbox into Macro Email."
- >
- <ConnectAction
- label="Connect"
- ariaLabel="Connect an Outlook account"
- onClick={() => onConnectEmail('OUTLOOK')}
- />
- </IntegrationRow>
- </SettingsSurface>
+ <Show when={outlookOffered()}>
+ <SettingsSurface>
+ <IntegrationRow
+ icon={<OutlookIcon />}
+ title="Connect an Outlook account"
+ description="Sync an Outlook.com or Microsoft 365 inbox into Macro Email."
+ >
+ <ConnectAction
+ label="Connect"
+ ariaLabel="Connect an Outlook account"
+ onClick={() => onConnectEmail('OUTLOOK')}
+ />
+ </IntegrationRow>
+ </SettingsSurface>
+ </Show>
</Show>
</div>
@@ -345,7 +351,10 @@ export function EmailCard(props: { class?: string } = {}) {
);
}
-/** Whether new Outlook connections are open; the provider chooser checks the same. */
+/**
+ * Whether new Outlook connections are open at click time, in case they closed
+ * after the row was shown; the provider chooser checks the same.
+ */
async function outlookAvailable(): Promise<boolean> {
try {
return (await fetchEmailConnectionProviders()).outlook;
diff --git a/apps/web/src/features/settings/EmailConnectRows.test.tsx b/apps/web/src/features/settings/EmailConnectRows.test.tsx
index 4e93dcc04a..f7e81bb4cd 100644
--- a/apps/web/src/features/settings/EmailConnectRows.test.tsx
+++ b/apps/web/src/features/settings/EmailConnectRows.test.tsx
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
}));
const [connected, setConnected] = createSignal(false);
const [multiInbox, setMultiInbox] = createSignal(false);
+const [outlookOffered, setOutlookOffered] = createSignal(true);
vi.mock('@core/email-link', () => ({
useEmailLinks: () => ({
@@ -22,6 +23,7 @@ vi.mock('@core/email-link', () => ({
}));
vi.mock('@queries/auth/outlook-link', () => ({
fetchEmailConnectionProviders: mocks.providers,
+ useOutlookAvailable: () => outlookOffered,
}));
vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: () => () => ({ enabled: multiInbox() }),
@@ -55,6 +57,7 @@ vi.mock('./SignatureSection', () => ({ clearSignatureState: vi.fn() }));
beforeEach(() => {
setConnected(false);
setMultiInbox(false);
+ setOutlookOffered(true);
mocks.providers.mockResolvedValue({ outlook: true });
});
afterEach(() => {
@@ -78,7 +81,7 @@ it('connects the chosen provider without asking again', async () => {
);
});
-it('stops before consent when new Outlook connections are closed', async () => {
+it('stops before consent when Outlook closed after the row was shown', async () => {
mocks.providers.mockResolvedValue({ outlook: false });
render(() => <EmailCard />);
fireEvent.click(
diff --git a/apps/web/src/features/settings/MobileSettings.tsx b/apps/web/src/features/settings/MobileSettings.tsx
index 557e125b8f..ede5832f23 100644
--- a/apps/web/src/features/settings/MobileSettings.tsx
+++ b/apps/web/src/features/settings/MobileSettings.tsx
@@ -6,6 +6,7 @@ import { enableEmailSignatures } from '@core/constant/featureFlags';
import { useSettingsTabs } from '@core/constant/settingsTabsConfig';
import { useEmail, useUserId } from '@core/context/user';
import { fireAndForget } from '@core/util/fireAndForget';
+import { useOutlookAvailable } from '@queries/auth/outlook-link';
import { isRealNamePart, useOwnUserName } from '@queries/auth/user-name-self';
import { Show, Suspense } from 'solid-js';
import { useMobileSettings } from './context/mobile-settings';
@@ -16,6 +17,8 @@ import { useTeamSettingsGroups } from './teamSettingsGroups';
export function MobileSettings() {
const settings = useMobileSettings();
const signatures = useFeatureFlag(enableEmailSignatures);
+ // Always mounted on phones; read the providers only once settings open.
+ const outlook = useOutlookAvailable(settings.open);
const { groups, searchGroups } = useSettingsTabs();
const navGroups = useTeamSettingsGroups(groups);
const userId = useUserId();
@@ -38,6 +41,7 @@ export function MobileSettings() {
groups={navGroups()}
searchGroups={searchGroups()}
emailSignatures={signatures().enabled}
+ outlook={outlook()}
name={displayName()}
email={email() ?? ''}
avatar={
diff --git a/apps/web/src/features/settings/MobileSettingsSheet.tsx b/apps/web/src/features/settings/MobileSettingsSheet.tsx
index 653bb25ebc..82a7f968ee 100644
--- a/apps/web/src/features/settings/MobileSettingsSheet.tsx
+++ b/apps/web/src/features/settings/MobileSettingsSheet.tsx
@@ -34,6 +34,8 @@ type MobileSettingsSheetProps = {
groups: SettingsTabGroup[];
searchGroups?: SettingsTabGroup[];
emailSignatures?: boolean;
+ /** Whether search lists the Outlook connection; see `searchSettings`. */
+ outlook?: boolean;
name: string;
email: string;
avatar: JSX.Element;
@@ -50,6 +52,7 @@ export function MobileSettingsSheet(props: MobileSettingsSheetProps) {
const results = createMemo(() =>
searchSettings(props.searchGroups ?? props.groups, query(), {
emailSignatures: props.emailSignatures,
+ outlook: props.outlook,
})
);
let mainScrollTop = 0;
diff --git a/apps/web/src/features/settings/Settings.tsx b/apps/web/src/features/settings/Settings.tsx
index dddea28d2e..2d484a4dea 100644
--- a/apps/web/src/features/settings/Settings.tsx
+++ b/apps/web/src/features/settings/Settings.tsx
@@ -24,6 +24,7 @@ import { isMobile } from '@core/mobile/isMobile';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { activeTabId, setActiveTabId } from '@core/signal/settingsTab';
import { fireAndForget } from '@core/util/fireAndForget';
+import { useOutlookAvailable } from '@queries/auth/outlook-link';
import {
createMemo,
createRenderEffect,
@@ -92,6 +93,7 @@ export function SettingsPanel(props: SettingsPanelProps) {
// from people without a team.
const navTabs = createMemo(() => navGroups().flatMap((group) => group.items));
const signatures = useFeatureFlag(enableEmailSignatures);
+ const outlook = useOutlookAvailable();
const activeNavigationTab = activeTabId;
@@ -101,6 +103,7 @@ export function SettingsPanel(props: SettingsPanelProps) {
const searchResults = createMemo(() =>
searchSettings(searchGroups(), searchQuery(), {
emailSignatures: signatures().enabled,
+ outlook: outlook(),
})
);
diff --git a/apps/web/src/features/settings/connections/integration-items.tsx b/apps/web/src/features/settings/connections/integration-items.tsx
index 644ed383b3..408cadcdf3 100644
--- a/apps/web/src/features/settings/connections/integration-items.tsx
+++ b/apps/web/src/features/settings/connections/integration-items.tsx
@@ -13,6 +13,7 @@ import ClaudeIcon from '@icon/claude-color.svg';
import GmailIcon from '@icon/gmail-color.svg';
import OutlookIcon from '@icon/outlook-color.svg';
import DesktopIcon from '@icon/system/regular/desktop.svg';
+import { useOutlookAvailable } from '@queries/auth/outlook-link';
import { useUserTeamsQuery } from '@queries/team/teams';
import type { Team as TeamSummary } from '@service-auth/generated/schemas/team';
import type { Link as EmailLink } from '@service-email/generated/schemas';
@@ -96,11 +97,18 @@ function emailItem(
};
}
-/** Gmail and Outlook, one row per provider; accounts are managed in Email settings. */
-export function useEmailItems(hosts: IntegrationItemHosts): IntegrationItem[] {
+/**
+ * Gmail and Outlook, one row per provider; accounts are managed in Email
+ * settings. Outlook shows when the server offers it to this user, or to manage
+ * Outlook inboxes already connected.
+ */
+export function useEmailItems(
+ hosts: IntegrationItemHosts
+): Accessor<IntegrationItem[]> {
const { query } = useEmailLinks();
const connectInbox = useConnectInbox();
const multiInbox = useFeatureFlag(enableMultiInbox);
+ const outlookOffered = useOutlookAvailable();
const links = () => (query.isSuccess ? query.data.links : []);
const linksFor = (provider: EmailLink['provider']) =>
links().filter((link) =>
@@ -113,7 +121,7 @@ export function useEmailItems(hosts: IntegrationItemHosts): IntegrationItem[] {
const actionsFor = (provider: EmailLink['provider']) => () => (
<>
- <Show when={canAdd()}>
+ <Show when={canAdd() && (provider !== 'OUTLOOK' || outlookOffered())}>
<ConnectAction
label={linksFor(provider).length > 0 ? 'Add account' : 'Connect'}
ariaLabel={
@@ -133,11 +141,21 @@ export function useEmailItems(hosts: IntegrationItemHosts): IntegrationItem[] {
</Show>
</>
);
- if (!ENABLE_EMAIL) return [];
- return [
- emailItem('GMAIL', () => linksFor('GMAIL'), actionsFor('GMAIL')),
- emailItem('OUTLOOK', () => linksFor('OUTLOOK'), actionsFor('OUTLOOK')),
- ];
+ if (!ENABLE_EMAIL) return () => [];
+ const gmail = emailItem(
+ 'GMAIL',
+ () => linksFor('GMAIL'),
+ actionsFor('GMAIL')
+ );
+ const outlook = emailItem(
+ 'OUTLOOK',
+ () => linksFor('OUTLOOK'),
+ actionsFor('OUTLOOK')
+ );
+ return () =>
+ outlookOffered() || linksFor('OUTLOOK').length > 0
+ ? [gmail, outlook]
+ : [gmail];
}
/**
diff --git a/apps/web/src/features/settings/connections/integrations-view.test.tsx b/apps/web/src/features/settings/connections/integrations-view.test.tsx
index 81f739b6b4..3808983aa0 100644
--- a/apps/web/src/features/settings/connections/integrations-view.test.tsx
+++ b/apps/web/src/features/settings/connections/integrations-view.test.tsx
@@ -89,7 +89,7 @@ vi.mock('./integration-items', async (importOriginal) => {
});
return {
...actual,
- useEmailItems: () => [],
+ useEmailItems: () => () => [],
useGithubItem: () => item('GitHub', () => null),
useGranolaItem: () => item('Granola', () => null),
useAgentProviderItem: (_model: unknown, provider: 'slack' | 'linear') =>
diff --git a/apps/web/src/features/settings/connections/integrations-view.tsx b/apps/web/src/features/settings/connections/integrations-view.tsx
index 7a847cf499..5135ec8f96 100644
--- a/apps/web/src/features/settings/connections/integrations-view.tsx
+++ b/apps/web/src/features/settings/connections/integrations-view.tsx
@@ -214,8 +214,8 @@ function IntegrationsOverview(
useAgentProviderItem(props.model, 'linear'),
useAgentProviderItem(props.model, 'notion'),
];
- const items = [
- ...useEmailItems(props),
+ const emailItems = useEmailItems(props);
+ const otherItems = [
useGithubItem(props.model),
...agentTools,
useGranolaItem(),
@@ -223,7 +223,7 @@ function IntegrationsOverview(
];
// Agent tool rows need connector records; without them their state is unknown.
const matching = () =>
- items.filter(
+ [...emailItems(), ...otherItems].filter(
(item) =>
(props.agentToolsAvailable || !agentTools.includes(item)) &&
matchesIntegration(item, query())
diff --git a/apps/web/src/features/settings/core/settings-search.ts b/apps/web/src/features/settings/core/settings-search.ts
index 400a81e0e0..a9b1184d92 100644
--- a/apps/web/src/features/settings/core/settings-search.ts
+++ b/apps/web/src/features/settings/core/settings-search.ts
@@ -384,7 +384,7 @@ function tokenScore(query: string, candidate: string): number {
export function searchSettings(
groups: readonly SettingsTabGroup[],
query: string,
- options: { emailSignatures?: boolean } = {}
+ options: { emailSignatures?: boolean; outlook?: boolean } = {}
): SettingsSearchResult[] {
const tokens = words(query);
if (!tokens.length) return [];
@@ -404,7 +404,8 @@ export function searchSettings(
(setting) =>
setting.tab === page.tab &&
(options.emailSignatures !== false ||
- setting.title !== 'Email signatures')
+ setting.title !== 'Email signatures') &&
+ (options.outlook !== false || setting.title !== 'Outlook')
).map((setting) => ({
...setting,
target: settingsTarget(setting.target),
diff --git a/apps/web/src/lib/core/email-link/ProviderDialog.tsx b/apps/web/src/lib/core/email-link/ProviderDialog.tsx
index d24e8964c1..3810093044 100644
--- a/apps/web/src/lib/core/email-link/ProviderDialog.tsx
+++ b/apps/web/src/lib/core/email-link/ProviderDialog.tsx
@@ -6,11 +6,14 @@ import {
openDialog,
Panel,
} from '@ui';
-import { type Owner, Show } from 'solid-js';
+import { type Owner, onCleanup, runWithOwner, Show } from 'solid-js';
export type EmailProvider = 'GMAIL' | 'OUTLOOK';
-/** Shared provider choice for onboarding, empty states and additional inboxes. */
+/**
+ * Shared provider choice for onboarding, empty states and additional inboxes.
+ * Outlook appears only when the server offers it to this user.
+ */
export function EmailProviderDialog(
props: ManagedDialogProps & {
onSelect: (provider: EmailProvider) => void;
@@ -33,7 +36,13 @@ export function EmailProviderDialog(
</Panel.Header>
<Panel.Body class="p-6 font-sans flex flex-col gap-3">
<Dialog.Description class="text-ink-muted text-sm/tight">
- Connect Gmail, Outlook.com, or an individual Microsoft 365 account.
+ <Show
+ when={props.outlookAvailable}
+ fallback="Connect a Gmail or Google Workspace account."
+ >
+ Connect Gmail, Outlook.com, or an individual Microsoft 365
+ account.
+ </Show>
</Dialog.Description>
<p class="text-ink-muted text-sm/tight">
Macro connects an account's email and calendar together, so keep the
@@ -46,17 +55,14 @@ export function EmailProviderDialog(
>
Gmail
</Button>
- <Button
- variant="secondary"
- disabled={props.disabled || !props.outlookAvailable}
- onClick={() => props.onSelect('OUTLOOK')}
- >
- Outlook / Microsoft 365
- </Button>
- <Show when={!props.outlookAvailable}>
- <p class="text-ink-muted text-sm">
- New Outlook connections are temporarily unavailable.
- </p>
+ <Show when={props.outlookAvailable}>
+ <Button
+ variant="secondary"
+ disabled={props.disabled}
+ onClick={() => props.onSelect('OUTLOOK')}
+ >
+ Outlook / Microsoft 365
+ </Button>
</Show>
<Button
variant="ghost"
@@ -71,21 +77,35 @@ export function EmailProviderDialog(
);
}
-/** Cancellation and owner disposal resolve without starting an OAuth attempt. */
+/**
+ * Cancellation and owner disposal resolve without starting an OAuth attempt.
+ * With Gmail the only provider on offer, there is nothing to choose.
+ */
export async function selectEmailProvider(
owner: Owner | null
): Promise<EmailProvider | undefined> {
+ // Registered before the read: a caller gone by the time it answers must not
+ // be sent to a consent screen.
+ let disposed = false;
+ if (owner)
+ runWithOwner(owner, () =>
+ onCleanup(() => {
+ disposed = true;
+ })
+ );
let outlookAvailable = false;
try {
outlookAvailable = (await fetchEmailConnectionProviders()).outlook;
} catch {
/* Gmail remains available when the availability read fails. */
}
+ if (disposed) return undefined;
+ if (!outlookAvailable) return 'GMAIL';
let selected: EmailProvider | undefined;
const handle = openDialog(
EmailProviderDialog,
{
- outlookAvailable,
+ outlookAvailable: true,
onSelect: (provider) => {
selected = provider;
handle.close();
diff --git a/apps/web/src/lib/queries/auth/outlook-link.ts b/apps/web/src/lib/queries/auth/outlook-link.ts
index 55030e5cfa..a5e553148e 100644
--- a/apps/web/src/lib/queries/auth/outlook-link.ts
+++ b/apps/web/src/lib/queries/auth/outlook-link.ts
@@ -1,8 +1,10 @@
import { throwOnErr } from '@core/util/result';
import { getWebOrigin } from '@core/util/webOrigin';
import { authServiceClient } from '@service-auth/client';
-import { useMutation } from '@tanstack/solid-query';
+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
+import { queryReadyGate } from '../gate';
import { authKeys } from './keys';
/** OAuth transport stays in the auth client, shared query orchestration here. */
@@ -23,9 +25,9 @@ export function useInitOutlookLink() {
*/
const adminConsentReturnUrl = () => `${getWebOrigin()}/app/inbox-link-callback`;
-/** Fetch on opening the chooser, without suspending unrelated application UI. */
-export function fetchEmailConnectionProviders() {
- return queryClient.fetchQuery({
+/** Per user: Outlook follows the server's `enable-outlook` flag. */
+const emailConnectionProvidersQuery = () =>
+ queryOptions({
queryKey: authKeys.emailConnectionProviders.queryKey,
queryFn: () =>
throwOnErr(() =>
@@ -33,4 +35,24 @@ export function fetchEmailConnectionProviders() {
),
staleTime: 0,
});
+
+/** Fetch on opening the chooser, without suspending unrelated application UI. */
+export function fetchEmailConnectionProviders() {
+ return queryClient.fetchQuery(emailConnectionProvidersQuery());
+}
+
+/**
+ * Whether to offer a new Outlook connection. False until the server says
+ * this user may start one, so Outlook never shows while loading or after a
+ * failed read. `enabled` defers the read for surfaces mounted before they open.
+ */
+export function useOutlookAvailable(
+ enabled: Accessor<boolean> = () => true
+): Accessor<boolean> {
+ const query = useQuery(() => ({
+ ...emailConnectionProvidersQuery(),
+ enabled: enabled(),
+ }));
+ // Gate the read: a pending query's data suspends the caller's boundary.
+ return () => queryReadyGate(query) && query.data.outlook;
}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index 8ca534aaf9..d59143c378 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -2578,14 +2578,21 @@ export type emailConnectionProvidersResponse400 = {
status: 400;
};
+export type emailConnectionProvidersResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
export type emailConnectionProvidersResponseSuccess =
emailConnectionProvidersResponse200 & {
headers: Headers;
};
-export type emailConnectionProvidersResponseError =
- emailConnectionProvidersResponse400 & {
- headers: Headers;
- };
+export type emailConnectionProvidersResponseError = (
+ | emailConnectionProvidersResponse400
+ | emailConnectionProvidersResponse401
+) & {
+ headers: Headers;
+};
export type emailConnectionProvidersResponse =
| emailConnectionProvidersResponseSuccess
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/emailConnectionProviders.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/emailConnectionProviders.ts
index 722e8e8d95..b89fef8bc5 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/emailConnectionProviders.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/emailConnectionProviders.ts
@@ -7,10 +7,12 @@
import type { EmailConnectionProvidersOutlookAdminConsentUrl } from './emailConnectionProvidersOutlookAdminConsentUrl';
/**
- * Actual deployment availability for the provider selector.
+ * What the provider selector offers the requesting user.
*/
export interface EmailConnectionProviders {
gmail: boolean;
+ /** Whether this user may start a new Outlook connection: the deployment
+switch and their `enable-outlook` flag. */
outlook: boolean;
/** Where a Microsoft 365 administrator approves Macro for their whole
directory. Present when Outlook is configured and the request named an
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index a846226a1c..0572188ec7 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -2185,6 +2185,16 @@
}
}
}
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
}
}
}
@@ -6519,14 +6529,15 @@
},
"EmailConnectionProviders": {
"type": "object",
- "description": "Actual deployment availability for the provider selector.",
+ "description": "What the provider selector offers the requesting user.",
"required": ["gmail", "outlook"],
"properties": {
"gmail": {
"type": "boolean"
},
"outlook": {
- "type": "boolean"
+ "type": "boolean",
+ "description": "Whether this user may start a new Outlook connection: the deployment\nswitch and their `enable-outlook` flag."
},
"outlook_admin_consent_url": {
"type": ["string", "null"],
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index a178bac23d..f707ad9d38 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -215,7 +215,7 @@
"ToolActor": "# Type Alias: ToolActor\n\n> **ToolActor** = `\"requester\"` \\| `\"owner\"`\n\nWhich authenticated participant's access a tool call requests.",
"ToolApprovalAnswerDto": "# Type Alias: ToolApprovalAnswerDto\n\n> **ToolApprovalAnswerDto** = `\"approve\"` \\| `\"approve_and_remember\"` \\| `\"deny\"` \\| `\"cancel\"`\n\nHow a person answers a held tool call.",
"ToolApprovalStatusDto": "# Type Alias: ToolApprovalStatusDto\n\n> **ToolApprovalStatusDto** = `\"pending\"` \\| `\"approved\"` \\| `\"denied\"` \\| `\"cancelled\"` \\| `\"expired\"`\n\nWhere a held tool call stands once answered.",
- "EmailConnectionProviders": "# Type Alias: EmailConnectionProviders\n\n> **EmailConnectionProviders** = \\{ `gmail`: `boolean`; `outlook`: `boolean`; `outlook_admin_consent_url?`: `string` \\| `null`; \\}\n\nActual deployment availability for the provider selector.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-gmail\"></a> `gmail` | `boolean` | - |\n| <a id=\"property-outlook\"></a> `outlook` | `boolean` | - |\n| <a id=\"property-outlook_admin_consent_url\"></a> `outlook_admin_consent_url?` | `string` \\| `null` | Where a Microsoft 365 administrator approves Macro for their whole directory. Present when Outlook is configured and the request named an `original_url` for the administrator's browser to return to. |",
+ "EmailConnectionProviders": "# Type Alias: EmailConnectionProviders\n\n> **EmailConnectionProviders** = \\{ `gmail`: `boolean`; `outlook`: `boolean`; `outlook_admin_consent_url?`: `string` \\| `null`; \\}\n\nWhat the provider selector offers the requesting user.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-gmail\"></a> `gmail` | `boolean` | - |\n| <a id=\"property-outlook\"></a> `outlook` | `boolean` | Whether this user may start a new Outlook connection: the deployment switch and their `enable-outlook` flag. |\n| <a id=\"property-outlook_admin_consent_url\"></a> `outlook_admin_consent_url?` | `string` \\| `null` | Where a Microsoft 365 administrator approves Macro for their whole directory. Present when Outlook is configured and the request named an `original_url` for the administrator's browser to return to. |",
"Language": "# Type Alias: Language\n\n> **Language** = `\"en\"` \\| `\"de\"` \\| `\"fr\"` \\| `\"es\"` \\| `\"it\"` \\| `\"nl\"` \\| `\"pt-PT\"` \\| `\"sv\"` \\| `\"da\"` \\| `\"nb\"` \\| `\"fi\"` \\| `\"pl\"` \\| `\"ru\"` \\| `\"ja\"` \\| `\"ko\"` \\| `\"zh-Hans\"` \\| `\"zh-Hant\"` \\| `\"hi\"` \\| `\"id\"` \\| `\"vi\"` \\| `\"th\"`\n\nA language the app's interface is available in, as a BCP 47 tag.",
"auth.LinkShare": "# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.",
"MacroApiTokenResponse": "# Type Alias: MacroApiTokenResponse\n\n> **MacroApiTokenResponse** = \\{ `macro_api_token`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-macro_api_token\"></a> `macro_api_token` | `string` | The newly created macro_api_token |",
diff --git a/crates/feature_flags/AGENTS.md b/crates/feature_flags/AGENTS.md
index f8f6858b4f..8a9e677426 100644
--- a/crates/feature_flags/AGENTS.md
+++ b/crates/feature_flags/AGENTS.md
@@ -22,8 +22,9 @@ for the authenticated Macro user, where one load returns a stable
## Boundaries
- Depends on: `macro_user_id`.
-- Used by: nothing yet (landed in #7985); a composition root wires an adapter
- in before any caller depends on this crate.
+- Used by: `agent_harness_service` (agent modes, routine templates) and
+ `authentication_service` (`enable-outlook`); each composition root wires the
+ PostHog adapter when `POSTHOG_API_KEY` is set.
## Recipes
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
index 5707ba83f4..cdf2765ec0 100644
--- a/docs/agent-guide/calendar.md
+++ b/docs/agent-guide/calendar.md
@@ -277,7 +277,8 @@ the flag request gets no answer, for example when a browser blocks it.
Calendar connections live in **Settings → Calendar** (`/app/settings/calendar`).
Connected calendars offers Connect account (pick Gmail or Outlook / Microsoft 365,
-then consent), Connect calendar for accounts missing calendar permission (consent
+then consent; Outlook is offered only to accounts with the `enable-outlook` flag,
+and without it Connect account goes straight to Google), Connect calendar for accounts missing calendar permission (consent
again for that account at its own provider with its address preselected, as
Settings → Email's Enable calendar does), and Disconnect with confirmation. When
the only linked account lacks calendar permission, the Calendar accounts row
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index 69f1e731b6..5de67f5e97 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -81,7 +81,9 @@ survive switching settings pages. On phones, the signature preview, replies/forw
toggle, and clear action are available; editing and import remain desktop-only.
Accounts list each inbox as its own row, followed by **Connect another Google
Workspace account** and **Connect an Outlook account**; Integrations shows the
-same rows. Its **Email settings**
+same rows. Outlook appears only once `/link/email/providers` offers it to the
+account (the `enable-outlook` flag); Integrations keeps an Outlook row with
+Manage alone for an account that already has an Outlook inbox. Its **Email settings**
gear opens the dedicated page, and Email links to Notifications and Calendar.
With a composer open, save a changed signature or reply-signature preference and
verify its preview updates. Once the account refresh completes, reopen a composer
diff --git a/docs/design/outlook-email-support.md b/docs/design/outlook-email-support.md
index efc5a5c239..d7b0b08408 100644
--- a/docs/design/outlook-email-support.md
+++ b/docs/design/outlook-email-support.md
@@ -81,6 +81,11 @@ environment after registering them in Doppler:
| Email | `OUTLOOK_CONNECTIONS_ENABLED`, `OUTLOOK_SYNC_ENABLED`, `OUTLOOK_WRITES_ENABLED` |
| Calendar | `OUTLOOK_SYNC_ENABLED`, `OUTLOOK_WRITES_ENABLED` |
+With the authentication switch on, a new connection also needs the user's
+PostHog flag `enable-outlook`, so connections roll out per user without a
+deploy. Reconnecting an existing inbox needs neither, and the email and calendar
+switches stay deployment-wide; they only act on inboxes that already exist.
+
The calendar service's existing global sync switch must also permit work. Existing
Microsoft application credentials, redirect URI, public webhook routing, and KMS
configuration must be available in the test environment. The available Doppler
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/EmailConnectionProviders.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/EmailConnectionProviders.md
index d999de5b6b..742102cd03 100644
--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/EmailConnectionProviders.md
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/EmailConnectionProviders.md
@@ -2,12 +2,12 @@
> **EmailConnectionProviders** = \{ `gmail`: `boolean`; `outlook`: `boolean`; `outlook_admin_consent_url?`: `string` \| `null`; \}
-Actual deployment availability for the provider selector.
+What the provider selector offers the requesting user.
## Properties
| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-gmail"></a> `gmail` | `boolean` | - |
-| <a id="property-outlook"></a> `outlook` | `boolean` | - |
+| <a id="property-outlook"></a> `outlook` | `boolean` | Whether this user may start a new Outlook connection: the deployment switch and their `enable-outlook` flag. |
| <a id="property-outlook_admin_consent_url"></a> `outlook_admin_consent_url?` | `string` \| `null` | Where a Microsoft 365 administrator approves Macro for their whole directory. Present when Outlook is configured and the request named an `original_url` for the administrator's browser to return to. |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/EmailConnectionProvidersErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/EmailConnectionProvidersErrors.md
index 01967521a6..f70eca4c53 100644
--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/EmailConnectionProvidersErrors.md
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/EmailConnectionProvidersErrors.md
@@ -1,9 +1,10 @@
# Type Alias: EmailConnectionProvidersErrors
-> **EmailConnectionProvidersErrors** = \{ `400`: [`ErrorResponse`](ErrorResponse.md); \}
+> **EmailConnectionProvidersErrors** = \{ `400`: [`ErrorResponse`](ErrorResponse.md); `401`: [`ErrorResponse`](ErrorResponse.md); \}
## Properties
| Property | Type |
| ------ | ------ |
| <a id="property-400"></a> `400` | [`ErrorResponse`](ErrorResponse.md) |
+| <a id="property-401"></a> `401` | [`ErrorResponse`](ErrorResponse.md) |
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 688e0cae75..d7a44db91d 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -446,10 +446,14 @@ export type CursorModelsResponse = {
export type DenyReason = 'allowance_exhausted' | 'free_allowance_exhausted' | 'overage_limit_reached' | 'overage_payment_failed';
/**
- * Actual deployment availability for the provider selector.
+ * What the provider selector offers the requesting user.
*/
export type EmailConnectionProviders = {
gmail: boolean;
+ /**
+ * Whether this user may start a new Outlook connection: the deployment
+ * switch and their `enable-outlook` flag.
+ */
outlook: boolean;
/**
* Where a Microsoft 365 administrator approves Macro for their whole
@@ -3032,6 +3036,7 @@ export type EmailConnectionProvidersData = {
export type EmailConnectionProvidersErrors = {
400: ErrorResponse;
+ 401: ErrorResponse;
};
export type EmailConnectionProvidersError = EmailConnectionProvidersErrors[keyof EmailConnectionProvidersErrors];
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index a846226a1c..0572188ec7 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -2185,6 +2185,16 @@
}
}
}
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
}
}
}
@@ -6519,14 +6529,15 @@
},
"EmailConnectionProviders": {
"type": "object",
- "description": "Actual deployment availability for the provider selector.",
+ "description": "What the provider selector offers the requesting user.",
"required": ["gmail", "outlook"],
"properties": {
"gmail": {
"type": "boolean"
},
"outlook": {
- "type": "boolean"
+ "type": "boolean",
+ "description": "Whether this user may start a new Outlook connection: the deployment\nswitch and their `enable-outlook` flag."
},
"outlook_admin_consent_url": {
"type": ["string", "null"],
diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.md
index 50122fc8d2..1499601f93 100644
--- a/services/authentication_service/AGENTS.md
+++ b/services/authentication_service/AGENTS.md
@@ -104,6 +104,15 @@ inputs cannot select an agent, and ordinary user credentials remain unattributed
when present; see `README.md` before changing signup behavior.
- Denial responses and policy errors must never disclose configured allowlist
addresses; never paste operational addresses into code, logs, or docs.
+- New Outlook connections need the deployment switch
+ `OUTLOOK_CONNECTIONS_ENABLED` and the user's PostHog flag `enable-outlook`
+ (`src/domain/microsoft.rs`), read with `crates/feature_flags` for the Macro
+ user id the web app identifies with. `/link/email/providers` answers
+ `outlook: false` and `/link/outlook` answers 404 for a new connection when
+ either is off; reconnecting an inbox reads neither. A failed flag load
+ closes new connections and logs one warning. Without `POSTHOG_API_KEY`
+ (local, tests) the switch alone decides. Each decision is the
+ `outlook.flag` span field (`on`, `off`, `error`, `unconfigured`).
- `/oauth2/{provider}/callback` verifies two signed `state` kinds
(`src/account_link_state.rs`): account links, which expire, and Microsoft
admin-consent returns, which do not. A consent screen that ends without a
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index c1e40fba6e..25900278db 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -81,6 +81,7 @@ entity_registry = { path = "../../crates/entity_registry/entity_registry", featu
] }
foreign_entity = { path = "../../crates/foreign_entity" }
favorites = { path = "../../crates/favorites", features = ["postgres"] }
+feature_flags = { path = "../../crates/feature_flags" }
fusionauth = { path = "../../crates/fusionauth" }
futures = { workspace = true }
generic_email_domains = { path = "../../crates/generic_email_domains" }
diff --git a/services/authentication_service/src/api/link/outlook.rs b/services/authentication_service/src/api/link/outlook.rs
index e828ea1851..ee5ea5cd28 100644
--- a/services/authentication_service/src/api/link/outlook.rs
+++ b/services/authentication_service/src/api/link/outlook.rs
@@ -1,4 +1,4 @@
-use crate::domain::microsoft::MicrosoftAuthError;
+use crate::domain::microsoft::{MicrosoftAuth, MicrosoftAuthError};
use axum::{
Json,
extract::{Query, State},
@@ -7,6 +7,7 @@ use axum::{
};
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
+use macro_user_id::user_id::MacroUserIdStr;
use model::response::ErrorResponse;
use serde_utils::urlencode::UrlEncoded;
use url::Url;
@@ -106,7 +107,7 @@ pub(crate) enum OutlookConsentScopes {
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.authorization.user.user_context.user_id, fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.authorization.user.user_context.user_id, fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id, outlook.flag = tracing::field::Empty), err)]
pub async fn init_outlook_link_handler(
State(ctx): State<ApiContext>,
Query(InitOutlookLinkQueryParams {
@@ -131,20 +132,45 @@ pub async fn init_outlook_link_handler(
let owner =
uuid::Uuid::parse_str(&authorization.authorization.user.user_context.fusion_user_id)
.map_err(|error| InitOutlookLinkError::InternalError(error.into()))?;
+ start_outlook_link(
+ service.as_ref(),
+ owner,
+ &authorization.authorization.user.macro_user_id,
+ format_redirect_uri("microsoft"),
+ original_url.map(String::from),
+ ctx.calendar_scope_enabled && matches!(scopes, OutlookConsentScopes::MailAndCalendar),
+ reconnect_link_id,
+ )
+ .await
+ .map(Json)
+}
+
+/// A new connection that the deployment switch or the user's flag refuses
+/// answers 404, the same as an unconfigured provider.
+async fn start_outlook_link(
+ service: &dyn MicrosoftAuth,
+ owner: uuid::Uuid,
+ user: &MacroUserIdStr<'_>,
+ redirect_uri: String,
+ original_url: Option<String>,
+ calendar_requested: bool,
+ reconnect_link_id: Option<uuid::Uuid>,
+) -> Result<InitOutlookLinkResponse, InitOutlookLinkError> {
let started = service
.start_link(
owner,
- format_redirect_uri("microsoft"),
- original_url.map(String::from),
- ctx.calendar_scope_enabled && matches!(scopes, OutlookConsentScopes::MailAndCalendar),
+ user,
+ redirect_uri,
+ original_url,
+ calendar_requested,
reconnect_link_id,
)
.await
.map_err(map_domain_error)?;
- Ok(Json(InitOutlookLinkResponse {
+ Ok(InitOutlookLinkResponse {
authorization_url: started.authorization_url,
link_id: started.id,
- }))
+ })
}
fn map_domain_error(error: MicrosoftAuthError) -> InitOutlookLinkError {
@@ -156,10 +182,12 @@ fn map_domain_error(error: MicrosoftAuthError) -> InitOutlookLinkError {
}
}
-/// Actual deployment availability for the provider selector.
+/// What the provider selector offers the requesting user.
#[derive(serde::Serialize, utoipa::ToSchema)]
pub struct EmailConnectionProviders {
pub gmail: bool,
+ /// Whether this user may start a new Outlook connection: the deployment
+ /// switch and their `enable-outlook` flag.
pub outlook: bool,
/// Where a Microsoft 365 administrator approves Macro for their whole
/// directory. Present when Outlook is configured and the request named an
@@ -183,13 +211,16 @@ pub(crate) struct EmailConnectionProvidersQueryParams {
responses(
(status = 200, body = EmailConnectionProviders),
(status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
)
)]
+#[tracing::instrument(skip_all, fields(fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id, outlook.flag = tracing::field::Empty), err)]
pub async fn email_connection_providers(
State(ctx): State<ApiContext>,
Query(EmailConnectionProvidersQueryParams { original_url }): Query<
EmailConnectionProvidersQueryParams,
>,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Json<EmailConnectionProviders>, InitOutlookLinkError> {
if original_url
.as_ref()
@@ -197,14 +228,32 @@ pub async fn email_connection_providers(
{
return Err(InitOutlookLinkError::InvalidReturnUrl);
}
+ Ok(Json(
+ connection_providers(
+ ctx.microsoft_auth.as_deref(),
+ &authorization.authorization.user.macro_user_id,
+ original_url,
+ ctx.calendar_scope_enabled,
+ )
+ .await,
+ ))
+}
+
+async fn connection_providers(
+ microsoft_auth: Option<&dyn MicrosoftAuth>,
+ user: &MacroUserIdStr<'_>,
+ original_url: Option<Url>,
+ calendar_scope_enabled: bool,
+) -> EmailConnectionProviders {
// The consent URL is an optional extra; a failure to sign it must not hide
- // which providers are available.
- let outlook_admin_consent_url = match (&ctx.microsoft_auth, original_url) {
+ // which providers are available. It stays independent of the flag: an
+ // inbox being reconnected can still need an administrator's approval.
+ let outlook_admin_consent_url = match (microsoft_auth, original_url) {
(Some(service), Some(original_url)) => service
.admin_consent_url(
&format_redirect_uri("microsoft"),
original_url.as_str(),
- ctx.calendar_scope_enabled,
+ calendar_scope_enabled,
)
.inspect_err(|error| {
tracing::warn!(error=?error, "unable to build Outlook admin-consent URL");
@@ -212,12 +261,13 @@ pub async fn email_connection_providers(
.ok(),
_ => None,
};
- Ok(Json(EmailConnectionProviders {
+ let outlook = match microsoft_auth {
+ Some(service) => service.new_connections_enabled(user).await,
+ None => false,
+ };
+ EmailConnectionProviders {
gmail: true,
- outlook: ctx
- .microsoft_auth
- .as_ref()
- .is_some_and(|service| service.new_connections_enabled()),
+ outlook,
outlook_admin_consent_url,
- }))
+ }
}
diff --git a/services/authentication_service/src/api/link/outlook/test.rs b/services/authentication_service/src/api/link/outlook/test.rs
index a15ea4322f..737471ae61 100644
--- a/services/authentication_service/src/api/link/outlook/test.rs
+++ b/services/authentication_service/src/api/link/outlook/test.rs
@@ -5,6 +5,12 @@ use utoipa::OpenApi;
use super::*;
use crate::api::swagger::ApiDoc;
+use crate::domain::microsoft::{
+ MicrosoftAuthService, MockMicrosoftGrantRepository, MockMicrosoftIdentityProvider,
+ OUTLOOK_FLAG, token::MockMicrosoftTokenCipher,
+};
+use feature_flags::{FlagSnapshot, FlagValue, outbound::fake::FakeFeatureFlags};
+use std::sync::Arc;
#[tokio::test]
async fn domain_errors_map_to_safe_statuses() {
@@ -59,3 +65,123 @@ fn outlook_link_openapi_includes_path_schema_and_error_responses() {
.is_some()
);
}
+
+#[tokio::test]
+async fn providers_offer_outlook_only_when_the_switch_and_the_users_flag_allow() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let cases = [
+ // (switch, flags configured, the user's flag load, outlook offered)
+ (
+ true,
+ true,
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(true),
+ )])),
+ true,
+ ),
+ (
+ true,
+ true,
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(false),
+ )])),
+ false,
+ ),
+ (true, true, Err("PostHog unreachable".to_owned()), false),
+ (true, false, Err("never loaded".to_owned()), true),
+ (
+ false,
+ true,
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(true),
+ )])),
+ false,
+ ),
+ ];
+ for (switch, configured, load, offered) in cases {
+ let mut flags = FakeFeatureFlags::default();
+ flags.set(user.clone(), load.clone());
+ let service = MicrosoftAuthService::new(
+ MockMicrosoftGrantRepository::new(),
+ MockMicrosoftIdentityProvider::new(),
+ Arc::new(MockMicrosoftTokenCipher::new()),
+ )
+ .with_connections_enabled(switch)
+ .with_feature_flags(configured.then_some(flags));
+ let providers = connection_providers(Some(&service), &user, None, false).await;
+ assert!(providers.gmail);
+ assert_eq!(
+ providers.outlook, offered,
+ "switch {switch}, configured {configured}, load {load:?}"
+ );
+ }
+ assert!(!connection_providers(None, &user, None, false).await.outlook);
+}
+
+#[tokio::test]
+async fn flagged_off_user_gets_404_for_a_new_link_but_can_reconnect() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let reconnect = uuid::Uuid::now_v7();
+ let mut repo = MockMicrosoftGrantRepository::new();
+ repo.expect_connection_facts().times(2).returning(|_, id| {
+ Ok(email::domain::inbox_entitlement::InboxConnectionFacts {
+ professional: true,
+ accessible_inboxes: 1,
+ reconnecting: id.is_some(),
+ })
+ });
+ repo.expect_begin_link().once().returning(|_| Ok(()));
+ let mut provider = MockMicrosoftIdentityProvider::new();
+ provider
+ .expect_identity_provider_id()
+ .once()
+ .returning(|| Ok("microsoft".into()));
+ provider
+ .expect_authorize()
+ .once()
+ .returning(|_| Ok("https://login.example.com/authorize".into()));
+ let mut flags = FakeFeatureFlags::default();
+ flags.set(
+ user.clone(),
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(false),
+ )])),
+ );
+ let service =
+ MicrosoftAuthService::new(repo, provider, Arc::new(MockMicrosoftTokenCipher::new()))
+ .with_feature_flags(Some(flags));
+
+ let refused = start_outlook_link(
+ &service,
+ uuid::Uuid::now_v7(),
+ &user,
+ "https://auth.example.com/oauth2/microsoft/callback".into(),
+ None,
+ false,
+ None,
+ )
+ .await
+ .unwrap_err()
+ .into_response();
+ assert_eq!(refused.status(), StatusCode::NOT_FOUND);
+
+ let reconnected = start_outlook_link(
+ &service,
+ uuid::Uuid::now_v7(),
+ &user,
+ "https://auth.example.com/oauth2/microsoft/callback".into(),
+ None,
+ false,
+ Some(reconnect),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ reconnected.authorization_url,
+ "https://login.example.com/authorize"
+ );
+}
diff --git a/services/authentication_service/src/domain/microsoft.rs b/services/authentication_service/src/domain/microsoft.rs
index 85b9070869..3c319b26e4 100644
--- a/services/authentication_service/src/domain/microsoft.rs
+++ b/services/authentication_service/src/domain/microsoft.rs
@@ -1,6 +1,8 @@
//! Owner-bound Microsoft linking and serialized refresh-token rotation.
use chrono::{DateTime, Duration, Utc};
+use feature_flags::FeatureFlags;
+use macro_user_id::user_id::MacroUserIdStr;
use std::{
collections::HashMap,
sync::{Arc, Mutex},
@@ -14,6 +16,28 @@ use token::{EncryptedMicrosoftToken, MicrosoftRefreshToken, MicrosoftTokenCipher
#[cfg(test)]
mod test;
+/// PostHog flag that admits a user to new Outlook connections when the
+/// deployment switch is on. Reconnecting an existing inbox never reads it.
+pub const OUTLOOK_FLAG: &str = "enable-outlook";
+
+/// The [`OUTLOOK_FLAG`] decision for one user, recorded as `outlook.flag`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
+#[strum(serialize_all = "snake_case")]
+pub enum OutlookFlag {
+ On,
+ Off,
+ /// The flags could not be loaded; new connections stay closed.
+ Error,
+ /// No flag provider is configured (local and tests); the switch decides.
+ Unconfigured,
+}
+
+impl OutlookFlag {
+ fn admits(self) -> bool {
+ matches!(self, Self::On | Self::Unconfigured)
+ }
+}
+
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum MicrosoftAuthError {
#[error("a professional subscription is required to link an additional inbox")]
@@ -213,7 +237,10 @@ pub trait MicrosoftIdentityProvider: Send + Sync {
#[async_trait::async_trait]
pub trait MicrosoftAuth: Send + Sync {
- fn new_connections_enabled(&self) -> bool;
+ /// Whether `user` may start a new Outlook connection: the deployment
+ /// switch, then their [`OUTLOOK_FLAG`]. Records `outlook.flag` on the
+ /// current span when the flag is read.
+ async fn new_connections_enabled(&self, user: &MacroUserIdStr<'_>) -> bool;
/// Where an administrator grants Macro's delegated permissions for their
/// whole directory, for users whose consent attempt needs admin approval.
fn admin_consent_url(
@@ -233,9 +260,12 @@ pub trait MicrosoftAuth: Send + Sync {
attempt: Uuid,
owner: Uuid,
) -> Result<CompletedMicrosoftGrant, MicrosoftAuthError>;
+ /// A new connection needs [`Self::new_connections_enabled`] for `user`;
+ /// reconnecting an inbox `owner` can already access does not.
async fn start_link(
&self,
owner: Uuid,
+ user: &MacroUserIdStr<'_>,
redirect_uri: String,
return_uri: Option<String>,
calendar_requested: bool,
@@ -279,19 +309,25 @@ struct CachedToken {
expires_at: DateTime<Utc>,
}
-pub struct MicrosoftAuthService<R, P> {
+pub struct MicrosoftAuthService<R, P, F> {
connections_enabled: bool,
+ /// `None` when no flag provider is configured; see [`OutlookFlag::Unconfigured`].
+ feature_flags: Option<F>,
repo: R,
provider: P,
cipher: Arc<dyn MicrosoftTokenCipher>,
cache: Mutex<HashMap<(Uuid, i64), CachedToken>>,
}
-impl<R, P> MicrosoftAuthService<R, P> {
+impl<R, P, F> MicrosoftAuthService<R, P, F> {
pub fn with_connections_enabled(mut self, enabled: bool) -> Self {
self.connections_enabled = enabled;
self
}
+ pub fn with_feature_flags(mut self, feature_flags: Option<F>) -> Self {
+ self.feature_flags = feature_flags;
+ self
+ }
pub fn new(repo: R, provider: P, cipher: Arc<dyn MicrosoftTokenCipher>) -> Self {
Self {
repo,
@@ -299,10 +335,37 @@ impl<R, P> MicrosoftAuthService<R, P> {
cipher,
cache: Mutex::new(HashMap::new()),
connections_enabled: true,
+ feature_flags: None,
}
}
}
+impl<R, P, F: FeatureFlags> MicrosoftAuthService<R, P, F> {
+ async fn outlook_flag(&self, user: &MacroUserIdStr<'_>) -> OutlookFlag {
+ let flag = match &self.feature_flags {
+ None => OutlookFlag::Unconfigured,
+ Some(feature_flags) => match feature_flags.load(user).await {
+ Ok(flags) if flags.is_enabled(OUTLOOK_FLAG) => OutlookFlag::On,
+ Ok(_) => OutlookFlag::Off,
+ Err(error) => {
+ tracing::warn!(
+ error = ?error,
+ flag = OUTLOOK_FLAG,
+ "feature flags unavailable; new Outlook connections stay closed"
+ );
+ OutlookFlag::Error
+ }
+ },
+ };
+ tracing::Span::current().record("outlook.flag", <&str>::from(flag));
+ flag
+ }
+
+ async fn admits_new_connection(&self, user: &MacroUserIdStr<'_>) -> bool {
+ self.connections_enabled && self.outlook_flag(user).await.admits()
+ }
+}
+
/// Persist one spelling for Graph capabilities so every consumer sees the same grant.
fn normalize_scopes(scopes: Vec<String>) -> Vec<String> {
const KNOWN: &[&str] = &[
@@ -346,11 +409,11 @@ fn has_required_scopes(scopes: &[String]) -> bool {
}
#[async_trait::async_trait]
-impl<R: MicrosoftGrantRepository, P: MicrosoftIdentityProvider> MicrosoftAuth
- for MicrosoftAuthService<R, P>
+impl<R: MicrosoftGrantRepository, P: MicrosoftIdentityProvider, F: FeatureFlags> MicrosoftAuth
+ for MicrosoftAuthService<R, P, F>
{
- fn new_connections_enabled(&self) -> bool {
- self.connections_enabled
+ async fn new_connections_enabled(&self, user: &MacroUserIdStr<'_>) -> bool {
+ self.admits_new_connection(user).await
}
fn admin_consent_url(
&self,
@@ -393,13 +456,14 @@ impl<R: MicrosoftGrantRepository, P: MicrosoftIdentityProvider> MicrosoftAuth
async fn start_link(
&self,
owner: Uuid,
+ user: &MacroUserIdStr<'_>,
redirect_uri: String,
return_uri: Option<String>,
calendar_requested: bool,
reconnect: Option<Uuid>,
) -> Result<LinkStart, MicrosoftAuthError> {
let facts = self.repo.connection_facts(owner, reconnect).await?;
- if !self.connections_enabled && !facts.reconnecting {
+ if !facts.reconnecting && !self.admits_new_connection(user).await {
return Err(MicrosoftAuthError::NotConfigured);
}
if !facts.permits_connection() {
@@ -508,7 +572,7 @@ impl<R: MicrosoftGrantRepository, P: MicrosoftIdentityProvider> MicrosoftAuth
}
}
-impl<R: MicrosoftGrantRepository, P: MicrosoftIdentityProvider> MicrosoftAuthService<R, P> {
+impl<R: MicrosoftGrantRepository, P: MicrosoftIdentityProvider, F> MicrosoftAuthService<R, P, F> {
async fn token_for_grant(
&self,
grant: StoredGrant,
diff --git a/services/authentication_service/src/domain/microsoft/test.rs b/services/authentication_service/src/domain/microsoft/test.rs
index 519047913c..c8b4300956 100644
--- a/services/authentication_service/src/domain/microsoft/test.rs
+++ b/services/authentication_service/src/domain/microsoft/test.rs
@@ -1,6 +1,13 @@
use super::*;
+use feature_flags::{FlagSnapshot, FlagValue, outbound::fake::FakeFeatureFlags};
use token::MockMicrosoftTokenCipher;
+type Service = MicrosoftAuthService<
+ MockMicrosoftGrantRepository,
+ MockMicrosoftIdentityProvider,
+ FakeFeatureFlags,
+>;
+
fn attempt() -> LinkAttempt {
LinkAttempt {
id: macro_uuid::generate_uuid_v7(),
@@ -47,7 +54,7 @@ async fn mismatched_provider_is_rejected_before_code_exchange() {
.once()
.return_once(move |_| Ok(pending));
repo.expect_abandon_link().once().returning(|_| Ok(()));
- let service = MicrosoftAuthService::new(
+ let service = Service::new(
repo,
MockMicrosoftIdentityProvider::new(),
Arc::new(MockMicrosoftTokenCipher::new()),
@@ -92,7 +99,7 @@ async fn verified_mailbox_never_changes_the_initiating_owner() {
actual == &owner.to_string() && email == "[email protected]"
})
.returning(|_, _, _| Ok(envelope()));
- let service = MicrosoftAuthService::new(repo, provider, Arc::new(cipher));
+ let service = Service::new(repo, provider, Arc::new(cipher));
assert_eq!(
service
.complete_link(id, "microsoft", "code")
@@ -122,8 +129,7 @@ async fn partial_consent_is_not_persisted_as_full_parity_grant() {
refresh_token: MicrosoftRefreshToken::new("refresh".into()),
})
});
- let service =
- MicrosoftAuthService::new(repo, provider, Arc::new(MockMicrosoftTokenCipher::new()));
+ let service = Service::new(repo, provider, Arc::new(MockMicrosoftTokenCipher::new()));
assert_eq!(
service.complete_link(id, "microsoft", "code").await,
Err(MicrosoftAuthError::MissingPermissions)
@@ -172,7 +178,7 @@ async fn lost_rotation_fence_never_returns_or_caches_the_access_token() {
.expect_decrypt()
.once()
.returning(|_, _, _| Ok(MicrosoftRefreshToken::new("refresh".into())));
- let service = MicrosoftAuthService::new(repo, provider, Arc::new(cipher));
+ let service = Service::new(repo, provider, Arc::new(cipher));
assert!(matches!(
service
.access_token(macro_uuid::generate_uuid_v7(), 1, 1, false)
@@ -189,7 +195,7 @@ async fn revoked_grants_are_checked_before_cache_hits() {
repo.expect_active_grant()
.once()
.returning(|_, _, _| Err(MicrosoftAuthError::ReauthorizationRequired));
- let service = MicrosoftAuthService::new(
+ let service = Service::new(
repo,
MockMicrosoftIdentityProvider::new(),
Arc::new(MockMicrosoftTokenCipher::new()),
@@ -249,7 +255,7 @@ async fn free_account_at_mixed_provider_limit_cannot_start_a_new_connection() {
reconnecting: false,
})
});
- let service = MicrosoftAuthService::new(
+ let service = Service::new(
repo,
MockMicrosoftIdentityProvider::new(),
Arc::new(MockMicrosoftTokenCipher::new()),
@@ -258,6 +264,7 @@ async fn free_account_at_mixed_provider_limit_cannot_start_a_new_connection() {
service
.start_link(
Uuid::now_v7(),
+ &MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"https://macro.test/callback".into(),
None,
false,
@@ -267,3 +274,202 @@ async fn free_account_at_mixed_provider_limit_cannot_start_a_new_connection() {
Err(MicrosoftAuthError::PaymentRequired)
));
}
+
+#[tokio::test]
+async fn new_connections_need_the_switch_and_the_users_flag() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let cases = [
+ // (switch, flags configured, the user's flag load, admitted)
+ (
+ true,
+ true,
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(true),
+ )])),
+ true,
+ ),
+ (
+ true,
+ true,
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(false),
+ )])),
+ false,
+ ),
+ (true, true, Ok(FlagSnapshot::default()), false),
+ (true, true, Err("PostHog unreachable".to_owned()), false),
+ (true, false, Err("never loaded".to_owned()), true),
+ (
+ false,
+ true,
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(true),
+ )])),
+ false,
+ ),
+ (false, false, Err("never loaded".to_owned()), false),
+ ];
+ for (switch, configured, load, admitted) in cases {
+ let mut flags = FakeFeatureFlags::default();
+ flags.set(user.clone(), load.clone());
+ let service = Service::new(
+ MockMicrosoftGrantRepository::new(),
+ MockMicrosoftIdentityProvider::new(),
+ Arc::new(MockMicrosoftTokenCipher::new()),
+ )
+ .with_connections_enabled(switch)
+ .with_feature_flags(configured.then_some(flags));
+ assert_eq!(
+ service.new_connections_enabled(&user).await,
+ admitted,
+ "switch {switch}, configured {configured}, load {load:?}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn flagged_off_user_cannot_start_a_new_connection() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ for load in [
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(false),
+ )])),
+ Err("PostHog unreachable".to_owned()),
+ ] {
+ let mut repo = MockMicrosoftGrantRepository::new();
+ repo.expect_connection_facts().once().returning(|_, _| {
+ Ok(email::domain::inbox_entitlement::InboxConnectionFacts {
+ professional: true,
+ accessible_inboxes: 0,
+ reconnecting: false,
+ })
+ });
+ let mut flags = FakeFeatureFlags::default();
+ flags.set(user.clone(), load);
+ // No begin_link expectation: a refused start records no attempt.
+ let service = Service::new(
+ repo,
+ MockMicrosoftIdentityProvider::new(),
+ Arc::new(MockMicrosoftTokenCipher::new()),
+ )
+ .with_feature_flags(Some(flags));
+ assert!(matches!(
+ service
+ .start_link(
+ Uuid::now_v7(),
+ &user,
+ "https://macro.test/callback".into(),
+ None,
+ false,
+ None
+ )
+ .await,
+ Err(MicrosoftAuthError::NotConfigured)
+ ));
+ }
+}
+
+#[tokio::test]
+async fn flagged_on_user_starts_a_new_connection() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let mut repo = MockMicrosoftGrantRepository::new();
+ repo.expect_connection_facts().once().returning(|_, _| {
+ Ok(email::domain::inbox_entitlement::InboxConnectionFacts {
+ professional: true,
+ accessible_inboxes: 0,
+ reconnecting: false,
+ })
+ });
+ repo.expect_begin_link().once().returning(|_| Ok(()));
+ let mut provider = MockMicrosoftIdentityProvider::new();
+ provider
+ .expect_identity_provider_id()
+ .once()
+ .returning(|| Ok("microsoft".into()));
+ provider
+ .expect_authorize()
+ .once()
+ .returning(|_| Ok("https://login.example.com/authorize".into()));
+ let mut flags = FakeFeatureFlags::default();
+ flags.set(
+ user.clone(),
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(true),
+ )])),
+ );
+ let service = Service::new(repo, provider, Arc::new(MockMicrosoftTokenCipher::new()))
+ .with_feature_flags(Some(flags));
+ let started = service
+ .start_link(
+ Uuid::now_v7(),
+ &user,
+ "https://macro.test/callback".into(),
+ None,
+ false,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ started.authorization_url,
+ "https://login.example.com/authorize"
+ );
+}
+
+#[tokio::test]
+async fn reconnecting_an_inbox_never_depends_on_the_flag_or_the_switch() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let reconnect = Uuid::now_v7();
+ for load in [
+ Ok(FlagSnapshot::new([(
+ OUTLOOK_FLAG.into(),
+ FlagValue::Boolean(false),
+ )])),
+ Err("PostHog unreachable".to_owned()),
+ ] {
+ let mut repo = MockMicrosoftGrantRepository::new();
+ repo.expect_connection_facts()
+ .once()
+ .withf(move |_, id| *id == Some(reconnect))
+ .returning(|_, _| {
+ Ok(email::domain::inbox_entitlement::InboxConnectionFacts {
+ professional: false,
+ accessible_inboxes: 2,
+ reconnecting: true,
+ })
+ });
+ repo.expect_begin_link().once().returning(|_| Ok(()));
+ let mut provider = MockMicrosoftIdentityProvider::new();
+ provider
+ .expect_identity_provider_id()
+ .once()
+ .returning(|| Ok("microsoft".into()));
+ provider
+ .expect_authorize()
+ .once()
+ .returning(|_| Ok("https://login.example.com/authorize".into()));
+ let mut flags = FakeFeatureFlags::default();
+ flags.set(user.clone(), load);
+ let service = Service::new(repo, provider, Arc::new(MockMicrosoftTokenCipher::new()))
+ .with_connections_enabled(false)
+ .with_feature_flags(Some(flags));
+ assert!(
+ service
+ .start_link(
+ Uuid::now_v7(),
+ &user,
+ "https://macro.test/callback".into(),
+ None,
+ false,
+ Some(reconnect),
+ )
+ .await
+ .is_ok()
+ );
+ }
+}
diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rs
index 2eb77ee063..1d79239bf0 100644
--- a/services/authentication_service/src/server.rs
+++ b/services/authentication_service/src/server.rs
@@ -235,6 +235,20 @@ pub async fn run() -> anyhow::Result<()> {
None => auth_client,
};
tracing::trace!("initialized auth client");
+ // Gates new Outlook connections per user (`enable-outlook`). Without a
+ // PostHog key the deployment switch alone decides.
+ let feature_flags = config
+ .posthog_api_key
+ .value()
+ .map(|key| {
+ feature_flags::outbound::posthog::PostHogFeatureFlags::new(
+ config.posthog_host.value().unwrap_or(DEFAULT_POSTHOG_HOST),
+ key.to_owned(),
+ Duration::from_secs(3),
+ )
+ })
+ .transpose()
+ .map_err(|error| anyhow!("invalid feature flag configuration: {error}"))?;
let microsoft_auth = microsoft_token_cipher.map(|cipher| {
use crate::{
domain::microsoft::{MicrosoftAuth, MicrosoftAuthService},
@@ -249,7 +263,8 @@ pub async fn run() -> anyhow::Result<()> {
),
cipher,
)
- .with_connections_enabled(config.outlook_connections_enabled),
+ .with_connections_enabled(config.outlook_connections_enabled)
+ .with_feature_flags(feature_flags),
) as Arc<dyn MicrosoftAuth>
});
@@ -348,8 +363,8 @@ pub async fn run() -> anyhow::Result<()> {
host: config
.posthog_host
.value()
- .map(str::to_string)
- .unwrap_or_else(|| "https://us.i.posthog.com".to_string()),
+ .unwrap_or(DEFAULT_POSTHOG_HOST)
+ .to_string(),
}
}),
}));
@@ -820,6 +835,8 @@ pub async fn run() -> anyhow::Result<()> {
const EVENT_BROKER_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
const INVITE_REMINDER_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
const MICROSOFT_GRANT_CLEANUP_INTERVAL: Duration = Duration::from_secs(5 * 60);
+/// PostHog's US ingestion origin, used when `POSTHOG_HOST` is unset.
+const DEFAULT_POSTHOG_HOST: &str = "https://us.i.posthog.com";
// SAFETY: this is not a secret value
const IOS_DEVELOPMENT_TEAM_ID: &str = "TY74Q77JBD";