Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(email): wire /link/gmail → callback → /email/init for multi-inbox (#3593)

gbirman63116da0ca35
diff --git a/js/app/packages/app/component/EmailAuth.tsx b/js/app/packages/app/component/EmailAuth.tsx
index e27fa80489..206abc6888 100644
--- a/js/app/packages/app/component/EmailAuth.tsx
+++ b/js/app/packages/app/component/EmailAuth.tsx
@@ -6,12 +6,13 @@ import { toast } from '@core/component/Toast/Toast';
import { useEmailLinks } from '@core/email-link';
import { whenSettled } from '@core/util/whenSettled';
import { invalidateAllAfterLogin } from '@queries/auth/user-info';
-import { useNavigate } from '@solidjs/router';
+import { useNavigate, useSearchParams } from '@solidjs/router';
import { onMount, Suspense } from 'solid-js';
type EmailAuthParams = {
callbackPath: string;
successPath: string;
+ linkCallbackPath: string;
};
export function makeEmailAuthComponents(params: EmailAuthParams) {
@@ -29,7 +30,13 @@ export function makeEmailAuthComponents(params: EmailAuthParams) {
/>
</Suspense>
),
+ EmailLinkCallback: () => (
+ <Suspense>
+ <EmailLinkCallback successPath={params.successPath} />
+ </Suspense>
+ ),
CALLBACK_PATH: params.callbackPath,
+ LINK_CALLBACK_PATH: params.linkCallbackPath,
};
}
@@ -82,7 +89,58 @@ function EmailSignupCallback(props: Pick<EmailAuthParams, 'successPath'>) {
return <LoadingBlock />;
}
-function EmailSignUp(props: EmailAuthParams) {
+/**
+ * Handles the OAuth callback after an already-authenticated user adds another Gmail
+ * inbox via /link/gmail. Reads `link_id` from the query string and invokes init to
+ * provision the second `email_links` row. Falls back to a toast on failure.
+ */
+function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {
+ const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
+ const { query, initEmailLink } = useEmailLinks();
+
+ const navigateToSuccess = () => {
+ navigate(props.successPath, { replace: true });
+ };
+
+ whenSettled(
+ query,
+ async () => {
+ const linkId =
+ typeof searchParams.link_id === 'string' ? searchParams.link_id : null;
+ if (!linkId) {
+ toast.failure('Missing link id in callback URL');
+ navigateToSuccess();
+ return;
+ }
+
+ await initEmailLink({ linkId }).match(
+ () => {
+ toast.success('Inbox connected');
+ navigateToSuccess();
+ },
+ (err) => {
+ if (err.tag === 'AlreadyInitialized') {
+ navigateToSuccess();
+ return;
+ }
+ toast.failure('Failed to add inbox');
+ navigateToSuccess();
+ }
+ );
+ },
+ (error) => {
+ toast.failure(error.message);
+ navigateToSuccess();
+ }
+ );
+
+ return <LoadingBlock />;
+}
+
+function EmailSignUp(
+ props: Pick<EmailAuthParams, 'callbackPath' | 'successPath'>
+) {
const navigate = useNavigate();
const { query: emailLinks } = useEmailLinks();
const analytics = useAnalytics();
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index 91eb19234e..412d4d9b83 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -254,10 +254,12 @@ function NotFound() {
return '';
}
-const { EmailCallback, CALLBACK_PATH } = makeEmailAuthComponents({
- callbackPath: '/email-signup-callback',
- successPath: '/',
-});
+const { EmailCallback, CALLBACK_PATH, EmailLinkCallback, LINK_CALLBACK_PATH } =
+ makeEmailAuthComponents({
+ callbackPath: '/email-signup-callback',
+ linkCallbackPath: '/inbox-link-callback',
+ successPath: '/',
+ });
const ROUTES: RouteDefinition[] = [
LAYOUT_ROUTE,
@@ -308,6 +310,10 @@ const ROUTES: RouteDefinition[] = [
path: CALLBACK_PATH,
component: EmailCallback,
},
+ {
+ path: LINK_CALLBACK_PATH,
+ component: EmailLinkCallback,
+ },
{
path: '/login/popup/success',
component: () => {
diff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsx
index 39be6df2ac..c5f488cecf 100644
--- a/js/app/packages/app/component/settings/Account.tsx
+++ b/js/app/packages/app/component/settings/Account.tsx
@@ -16,6 +16,7 @@ import {
DEV_MODE_ENV,
ENABLE_AUTO_UPDATE_UI,
ENABLE_EMAIL,
+ ENABLE_MULTI_INBOX,
ENABLE_PROFILE_PICTURES,
ENABLE_NEW_PRICING_OVERRIDE,
} from '@core/constant/featureFlags';
@@ -45,10 +46,9 @@ import { useSettingsState } from '@core/constant/SettingsState';
import PaywallComponent from '../paywall/PaywallComponent';
import PaywallTeamMemberView from '../paywall/PaywallTeamMemberView';
import PaywallTeamOwnerView from '../paywall/PaywallTeamOwnerView';
-import {
- useEmailLinks,
- useEmailLinksStatus,
-} from '@core/email-link';
+import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
+import { useEmailLinks, useEmailLinksStatus } from '@core/email-link';
+import { useInitGmailLink } from '@queries/auth';
import {
type SupportedNotificationSettings,
useNotificationSettings,
@@ -151,6 +151,17 @@ export function Account() {
const emailActive = useEmailLinksStatus();
+ const initGmailLink = useInitGmailLink();
+ const handleAddInbox = async () => {
+ const callbackUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}inbox-link-callback`;
+ const result = await initGmailLink.mutateAsync(callbackUrl);
+ if (result.isOk()) {
+ window.location.href = result.value.authorization_url;
+ } else {
+ toast.failure('Failed to start Gmail link flow');
+ }
+ };
+
const [githubLinkExists, { refetch: refetchGithubLink }] = createResource(async () => {
const response = await authServiceClient.checkLinkExists({ idp_name: 'github' });
return response.isOk() ? response.value.link_exists : false;
@@ -333,14 +344,26 @@ export function Account() {
<Show
when={!emailActive()}
fallback={
- <Button
- variant="base"
- size="sm"
- depth={3}
- onClick={() => setShowEmailModal(true)}
- >
- Disable
- </Button>
+ <div class="flex items-center gap-2">
+ <Show when={ENABLE_MULTI_INBOX}>
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ onClick={handleAddInbox}
+ >
+ Add Inbox
+ </Button>
+ </Show>
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ onClick={() => setShowEmailModal(true)}
+ >
+ Disable
+ </Button>
+ </div>
}
>
<Show when={!showEnableEmailModal()}>
diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.ts
index ff4b0cbebe..e7972fde3e 100644
--- a/js/app/packages/core/constant/featureFlags.ts
+++ b/js/app/packages/core/constant/featureFlags.ts
@@ -236,6 +236,11 @@ const _ENABLE_DOCK_NOTITIFCATIONS = resolveFeatureFlag(
);
export const ENABLE_TTFT = resolveFeatureFlag('ENABLE_TTFT', DEV_MODE_ENV);
+export const ENABLE_MULTI_INBOX = resolveFeatureFlag(
+ 'ENABLE_MULTI_INBOX',
+ DEV_MODE_ENV
+);
+
const _ENABLE_TASKS_TABS = resolveFeatureFlag('ENABLE_TASKS_TABS', true);
export const ENABLE_EMAIL_SHARING = resolveFeatureFlag(
diff --git a/js/app/packages/core/email-link/index.ts b/js/app/packages/core/email-link/index.ts
index d253a6c6cd..863191f185 100644
--- a/js/app/packages/core/email-link/index.ts
+++ b/js/app/packages/core/email-link/index.ts
@@ -40,28 +40,34 @@ type EmailInitError =
/**
* Calls email service to start syncing and initialize a new email link.
*
+ * Pass `linkId` to complete a multi-inbox add via the `/link/gmail` flow — init will
+ * read the `in_progress_user_link` row and provision a second `email_links` scoped to
+ * that linked email. Omit for the first-time signup path.
+ *
* @returns ok if syncing was started, err if syncing failed
*/
-function initEmailLink(): ResultAsync<void, EmailInitError> {
- return ResultAsync.fromSafePromise(emailClient.init()).andThen(
- (initResult) => {
- if (initResult.isErr()) {
- const badRequestError = initResult.error.find(
- // TODO: this is cope but seems like error.code not being set correctly
- (e) => e.message.includes('400')
- );
- return err(
- badRequestError
- ? { tag: 'AlreadyInitialized' as const }
- : {
- tag: 'FailedToInitialize' as const,
- message: 'Failed to initialize',
- }
- );
- }
- return okAsync(undefined);
+function initEmailLink(args?: {
+ linkId?: string;
+}): ResultAsync<void, EmailInitError> {
+ return ResultAsync.fromSafePromise(
+ emailClient.init({ linkId: args?.linkId })
+ ).andThen((initResult) => {
+ if (initResult.isErr()) {
+ const badRequestError = initResult.error.find(
+ // TODO: this is cope but seems like error.code not being set correctly
+ (e) => e.message.includes('400')
+ );
+ return err(
+ badRequestError
+ ? { tag: 'AlreadyInitialized' as const }
+ : {
+ tag: 'FailedToInitialize' as const,
+ message: 'Failed to initialize',
+ }
+ );
}
- );
+ return okAsync(undefined);
+ });
}
/**
@@ -150,11 +156,11 @@ export function useEmailLinks() {
return {
query: query,
isConnected: () => hasEmailLinks(query),
- initEmailLink: () =>
- initEmailLink().map(startEmailPolling).map(invalidations),
+ initEmailLink: (args?: { linkId?: string }) =>
+ initEmailLink(args).map(startEmailPolling).map(invalidations),
connect: () =>
connectEmail()
- .andThen(initEmailLink)
+ .andThen(() => initEmailLink())
.map(startEmailPolling)
.andTee(invalidations),
disconnect: () => disconnectEmail().andTee(invalidations),
diff --git a/js/app/packages/queries/auth/gmail-link.ts b/js/app/packages/queries/auth/gmail-link.ts
new file mode 100644
index 0000000000..14d6ead65c
--- /dev/null
+++ b/js/app/packages/queries/auth/gmail-link.ts
@@ -0,0 +1,15 @@
+import { authServiceClient } 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.
+ */
+export function useInitGmailLink() {
+ return useMutation(() => ({
+ mutationFn: async (originalUrl: string) => {
+ return authServiceClient.initGmailLink(originalUrl);
+ },
+ }));
+}
diff --git a/js/app/packages/queries/auth/index.ts b/js/app/packages/queries/auth/index.ts
index cddd4d0b57..f28bb4d0fe 100644
--- a/js/app/packages/queries/auth/index.ts
+++ b/js/app/packages/queries/auth/index.ts
@@ -4,6 +4,7 @@ export {
useUserId,
useUserInfo,
} from '@core/context/user';
+export { useInitGmailLink } from './gmail-link';
export { authKeys } from './keys';
export { useSendMobileWelcomeEmail } from './mobile-welcome-email';
export {} from './mutations';
diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.ts
index bcd8dcaa70..34710906ab 100644
--- a/js/app/packages/service-clients/service-auth/client.ts
+++ b/js/app/packages/service-clients/service-auth/client.ts
@@ -13,6 +13,7 @@ import type {
EnrichGithubPullRequestsProxyRequest,
EnrichGithubPullRequestsResponse,
InitGithubLinkResponse,
+ InitGmailLinkResponse,
PatchSubscriptionTierRequest,
PatchUserTutorialRequest,
SendMobileWelcomeEmailResponse,
@@ -559,6 +560,23 @@ export const authServiceClient = {
).map((result) => result.authorization_url);
},
+ /**
+ * Initializes a gmail account link for the already-authenticated user (multi-inbox flow).
+ * 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.
+ */
+ async initGmailLink(originalUrl?: string) {
+ const url = originalUrl
+ ? `${authHost}/link/gmail?original_url=${encodeURIComponent(originalUrl)}`
+ : `${authHost}/link/gmail`;
+ return (
+ await fetchWithAuth<InitGmailLinkResponse>(url, {
+ method: 'POST',
+ })
+ ).map((result) => result);
+ },
+
/**
* Deletes a github link for a user
* NOTE: this does not delete the github application from being installed on a teams repository
diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.ts
index f6546838ef..7ccfeba92e 100644
--- a/js/app/packages/service-clients/service-email/client.ts
+++ b/js/app/packages/service-clients/service-email/client.ts
@@ -52,9 +52,12 @@ function emailFetch<T extends ObjectLike = never>(
}
export const emailClient = {
- async init() {
+ async init(args?: { linkId?: string }) {
+ const path = args?.linkId
+ ? `/email/init?link_id=${encodeURIComponent(args.linkId)}`
+ : '/email/init';
return (
- await emailFetch<EmptyResponse>('/email/init', {
+ await emailFetch<EmptyResponse>(path, {
method: 'POST',
})
).map((result) => result);
diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.ts
index 10b701b982..e019fde301 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -29,6 +29,7 @@ import type {
GetThreadParams,
GetThreadResponse,
InitResponse,
+ InitUserParams,
ListBlockedResponse,
ListContactsResponse,
ListEmailFiltersResponse,
@@ -1458,14 +1459,27 @@ export type initUserResponseError = (
export type initUserResponse = initUserResponseSuccess | initUserResponseError;
-export const getInitUserUrl = () => {
- return `/email/init`;
+export const getInitUserUrl = (params?: InitUserParams) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/email/init?${stringifiedParams}`
+ : `/email/init`;
};
export const initUser = async (
+ params?: InitUserParams,
options?: RequestInit
): Promise<initUserResponse> => {
- const res = await fetch(getInitUserUrl(), {
+ const res = await fetch(getInitUserUrl(params), {
...options,
method: 'POST',
});
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
index c9bd8ceaac..3623381c7d 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
@@ -174,6 +174,7 @@ export * from './getThreadMessagesHandlerParams';
export * from './getThreadParams';
export * from './getThreadResponse';
export * from './initResponse';
+export * from './initUserParams';
export * from './label';
export * from './labelId';
export * from './labelInfo';
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/initUserParams.ts b/js/app/packages/service-clients/service-email/generated/schemas/initUserParams.ts
new file mode 100644
index 0000000000..6ba2ba7388
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/initUserParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type InitUserParams = {
+ /**
+ * **OPTIONAL**. The in_progress_user_link id from a /link/gmail flow.
+ */
+ link_id?: string;
+};
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index c2c8599c02..28333f7640 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -1293,6 +1293,18 @@
"tags": ["Init"],
"summary": "Initialize email functionality for the user. Populates initial threads and enables inbox syncing.",
"operationId": "init_user",
+ "parameters": [
+ {
+ "name": "link_id",
+ "in": "query",
+ "description": "**OPTIONAL**. The in_progress_user_link id from a /link/gmail flow.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
"responses": {
"200": {
"description": "",
diff --git a/local_stack.just b/local_stack.just
index cb8e3f7874..c828d03ca8 100644
--- a/local_stack.just
+++ b/local_stack.just
@@ -2,14 +2,18 @@
export AWS_PAGER := ""
# Start LocalStack for local AWS emulation
+# Pinned to v4 — `latest` requires LOCALSTACK_AUTH_TOKEN for all features.
start_localstack:
docker rm -f localstack 2>/dev/null || true
docker run -d --name localstack \
--network databases \
-p 4566:4566 \
-e SERVICES=sqs,dynamodb,s3 \
- localstack/localstack
+ localstack/localstack:4
@echo "LocalStack started"
+ @echo "Waiting for LocalStack to be ready..."
+ @until curl -fsS http://localhost:4566/_localstack/health >/dev/null 2>&1; do sleep 1; done
+ @echo "LocalStack ready"
# Create SQS queues in LocalStack
create_local_queues:
@@ -117,7 +121,6 @@ configure_document_upload_finalizer_notifications:
# Full LocalStack setup
setup_localstack:
just start_localstack
- sleep 2
just create_local_queues
just create_local_tables
just create_local_buckets
diff --git a/rust/cloud-storage/.sqlx/query-131fdac5ab0aba8955d6900eb7390dd279939a1323b5805eaae071cc500f54dc.json b/rust/cloud-storage/.sqlx/query-131fdac5ab0aba8955d6900eb7390dd279939a1323b5805eaae071cc500f54dc.json
new file mode 100644
index 0000000000..5c4540cc5a
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-131fdac5ab0aba8955d6900eb7390dd279939a1323b5805eaae071cc500f54dc.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE in_progress_user_link\n SET linked_email = $1\n WHERE id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "131fdac5ab0aba8955d6900eb7390dd279939a1323b5805eaae071cc500f54dc"
+}
diff --git a/rust/cloud-storage/.sqlx/query-4a8b04d2fa922cd2f007241f83d6ad7e4dbcb5e7f6b0560316ca474878971e63.json b/rust/cloud-storage/.sqlx/query-4a8b04d2fa922cd2f007241f83d6ad7e4dbcb5e7f6b0560316ca474878971e63.json
new file mode 100644
index 0000000000..c905db25bd
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-4a8b04d2fa922cd2f007241f83d6ad7e4dbcb5e7f6b0560316ca474878971e63.json
@@ -0,0 +1,84 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, created_at, updated_at\n FROM email_links\n WHERE fusionauth_user_id = $1 AND email_address = $2 AND provider = $3\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "fusionauth_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "provider: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_user_provider_enum",
+ "kind": {
+ "Enum": [
+ "GMAIL"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 5,
+ "name": "is_sync_active",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ {
+ "Custom": {
+ "name": "email_user_provider_enum",
+ "kind": {
+ "Enum": [
+ "GMAIL"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "4a8b04d2fa922cd2f007241f83d6ad7e4dbcb5e7f6b0560316ca474878971e63"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9e998a79214f591775e9d6711c9086235243eae535cc42bb0908210b54b916d8.json b/rust/cloud-storage/.sqlx/query-9e998a79214f591775e9d6711c9086235243eae535cc42bb0908210b54b916d8.json
new file mode 100644
index 0000000000..d07bcde732
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-9e998a79214f591775e9d6711c9086235243eae535cc42bb0908210b54b916d8.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"macro_user_id\"\n FROM \"User\"\n WHERE \"email\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_user_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "9e998a79214f591775e9d6711c9086235243eae535cc42bb0908210b54b916d8"
+}
diff --git a/rust/cloud-storage/.sqlx/query-fafa84eb636a2855f683f73eba494f9ce25445a642ef58e1f8a59788a7f374b8.json b/rust/cloud-storage/.sqlx/query-fafa84eb636a2855f683f73eba494f9ce25445a642ef58e1f8a59788a7f374b8.json
new file mode 100644
index 0000000000..9c9523edbb
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-fafa84eb636a2855f683f73eba494f9ce25445a642ef58e1f8a59788a7f374b8.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n macro_user_id,\n linked_email\n FROM\n in_progress_user_link\n WHERE\n id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_user_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "linked_email",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "fafa84eb636a2855f683f73eba494f9ce25445a642ef58e1f8a59788a7f374b8"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a6a849d453..213c465ba5 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4013,6 +4013,7 @@ dependencies = [
"macro_auth",
"macro_aws_config",
"macro_cors",
+ "macro_db_client",
"macro_entrypoint",
"macro_env",
"macro_env_var",
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs
index 3454f2b974..3d6023e13e 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs
@@ -4,11 +4,12 @@ use std::borrow::Cow;
use axum::{
Json,
- response::{IntoResponse, Response},
+ response::{IntoResponse, Redirect, Response},
};
use model::response::ErrorResponse;
use reqwest::StatusCode;
use tower_cookies::Cookies;
+use url::Url;
use crate::api::{
context::ApiContext,
@@ -17,7 +18,6 @@ use crate::api::{
login::{self},
},
};
-use authentication_service::service::user::create_user::create_user_profile;
use fusionauth::identity_provider::{IdentityProviderLink, LinkUserRequest};
async fn link_user(
@@ -26,7 +26,6 @@ async fn link_user(
code: &str,
link_id: &uuid::Uuid,
) -> Result<(), (StatusCode, String)> {
- // Get existing macro user id from link id
let macro_user_id =
macro_db_client::in_progress_user_link::get_macro_user_id_by_link_id(&ctx.db, link_id)
.await
@@ -62,68 +61,49 @@ async fn link_user(
)
})?;
- // Check if this is an account merge situation
- match macro_db_client::user::get::get_user_id_by_email(ctx.db.clone(), &user_info_email).await {
- Ok(_) => {
- // NOTE: the user profile already exists, we need to handle account merging separately
- return Err((
- StatusCode::NOT_IMPLEMENTED,
- "user profile already exists".to_string(),
- ));
- }
- Err(_e) => (), // if there is an error we assume that it's because the user does not exist
+ // Reject account-merge attempts: a different macro user already owns this email.
+ // Same-user re-linking (e.g. user adds their primary Gmail again) is allowed — init's
+ // idempotency check on email_links will short-circuit downstream.
+ if let Some(existing_macro_user_id) =
+ macro_db_client::user::get::get_macro_user_id_by_email(&ctx.db, &user_info_email)
+ .await
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
+ && existing_macro_user_id != macro_user_id
+ {
+ return Err((
+ StatusCode::NOT_IMPLEMENTED,
+ "user profile already exists".to_string(),
+ ));
}
- // Creates the new user profile
- create_user_profile(&macro_user_id.to_string(), &user_info.email, &ctx.db)
- .await
- .map_err(|e| {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- format!("unable to create user profile {e}"),
- )
- })?;
-
- // With the token response and the user's macro_user_id, we can now link the user
- match ctx
- .auth_client
+ ctx.auth_client
.link_user(LinkUserRequest {
identity_provider_link: IdentityProviderLink {
display_name: user_info_email.clone(),
identity_provider_id: Cow::Borrowed(identity_provider_id),
- identity_provider_user_id: Cow::Borrowed(&user_info.sub), // google user id
- user_id: Cow::Borrowed(&macro_user_id.to_string()), // fusionauth user id
- token: Cow::Borrowed(&token_response.refresh_token), // For google, this is the refresh token
+ identity_provider_user_id: Cow::Borrowed(&user_info.sub),
+ user_id: Cow::Borrowed(&macro_user_id.to_string()),
+ token: Cow::Borrowed(&token_response.refresh_token),
},
})
.await
- {
- Ok(()) => (),
- Err(e) => {
- let macro_user_id = format!("macro|{}", &user_info_email);
-
- let _ = macro_db_client::user::delete_user::delete_user(&ctx.db, &macro_user_id)
- .await
- .inspect_err(|e| {
- tracing::error!(
- error=?e,
- "unable to delete user {user_info_email}"
- );
- });
-
- return Err((
+ .map_err(|e| {
+ (
StatusCode::INTERNAL_SERVER_ERROR,
format!("unable to link user {e}"),
- ));
- }
- }
+ )
+ })?;
- // delete in_progress_user_link once complete
- let _ = macro_db_client::in_progress_user_link::delete_in_progress_user_link(&ctx.db, link_id)
+ // Stash the linked email on the in_progress_user_link row so /email/init can pick it up.
+ // The row is consumed and deleted by /email/init once the email_links record is created.
+ macro_db_client::in_progress_user_link::set_linked_email(&ctx.db, link_id, &user_info_email)
.await
- .inspect_err(|e| {
- tracing::error!(error=?e, "unable to delete in progress user link");
- });
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unable to record linked email on in_progress_user_link {e}"),
+ )
+ })?;
Ok(())
}
@@ -149,7 +129,38 @@ pub(in crate::api::oauth2) async fn handler(
)
.into_response()
})?;
- // Early exit, we don't actually log the user into fusionauth
+
+ if let Some(original_url) = &state.original_url {
+ let decoded = urlencoding::decode(original_url).map_err(|e| {
+ tracing::error!(error=?e, "unable to decode original url");
+ (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: "unable to decode original url".into(),
+ }),
+ )
+ .into_response()
+ })?;
+
+ let mut url: Url = decoded
+ .parse()
+ .inspect_err(|e| tracing::error!(error=?e, "unable to parse string to url"))
+ .map_err(|_| {
+ (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: "unable to parse to original url".into(),
+ }),
+ )
+ .into_response()
+ })?;
+
+ url.query_pairs_mut()
+ .append_pair("link_id", &link_id.to_string());
+
+ return Ok(Redirect::to(url.as_str()).into_response());
+ }
+
return Ok(StatusCode::OK.into_response());
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
index 45d9fe0d13..b7be91938e 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
@@ -37,6 +37,39 @@ pub(super) async fn link_by_fusionauth_and_macro_id(
.map_err(|e| sqlx::Error::Decode(Box::new(e)))
}
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn link_by_fusionauth_email_provider(
+ pool: &PgPool,
+ fusionauth_user_id: &str,
+ email_address: &str,
+ provider: UserProvider,
+) -> Result<Option<Link>, sqlx::Error> {
+ let provider: DbUserProvider = match provider {
+ UserProvider::Gmail => DbUserProvider::Gmail,
+ };
+
+ let db_link = sqlx::query_as!(
+ DbLink,
+ r#"
+ SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
+ is_sync_active, created_at, updated_at
+ FROM email_links
+ WHERE fusionauth_user_id = $1 AND email_address = $2 AND provider = $3
+ LIMIT 1
+ "#,
+ fusionauth_user_id,
+ email_address,
+ provider as _
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ db_link
+ .map(|v| v.try_into_model())
+ .transpose()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))
+}
+
#[tracing::instrument(err, skip(pool))]
pub(super) async fn link_by_macro_id(
pool: &PgPool,
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
index e9884aa163..a56ca0aec0 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
@@ -37,6 +37,21 @@ impl EmailPgRepo {
pub fn new(pool: PgPool) -> Self {
EmailPgRepo { pool }
}
+
+ pub async fn link_by_fusionauth_email_provider(
+ &self,
+ fusionauth_user_id: &str,
+ email_address: &str,
+ provider: UserProvider,
+ ) -> Result<Option<Link>, sqlx::Error> {
+ link::link_by_fusionauth_email_provider(
+ &self.pool,
+ fusionauth_user_id,
+ email_address,
+ provider,
+ )
+ .await
+ }
}
impl EmailRepo for EmailPgRepo {
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs
index 01ad3fdd9b..981a065fa9 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs
@@ -65,3 +65,66 @@ async fn test_link_by_fusionauth_and_macro_id_wrong_macro_id(
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_link_by_fusionauth_email_provider_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let link = repo
+ .link_by_fusionauth_email_provider("fa-user-1", "[email protected]", UserProvider::Gmail)
+ .await?;
+
+ assert!(link.is_some(), "Link should exist for the fixture row");
+ let link = link.unwrap();
+ assert_eq!(link.fusionauth_user_id, "fa-user-1");
+ assert_eq!(link.email_address.0.as_ref(), "[email protected]");
+ assert_eq!(link.provider, UserProvider::Gmail);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_link_by_fusionauth_email_provider_wrong_email(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let link = repo
+ .link_by_fusionauth_email_provider("fa-user-1", "[email protected]", UserProvider::Gmail)
+ .await?;
+
+ assert!(link.is_none(), "Wrong email should return None");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_link_by_fusionauth_email_provider_wrong_fusionauth(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let link = repo
+ .link_by_fusionauth_email_provider(
+ "nonexistent-fa-user",
+ UserProvider::Gmail,
+ )
+ .await?;
+
+ assert!(
+ link.is_none(),
+ "Wrong fusionauth_user_id should return None"
+ );
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index e93b4b5539..368733f39a 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -98,6 +98,7 @@ item_filters = { path = "../item_filters" }
lol_html = "2.4.0"
macro_auth = { path = "../macro_auth" }
macro_cors = { path = "../macro_cors" }
+macro_db_client = { path = "../macro_db_client" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
mailparse = "0.16.1"
diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rs
index 077e244d9a..b466d505b9 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -2,17 +2,17 @@ use crate::api::ApiContext;
use crate::utils::extract_email_with_response;
use anyhow::Context;
use axum::{
- Extension,
- extract::State,
+ extract::{Query, State},
http::StatusCode,
response::{IntoResponse, Json, Response},
};
use email::domain::models::UserProvider;
use email::domain::ports::EmailRepo;
+use email::outbound::EmailPgRepo;
+use email_utils::token_cache_key::TokenCacheKey;
use macro_user_id::email::EmailStr;
use macro_user_id::user_id::MacroUserIdStr;
use model::response::ErrorResponse;
-use model::user::UserContext;
use model::user::axum_extractor::MacroUserExtractor;
use models_email::email::service::backfill::{
BackfillJobStatus, BackfillOperation, BackfillPubsubMessage, InitPayload, JobScopedPayload,
@@ -70,11 +70,21 @@ pub struct InitResponse {
pub backfill_job_id: Uuid,
}
+#[derive(Debug, serde::Deserialize)]
+pub struct InitParams {
+ /// Optional link id from a `/link/gmail` flow. When set, init provisions the inbox
+ /// for the email recorded on the in_progress_user_link row instead of the JWT email.
+ link_id: Option<Uuid>,
+}
+
/// Initialize email functionality for the user. Populates initial threads and enables inbox syncing.
#[utoipa::path(
post,
tag = "Init",
path = "/email/init",
+ params(
+ ("link_id" = Option<Uuid>, Query, description = "**OPTIONAL**. The in_progress_user_link id from a /link/gmail flow."),
+ ),
operation_id = "init_user",
responses(
(status = 200, body=InitResponse),
@@ -83,172 +93,248 @@ pub struct InitResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, gmail_token), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, user_extractor), fields(user_id=user_extractor.user_context.user_id, fusionauth_user_id=user_extractor.user_context.fusion_user_id), err)]
pub async fn handler(
State(ctx): State<ApiContext>,
- MacroUserExtractor {
+ Query(InitParams { link_id }): Query<InitParams>,
+ user_extractor: MacroUserExtractor,
+) -> Result<Response, InitError> {
+ let MacroUserExtractor {
macro_user_id,
user_context,
..
- }: MacroUserExtractor,
- gmail_token: Extension<String>,
-) -> Result<Response, InitError> {
- tracing::info!(user_id = %user_context.user_id, "Init called");
- // Fetch the existing link for the user
- let pg_repo = email::outbound::EmailPgRepo::new(ctx.db.clone());
- let existing_link = pg_repo
- .link_by_fusionauth_and_macro_id(
- &user_context.fusion_user_id,
- macro_user_id,
- UserProvider::Gmail,
- )
- .await
- .context("Failed to fetch existing link")?;
-
- // Handle different cases based on the existing link's state
- match &existing_link {
- // Case 1: User already has a link
- Some(_) => Err(InitError::AlreadyInitialized),
-
- // Case 2 & 3: Enable sync for new users
- None => {
- let link = enable_gmail_sync(&ctx, &user_context, Some(gmail_token.as_str())).await?;
-
- // users can only have 3 jobs within past 24h and one backfill job per link in progress at a time
- let recent_jobs =
- email_db_client::backfill::job::get::get_recent_jobs_by_fusionauth_user_id(
- &ctx.db,
- &link.fusionauth_user_id,
- )
+ } = user_extractor;
+ tracing::info!(user_id = %user_context.user_id, ?link_id, "Init called");
+
+ let pg_repo = EmailPgRepo::new(ctx.db.clone());
+
+ let (link, email_address) = if let Some(link_id) = link_id {
+ let in_progress =
+ macro_db_client::in_progress_user_link::get_in_progress_user_link(&ctx.db, &link_id)
.await
- .context("Failed to fetch jobs by macro id")?;
+ .context("Failed to fetch in_progress_user_link")?;
- if recent_jobs.len() >= 3 && !link.email_address.0.as_ref().ends_with("@macro.com") {
- tracing::info!(user_id = %user_context.user_id, "Too many jobs error");
- email_db_client::links::delete::delete_link_by_id(&ctx.db, link.id)
- .await
- .context("Failed to delete link")?;
+ if in_progress.macro_user_id.to_string() != user_context.fusion_user_id {
+ return Err(InitError::BadRequest(
+ "link_id does not belong to the requesting user".to_string(),
+ ));
+ }
- return Err(InitError::TooManyJobs);
- }
+ let linked_email = in_progress.linked_email.ok_or_else(|| {
+ InitError::BadRequest("link has not completed authentication yet".to_string())
+ })?;
- // Record link creation in history table for tracking (best-effort)
- email_db_client::links_history::insert::insert_email_link_history(
- &ctx.db,
- link.id,
- &link.fusionauth_user_id,
- link.email_address.0.as_ref(),
- link.provider,
+ if pg_repo
+ .link_by_fusionauth_email_provider(
+ &user_context.fusion_user_id,
+ &linked_email,
+ UserProvider::Gmail,
)
+ .await
+ .context("Failed to check existing link by email")?
+ .is_some()
+ {
+ return Err(InitError::AlreadyInitialized);
+ }
+
+ let gmail_token =
+ fetch_gmail_token_for_email(&ctx, &user_context.fusion_user_id, &linked_email).await?;
+
+ let link = enable_gmail_sync_for(
+ &ctx,
+ &user_context.fusion_user_id,
+ macro_user_id.clone(),
+ &linked_email,
+ &gmail_token,
+ )
+ .await?;
+
+ macro_db_client::in_progress_user_link::delete_in_progress_user_link(&ctx.db, &link_id)
.await
.inspect_err(|e| {
- tracing::error!(error=?e, link_id=?link.id, "Failed to insert email link history");
+ tracing::error!(error=?e, ?link_id, "Failed to delete in_progress_user_link after init");
})
.ok();
- // create job to backfill user's inbox history
- let backfill_job = email_db_client::backfill::job::insert::create_backfill_job(
- &ctx.db,
- link.id,
- link.fusionauth_user_id.as_str(),
- None,
+ (link, linked_email)
+ } else {
+ let existing_link = pg_repo
+ .link_by_fusionauth_and_macro_id(
+ &user_context.fusion_user_id,
+ macro_user_id.clone(),
+ UserProvider::Gmail,
)
.await
- .context("Failed to create backfill job")?;
-
- let ps_message = BackfillPubsubMessage {
- backfill_operation: BackfillOperation::Init(JobScopedPayload {
- link_id: link.id,
- job_id: backfill_job.id,
- payload: InitPayload {},
- }),
- };
-
- if let Err(e) = ctx
- .sqs_client
- .enqueue_email_backfill_message(ps_message)
+ .context("Failed to fetch existing link")?;
+
+ if existing_link.is_some() {
+ return Err(InitError::AlreadyInitialized);
+ }
+
+ let email = extract_email_with_response(&user_context.user_id)
+ .map_err(|_| InitError::BadRequest("Failed to extract email".to_string()))?;
+
+ let gmail_token = email_service::util::gmail::auth::fetch_gmail_token_no_cache(
+ &user_context,
+ &ctx.redis_client,
+ &ctx.auth_service_client,
+ )
+ .await
+ .map_err(|_| InitError::BadRequest("Failed to fetch Gmail token".to_string()))?;
+
+ let link = enable_gmail_sync_for(
+ &ctx,
+ &user_context.fusion_user_id,
+ macro_user_id.clone(),
+ &email,
+ &gmail_token,
+ )
+ .await?;
+
+ (link, email)
+ };
+
+ // users can only have 3 jobs within past 24h and one backfill job per link in progress at a time
+ let recent_jobs = email_db_client::backfill::job::get::get_recent_jobs_by_fusionauth_user_id(
+ &ctx.db,
+ &link.fusionauth_user_id,
+ )
+ .await
+ .context("Failed to fetch jobs by macro id")?;
+
+ if recent_jobs.len() >= 3 && !email_address.ends_with("@macro.com") {
+ tracing::info!(user_id = %user_context.user_id, "Too many jobs error");
+ email_db_client::links::delete::delete_link_by_id(&ctx.db, link.id)
+ .await
+ .context("Failed to delete link")?;
+
+ return Err(InitError::TooManyJobs);
+ }
+
+ // Record link creation in history table for tracking (best-effort)
+ email_db_client::links_history::insert::insert_email_link_history(
+ &ctx.db,
+ link.id,
+ &link.fusionauth_user_id,
+ link.email_address.0.as_ref(),
+ link.provider,
+ )
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, link_id=?link.id, "Failed to insert email link history");
+ })
+ .ok();
+
+ let backfill_job = email_db_client::backfill::job::insert::create_backfill_job(
+ &ctx.db,
+ link.id,
+ link.fusionauth_user_id.as_str(),
+ None,
+ )
+ .await
+ .context("Failed to create backfill job")?;
+
+ let ps_message = BackfillPubsubMessage {
+ backfill_operation: BackfillOperation::Init(JobScopedPayload {
+ link_id: link.id,
+ job_id: backfill_job.id,
+ payload: InitPayload {},
+ }),
+ };
+
+ if let Err(e) = ctx
+ .sqs_client
+ .enqueue_email_backfill_message(ps_message)
+ .await
+ {
+ tracing::error!(error = ?e, backfill_id = %backfill_job.id, "Failed to enqueue backfill message");
+
+ let db_pool = ctx.db.clone();
+ let job_id = backfill_job.id;
+ tokio::spawn(async move {
+ if let Err(update_err) =
+ email_db_client::backfill::job::update::update_backfill_job_status(
+ &db_pool,
+ job_id,
+ BackfillJobStatus::Failed,
+ )
.await
{
- // Log the error
- tracing::error!(error = ?e, backfill_id = %backfill_job.id, "Failed to enqueue backfill message");
-
- // Update the job status to Failed
- let db_pool = ctx.db.clone();
- let job_id = backfill_job.id;
- tokio::spawn(async move {
- if let Err(update_err) =
- email_db_client::backfill::job::update::update_backfill_job_status(
- &db_pool,
- job_id,
- BackfillJobStatus::Failed,
- )
- .await
- {
- tracing::error!(
- error = ?update_err,
- backfill_id = %job_id,
- "Failed to update backfill job status to Failed"
- );
- }
- });
-
- return Err(InitError::EnqueueError);
+ tracing::error!(
+ error = ?update_err,
+ backfill_id = %job_id,
+ "Failed to update backfill job status to Failed"
+ );
}
+ });
- Ok((
- StatusCode::OK,
- Json(InitResponse {
- link_id: link.id,
- backfill_job_id: backfill_job.id,
- }),
- )
- .into_response())
- }
+ return Err(InitError::EnqueueError);
}
+
+ Ok((
+ StatusCode::OK,
+ Json(InitResponse {
+ link_id: link.id,
+ backfill_job_id: backfill_job.id,
+ }),
+ )
+ .into_response())
}
-/// Enables Gmail sync for a user by A) registering a watch with Gmail API B) updating the link record
-/// to is_sync_active = true and C) updating gmail_histories entry with the current history value.
-#[tracing::instrument(skip(ctx, user_context, gmail_access_token), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
-pub async fn enable_gmail_sync(
+/// Fetches a Gmail access token scoped to a specific linked email by constructing the
+/// `macro|<email>` cache key directly. Use this instead of going through the
+/// `UserContext`-keyed path when the target inbox is not the user's primary email.
+async fn fetch_gmail_token_for_email(
ctx: &ApiContext,
- user_context: &UserContext,
- gmail_access_token: Option<&str>,
-) -> Result<Link, InitError> {
- let token = match gmail_access_token {
- Some(token) => token.to_string(),
- None => email_service::util::gmail::auth::fetch_gmail_token_no_cache(
- user_context,
- &ctx.redis_client,
- &ctx.auth_service_client,
- )
+ fusion_user_id: &str,
+ linked_email: &str,
+) -> Result<String, InitError> {
+ let macro_id = format!("macro|{}", linked_email);
+ let key = TokenCacheKey::new(fusion_user_id, macro_id, UserProvider::Gmail.as_str());
+
+ let conn = ctx
+ .redis_client
+ .inner
+ .get_multiplexed_async_connection()
.await
- .map_err(|_| InitError::BadRequest("Failed to fetch Gmail token".to_string()))?,
- };
+ .context("unable to connect to redis")?;
- // Register watch with Gmail
- let watch_response = ctx.gmail_client.register_watch(&token).await?;
+ email::outbound::fetch_gmail_access_token_no_cache(&key, &conn, &ctx.auth_service_client)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to fetch gmail token for linked email");
+ InitError::BadRequest("Failed to fetch Gmail token for linked email".to_string())
+ })
+}
- let email = extract_email_with_response(&user_context.user_id)
- .map_err(|_| InitError::BadRequest("Failed to extract email".to_string()))?;
+/// Registers a Gmail watch, upserts the `email_links` row, and seeds the gmail history entry.
+/// Caller-provided identifiers let this serve both the JWT-driven new-user signup and the
+/// `link_id`-driven add-inbox flow.
+#[tracing::instrument(skip(ctx, gmail_token), err)]
+async fn enable_gmail_sync_for(
+ ctx: &ApiContext,
+ fusion_user_id: &str,
+ macro_id: MacroUserIdStr<'static>,
+ email_address: &str,
+ gmail_token: &str,
+) -> Result<Link, InitError> {
+ let watch_response = ctx.gmail_client.register_watch(gmail_token).await?;
- let mut link = link::Link {
- id: macro_uuid::generate_uuid_v7(), // will get ignored for existing links
- macro_id: MacroUserIdStr::try_from(user_context.user_id.clone())?,
- fusionauth_user_id: user_context.fusion_user_id.clone(),
- email_address: EmailStr::try_from(email)?,
- provider: models_email::service::link::UserProvider::Gmail,
+ let link = link::Link {
+ id: macro_uuid::generate_uuid_v7(),
+ macro_id,
+ fusionauth_user_id: fusion_user_id.to_string(),
+ email_address: EmailStr::try_from(email_address.to_string())?,
+ provider: link::UserProvider::Gmail,
is_sync_active: true,
created_at: Default::default(),
updated_at: Default::default(),
};
- // either create new link for user or update is_sync_active to true
- link = email_db_client::links::insert::upsert_link(&ctx.db, link)
+ let link = email_db_client::links::insert::upsert_link(&ctx.db, link)
.await
.context("Failed to upsert link")?;
- // either create gmail_histories value or update history_id to current value
email_db_client::histories::upsert_gmail_history(&ctx.db, link.id, &watch_response.history_id)
.await
.context("Failed to upsert gmail history")?;
diff --git a/rust/cloud-storage/email_service/src/api/email/mod.rs b/rust/cloud-storage/email_service/src/api/email/mod.rs
index 33c182cdcb..1f5a7a8f7e 100644
--- a/rust/cloud-storage/email_service/src/api/email/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/mod.rs
@@ -33,11 +33,5 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.layer(axum::middleware::from_fn(
macro_middleware::connection_drop_prevention_handler,
))
- .route(
- "/init",
- post(init::handler).layer(axum::middleware::from_fn_with_state(
- state,
- crate::api::middleware::gmail_token::attach_gmail_token_no_cache,
- )),
- )
+ .route("/init", post(init::handler))
}
diff --git a/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs b/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs
index 596f0ad534..badc158a88 100644
--- a/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs
+++ b/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs
@@ -3,9 +3,7 @@ use axum::{Extension, extract::Request, middleware::Next, response::Response};
use model::user::UserContext;
use crate::api::context::ApiContext;
-use email_service::util::gmail::auth::{
- fetch_gmail_token_no_cache, fetch_gmail_token_usercontext_response,
-};
+use email_service::util::gmail::auth::fetch_gmail_token_usercontext_response;
pub(in crate::api) async fn attach_gmail_token(
State(ctx): State<ApiContext>,
@@ -23,20 +21,3 @@ pub(in crate::api) async fn attach_gmail_token(
req.extensions_mut().insert(gmail_token);
Ok(next.run(req).await)
}
-
-/// Like [`attach_gmail_token`] but always fetches a fresh token from the auth service,
-/// bypassing the Redis cache. Used only by the `/email/init` endpoint.
-#[tracing::instrument(skip(ctx, user_context, req, next))]
-pub(in crate::api) async fn attach_gmail_token_no_cache(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
- mut req: Request,
- next: Next,
-) -> Result<Response, Response> {
- let gmail_token =
- fetch_gmail_token_no_cache(&user_context, &ctx.redis_client, &ctx.auth_service_client)
- .await?;
-
- req.extensions_mut().insert(gmail_token);
- Ok(next.run(req).await)
-}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260527191958_in_progress_user_link_linked_email.sql b/rust/cloud-storage/macro_db_client/migrations/20260527191958_in_progress_user_link_linked_email.sql
new file mode 100644
index 0000000000..9e1f3c5f9b
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260527191958_in_progress_user_link_linked_email.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "in_progress_user_link"
+ ADD COLUMN IF NOT EXISTS "linked_email" TEXT;
diff --git a/rust/cloud-storage/macro_db_client/src/in_progress_user_link.rs b/rust/cloud-storage/macro_db_client/src/in_progress_user_link.rs
index eff95c218a..b28dcac544 100644
--- a/rust/cloud-storage/macro_db_client/src/in_progress_user_link.rs
+++ b/rust/cloud-storage/macro_db_client/src/in_progress_user_link.rs
@@ -1,5 +1,8 @@
use uuid::Uuid;
+#[cfg(test)]
+mod test;
+
pub async fn count_existing_in_progress_user_links_for_user(
db: &sqlx::Pool<sqlx::Postgres>,
macro_user_id: &str,
@@ -108,3 +111,57 @@ pub async fn get_macro_user_id_by_link_id(
Ok(link)
}
+
+pub struct InProgressUserLink {
+ pub macro_user_id: Uuid,
+ pub linked_email: Option<String>,
+}
+
+pub async fn get_in_progress_user_link(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ link_id: &uuid::Uuid,
+) -> anyhow::Result<InProgressUserLink> {
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ macro_user_id,
+ linked_email
+ FROM
+ in_progress_user_link
+ WHERE
+ id = $1
+ "#,
+ link_id
+ )
+ .fetch_one(db)
+ .await?;
+
+ Ok(InProgressUserLink {
+ macro_user_id: row.macro_user_id,
+ linked_email: row.linked_email,
+ })
+}
+
+pub async fn set_linked_email(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ link_id: &uuid::Uuid,
+ linked_email: &str,
+) -> anyhow::Result<()> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE in_progress_user_link
+ SET linked_email = $1
+ WHERE id = $2
+ "#,
+ linked_email,
+ link_id
+ )
+ .execute(db)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ anyhow::bail!("in_progress_user_link not found for link_id={link_id}");
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/macro_db_client/src/in_progress_user_link/test.rs b/rust/cloud-storage/macro_db_client/src/in_progress_user_link/test.rs
new file mode 100644
index 0000000000..84e9bde93f
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/src/in_progress_user_link/test.rs
@@ -0,0 +1,50 @@
+use super::*;
+use sqlx::{Pool, Postgres};
+
+async fn insert_macro_user(pool: &Pool<Postgres>, id: Uuid) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, 'tester', '[email protected]', 'cus_test')
+ "#,
+ &id
+ )
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+#[sqlx::test]
+async fn set_linked_email_then_get(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let macro_user_id = macro_uuid::generate_uuid_v7();
+ insert_macro_user(&pool, macro_user_id).await?;
+
+ let link_id = create_in_progress_user_link(&pool, &macro_user_id.to_string()).await?;
+
+ let pre = get_in_progress_user_link(&pool, &link_id).await?;
+ assert_eq!(pre.macro_user_id, macro_user_id);
+ assert!(pre.linked_email.is_none());
+
+ set_linked_email(&pool, &link_id, "[email protected]").await?;
+
+ let post = get_in_progress_user_link(&pool, &link_id).await?;
+ assert_eq!(post.macro_user_id, macro_user_id);
+ assert_eq!(post.linked_email.as_deref(), Some("[email protected]"));
+
+ Ok(())
+}
+
+#[sqlx::test]
+async fn delete_clears_row(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let macro_user_id = macro_uuid::generate_uuid_v7();
+ insert_macro_user(&pool, macro_user_id).await?;
+
+ let link_id = create_in_progress_user_link(&pool, &macro_user_id.to_string()).await?;
+ set_linked_email(&pool, &link_id, "[email protected]").await?;
+ delete_in_progress_user_link(&pool, &link_id).await?;
+
+ let err = get_in_progress_user_link(&pool, &link_id).await;
+ assert!(err.is_err(), "row should be gone after delete");
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/macro_db_client/src/user/get/mod.rs b/rust/cloud-storage/macro_db_client/src/user/get/mod.rs
index 6dcad83266..55510636aa 100644
--- a/rust/cloud-storage/macro_db_client/src/user/get/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/user/get/mod.rs
@@ -75,6 +75,26 @@ pub async fn get_user_id_by_email(
Ok(user_id)
}
+/// Returns the `macro_user_id` (FusionAuth uuid) tied to a User row by email, if any.
+/// Used to distinguish "this email belongs to the same macro user" from a true cross-user
+/// account merge.
+#[tracing::instrument(skip(db))]
+pub async fn get_macro_user_id_by_email(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ email: &str,
+) -> Result<Option<uuid::Uuid>, sqlx::Error> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT "macro_user_id"
+ FROM "User"
+ WHERE "email" = $1
+ "#,
+ email
+ )
+ .fetch_optional(db)
+ .await
+}
+
/// Gets the user id and stripe customer id for a given email
#[tracing::instrument(skip(db))]
pub async fn get_user_id_and_stripe_customer_id_by_email(
diff --git a/rust/sync-service/Dockerfile b/rust/sync-service/Dockerfile
index 0e666bd6c3..51ba7b5549 100644
--- a/rust/sync-service/Dockerfile
+++ b/rust/sync-service/Dockerfile
@@ -12,9 +12,12 @@ RUN apt-get update && apt-get install -y \
clang \
&& rm -rf /var/lib/apt/lists/*
-# Install wasm32 target and worker-build once
+# Install wasm32 target and worker-build once.
+# Pinned: worker-build 0.8.3 raised its wasm-bindgen floor to 0.2.121, but the
+# locked dep graph here is on wasm-bindgen 0.2.118 (via worker 0.8.1 →
+# serde-wasm-bindgen → js-sys 0.3.95). Stay on 0.8.1 until worker is bumped.
RUN rustup target add wasm32-unknown-unknown && \
- cargo install worker-build@^0.8 --locked
+ cargo install worker-build@=0.8.1 --locked
WORKDIR /app