Skip to content

Commit 03309eb

Browse files
committed
fix(inbox): require an authenticated sender before an allow-listed address is admitted
1 parent 507953c commit 03309eb

4 files changed

Lines changed: 66 additions & 41 deletions

File tree

‎apps/docs/content/docs/chat/mailer.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Manage **Allowed senders** in **Settings** → **Inbox**:
4040

4141
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.
4242

43-
Emails from unauthorized senders are rejected. Automated senders, rate limits, or loss of plan entitlement can also prevent a task from being accepted.
43+
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.
4444

4545
## Select secret access
4646

‎apps/sim/app/api/webhooks/agentmail/route.ts‎

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ export const POST = withRouteHandler(async (req: Request) => {
205205
)
206206
.limit(1)
207207
: Promise.resolve([]),
208-
isSenderAllowed(fromEmail, senderAuthenticated, result.id),
208+
senderAuthenticated ? isSenderAllowed(fromEmail, result.id) : false,
209209
getRecentTaskCount(result.id),
210210
inReplyTo
211211
? db
@@ -350,11 +350,12 @@ function organizationalDomain(domain: string): string | null {
350350
return getDomain(domain, { allowPrivateDomains: true })
351351
}
352352

353-
async function isSenderAllowed(
354-
email: string,
355-
senderAuthenticated: boolean,
356-
workspaceId: string
357-
): Promise<boolean> {
353+
/**
354+
* Whether `email` is a workspace member or allow-listed. Only meaningful once
355+
* {@link isSenderAuthenticated} holds: without it, an allowlist entry is as
356+
* forgeable as a member's address.
357+
*/
358+
async function isSenderAllowed(email: string, workspaceId: string): Promise<boolean> {
358359
const [allowedSenderResult, memberResult] = await Promise.all([
359360
db
360361
.select({ id: mothershipInboxAllowedSender.id })
@@ -366,20 +367,18 @@ async function isSenderAllowed(
366367
)
367368
)
368369
.limit(1),
369-
senderAuthenticated
370-
? db
371-
.select({ userId: permissions.userId })
372-
.from(permissions)
373-
.innerJoin(user, eq(permissions.userId, user.id))
374-
.where(
375-
and(
376-
eq(permissions.entityType, 'workspace'),
377-
eq(permissions.entityId, workspaceId),
378-
sql`lower(${user.email}) = ${email}`
379-
)
380-
)
381-
.limit(1)
382-
: [],
370+
db
371+
.select({ userId: permissions.userId })
372+
.from(permissions)
373+
.innerJoin(user, eq(permissions.userId, user.id))
374+
.where(
375+
and(
376+
eq(permissions.entityType, 'workspace'),
377+
eq(permissions.entityId, workspaceId),
378+
sql`lower(${user.email}) = ${email}`
379+
)
380+
)
381+
.limit(1),
383382
])
384383

385384
return !!(allowedSenderResult[0] || memberResult[0])

‎apps/sim/app/api/webhooks/agentmail/sender-authentication.integration.ts‎

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
22
/**
33
* An inbox email's From header is written by whoever sends it. Against real
4-
* PostgreSQL, a message naming a workspace member is only admitted, and only runs
5-
* with that member's authority, when AgentMail's SPF, DKIM, or DMARC verdict proves
6-
* the sender controls the address's domain. The webhook is signed per the Standard
4+
* PostgreSQL, a message naming a workspace member or an allow-listed address is
5+
* admitted only when AgentMail's SPF, DKIM, or DMARC verdict proves the sender
6+
* controls the address's domain, and only an authenticated member's message runs
7+
* with that member's authority. The webhook is signed per the Standard
78
* Webhooks spec, so these cases exercise the authenticated AgentMail relay itself.
89
*/
910
import { authBanMock } from '@sim/testing/mocks/auth-ban.mock'
@@ -69,6 +70,8 @@ const memberEmail = `admin@mail.${memberDomain}`
6970
const memberFrom = `Admin <${memberEmail}>`
7071
const allowlistedMemberId = generateId()
7172
const allowlistedMemberEmail = `ops@mail.${memberDomain}`
73+
const partnerDomain = `${generateId()}.test`
74+
const partnerEmail = `partner@${partnerDomain}`
7275
const inboxId = `${workspaceId}@agentmail.to`
7376
const secret = `whsec_${Buffer.from(generateId()).toString('base64')}`
7477

@@ -175,12 +178,10 @@ describe('inbox sender authentication', () => {
175178
})
176179
await seedUser(memberId, memberEmail, 'admin')
177180
await seedUser(allowlistedMemberId, allowlistedMemberEmail, 'write')
178-
await db.insert(mothershipInboxAllowedSender).values({
179-
id: generateId(),
180-
workspaceId,
181-
email: allowlistedMemberEmail,
182-
addedBy: ownerId,
183-
})
181+
await db.insert(mothershipInboxAllowedSender).values([
182+
{ id: generateId(), workspaceId, email: allowlistedMemberEmail, addedBy: ownerId },
183+
{ id: generateId(), workspaceId, email: partnerEmail, addedBy: ownerId },
184+
])
184185
await db.insert(mothershipInboxWebhook).values({
185186
id: generateId(),
186187
workspaceId,
@@ -232,11 +233,6 @@ describe('inbox sender authentication', () => {
232233
`${memberFrom}, Attacker <ceo@attacker.test>`,
233234
{ spf: 'pass' },
234235
],
235-
[
236-
'lists an allow-listed address beside a second mailbox',
237-
`Ops <${allowlistedMemberEmail}>, Attacker <ceo@attacker.test>`,
238-
undefined,
239-
],
240236
])('rejects a message naming a member that %s', async (_case, from, results) => {
241237
const task = await deliver(from, results)
242238

@@ -268,9 +264,16 @@ describe('inbox sender authentication', () => {
268264
})
269265
})
270266

271-
it('runs an unauthenticated allow-listed address as an external sender, even when a member owns it', async () => {
272-
const task = await deliver(`Ops <${allowlistedMemberEmail}>`)
273-
expect(task).toMatchObject({ status: 'received', senderAuthenticated: false })
267+
it('rejects an unauthenticated allow-listed sender', async () => {
268+
const task = await deliver(`Partner <${partnerEmail}>`)
269+
270+
expect(task).toMatchObject({ status: 'rejected', rejectionReason: 'sender_not_allowed' })
271+
expect(mockExecuteInboxTask).not.toHaveBeenCalled()
272+
})
273+
274+
it('runs an authenticated allow-listed external address as an external sender', async () => {
275+
const task = await deliver(`Partner <${partnerEmail}>`, { dmarc: 'pass' })
276+
expect(task).toMatchObject({ status: 'received', senderAuthenticated: true })
274277

275278
await executeInboxTask(task.id)
276279

@@ -281,4 +284,26 @@ describe('inbox sender authentication', () => {
281284
userPermission: 'read',
282285
})
283286
})
287+
288+
it('never runs an unauthenticated task as the member its From names', async () => {
289+
const taskId = generateId()
290+
await db.insert(mothershipInboxTask).values({
291+
id: taskId,
292+
workspaceId,
293+
fromEmail: memberEmail,
294+
senderAuthenticated: false,
295+
subject: 'Queued without a verdict',
296+
bodyText: 'Run a workflow.',
297+
status: 'received',
298+
})
299+
300+
await executeInboxTask(taskId)
301+
302+
const [, options] = mockRunHeadlessCopilotLifecycle.mock.calls[0]
303+
expect(options).toMatchObject({
304+
userId: ownerId,
305+
secretActorUserId: null,
306+
userPermission: 'read',
307+
})
308+
})
284309
})

‎apps/sim/lib/mothership/inbox/executor.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -385,9 +385,10 @@ async function resolveWorkspaceChatId(
385385
/**
386386
* Resolve the execution and raw-secret actors independently. Workspace members
387387
* whose address the provider authenticated execute and mount secrets as
388-
* themselves; an unauthenticated message naming a member is external. External
389-
* senders retain the existing owner execution fallback but receive no raw-secret
390-
* actor.
388+
* themselves; any other admitted sender is external. The webhook already rejects
389+
* unauthenticated senders, so the verdict check here is defense in depth: a task
390+
* without it never runs as the member its From names. External senders retain
391+
* the existing owner execution fallback but receive no raw-secret actor.
391392
*
392393
* The owner fallback exists because billing attribution and workspace reads need
393394
* a real user, not because an unknown sender should act as the owner. A null

0 commit comments

Comments
 (0)