From 03309eb378efefd822f2e8a607ea0ea3b493a3c5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 11:57:20 -0800 Subject: [PATCH] fix(inbox): require an authenticated sender before an allow-listed address is admitted --- apps/docs/content/docs/chat/mailer.mdx | 2 +- apps/sim/app/api/webhooks/agentmail/route.ts | 39 ++++++------ .../sender-authentication.integration.ts | 59 +++++++++++++------ apps/sim/lib/mothership/inbox/executor.ts | 7 ++- 4 files changed, 66 insertions(+), 41 deletions(-) diff --git a/apps/docs/content/docs/chat/mailer.mdx b/apps/docs/content/docs/chat/mailer.mdx index b4d73d1505a..085704a55b3 100644 --- a/apps/docs/content/docs/chat/mailer.mdx +++ b/apps/docs/content/docs/chat/mailer.mdx @@ -40,7 +40,7 @@ Manage **Allowed senders** in **Settings** → **Inbox**: An external email sender is different from an external workspace member. The latter has access to Sim according to their workspace role without joining the organization; an email-only sender has no such membership. -Emails from unauthorized senders are rejected. Automated senders, rate limits, or loss of plan entitlement can also prevent a task from being accepted. +Emails from unauthorized senders are rejected. A member or allowed address is only recognized when the message passes SPF, DKIM, or DMARC for that address's domain, so mail from a domain that publishes none of these is rejected. Automated senders, rate limits, or loss of plan entitlement can also prevent a task from being accepted. ## Select secret access diff --git a/apps/sim/app/api/webhooks/agentmail/route.ts b/apps/sim/app/api/webhooks/agentmail/route.ts index 053eb56e570..a0b9d9079fe 100644 --- a/apps/sim/app/api/webhooks/agentmail/route.ts +++ b/apps/sim/app/api/webhooks/agentmail/route.ts @@ -205,7 +205,7 @@ export const POST = withRouteHandler(async (req: Request) => { ) .limit(1) : Promise.resolve([]), - isSenderAllowed(fromEmail, senderAuthenticated, result.id), + senderAuthenticated ? isSenderAllowed(fromEmail, result.id) : false, getRecentTaskCount(result.id), inReplyTo ? db @@ -350,11 +350,12 @@ function organizationalDomain(domain: string): string | null { return getDomain(domain, { allowPrivateDomains: true }) } -async function isSenderAllowed( - email: string, - senderAuthenticated: boolean, - workspaceId: string -): Promise { +/** + * Whether `email` is a workspace member or allow-listed. Only meaningful once + * {@link isSenderAuthenticated} holds: without it, an allowlist entry is as + * forgeable as a member's address. + */ +async function isSenderAllowed(email: string, workspaceId: string): Promise { const [allowedSenderResult, memberResult] = await Promise.all([ db .select({ id: mothershipInboxAllowedSender.id }) @@ -366,20 +367,18 @@ async function isSenderAllowed( ) ) .limit(1), - senderAuthenticated - ? db - .select({ userId: permissions.userId }) - .from(permissions) - .innerJoin(user, eq(permissions.userId, user.id)) - .where( - and( - eq(permissions.entityType, 'workspace'), - eq(permissions.entityId, workspaceId), - sql`lower(${user.email}) = ${email}` - ) - ) - .limit(1) - : [], + db + .select({ userId: permissions.userId }) + .from(permissions) + .innerJoin(user, eq(permissions.userId, user.id)) + .where( + and( + eq(permissions.entityType, 'workspace'), + eq(permissions.entityId, workspaceId), + sql`lower(${user.email}) = ${email}` + ) + ) + .limit(1), ]) return !!(allowedSenderResult[0] || memberResult[0]) diff --git a/apps/sim/app/api/webhooks/agentmail/sender-authentication.integration.ts b/apps/sim/app/api/webhooks/agentmail/sender-authentication.integration.ts index 38534ef4e86..17e4010056f 100644 --- a/apps/sim/app/api/webhooks/agentmail/sender-authentication.integration.ts +++ b/apps/sim/app/api/webhooks/agentmail/sender-authentication.integration.ts @@ -1,9 +1,10 @@ import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' /** * An inbox email's From header is written by whoever sends it. Against real - * PostgreSQL, a message naming a workspace member is only admitted, and only runs - * with that member's authority, when AgentMail's SPF, DKIM, or DMARC verdict proves - * the sender controls the address's domain. The webhook is signed per the Standard + * PostgreSQL, a message naming a workspace member or an allow-listed address is + * admitted only when AgentMail's SPF, DKIM, or DMARC verdict proves the sender + * controls the address's domain, and only an authenticated member's message runs + * with that member's authority. The webhook is signed per the Standard * Webhooks spec, so these cases exercise the authenticated AgentMail relay itself. */ import { authBanMock } from '@sim/testing/mocks/auth-ban.mock' @@ -69,6 +70,8 @@ const memberEmail = `admin@mail.${memberDomain}` const memberFrom = `Admin <${memberEmail}>` const allowlistedMemberId = generateId() const allowlistedMemberEmail = `ops@mail.${memberDomain}` +const partnerDomain = `${generateId()}.test` +const partnerEmail = `partner@${partnerDomain}` const inboxId = `${workspaceId}@agentmail.to` const secret = `whsec_${Buffer.from(generateId()).toString('base64')}` @@ -175,12 +178,10 @@ describe('inbox sender authentication', () => { }) await seedUser(memberId, memberEmail, 'admin') await seedUser(allowlistedMemberId, allowlistedMemberEmail, 'write') - await db.insert(mothershipInboxAllowedSender).values({ - id: generateId(), - workspaceId, - email: allowlistedMemberEmail, - addedBy: ownerId, - }) + await db.insert(mothershipInboxAllowedSender).values([ + { id: generateId(), workspaceId, email: allowlistedMemberEmail, addedBy: ownerId }, + { id: generateId(), workspaceId, email: partnerEmail, addedBy: ownerId }, + ]) await db.insert(mothershipInboxWebhook).values({ id: generateId(), workspaceId, @@ -232,11 +233,6 @@ describe('inbox sender authentication', () => { `${memberFrom}, Attacker `, { spf: 'pass' }, ], - [ - 'lists an allow-listed address beside a second mailbox', - `Ops <${allowlistedMemberEmail}>, Attacker `, - undefined, - ], ])('rejects a message naming a member that %s', async (_case, from, results) => { const task = await deliver(from, results) @@ -268,9 +264,16 @@ describe('inbox sender authentication', () => { }) }) - it('runs an unauthenticated allow-listed address as an external sender, even when a member owns it', async () => { - const task = await deliver(`Ops <${allowlistedMemberEmail}>`) - expect(task).toMatchObject({ status: 'received', senderAuthenticated: false }) + it('rejects an unauthenticated allow-listed sender', async () => { + const task = await deliver(`Partner <${partnerEmail}>`) + + expect(task).toMatchObject({ status: 'rejected', rejectionReason: 'sender_not_allowed' }) + expect(mockExecuteInboxTask).not.toHaveBeenCalled() + }) + + it('runs an authenticated allow-listed external address as an external sender', async () => { + const task = await deliver(`Partner <${partnerEmail}>`, { dmarc: 'pass' }) + expect(task).toMatchObject({ status: 'received', senderAuthenticated: true }) await executeInboxTask(task.id) @@ -281,4 +284,26 @@ describe('inbox sender authentication', () => { userPermission: 'read', }) }) + + it('never runs an unauthenticated task as the member its From names', async () => { + const taskId = generateId() + await db.insert(mothershipInboxTask).values({ + id: taskId, + workspaceId, + fromEmail: memberEmail, + senderAuthenticated: false, + subject: 'Queued without a verdict', + bodyText: 'Run a workflow.', + status: 'received', + }) + + await executeInboxTask(taskId) + + const [, options] = mockRunHeadlessCopilotLifecycle.mock.calls[0] + expect(options).toMatchObject({ + userId: ownerId, + secretActorUserId: null, + userPermission: 'read', + }) + }) }) diff --git a/apps/sim/lib/mothership/inbox/executor.ts b/apps/sim/lib/mothership/inbox/executor.ts index d928bafe168..5f8fe6a87c8 100644 --- a/apps/sim/lib/mothership/inbox/executor.ts +++ b/apps/sim/lib/mothership/inbox/executor.ts @@ -385,9 +385,10 @@ async function resolveWorkspaceChatId( /** * Resolve the execution and raw-secret actors independently. Workspace members * whose address the provider authenticated execute and mount secrets as - * themselves; an unauthenticated message naming a member is external. External - * senders retain the existing owner execution fallback but receive no raw-secret - * actor. + * themselves; any other admitted sender is external. The webhook already rejects + * unauthenticated senders, so the verdict check here is defense in depth: a task + * without it never runs as the member its From names. External senders retain + * the existing owner execution fallback but receive no raw-secret actor. * * The owner fallback exists because billing attribution and workspace reads need * a real user, not because an unknown sender should act as the owner. A null