Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/docs/content/docs/chat/mailer.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
39 changes: 19 additions & 20 deletions apps/sim/app/api/webhooks/agentmail/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<boolean> {
/**
* 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<boolean> {
const [allowedSenderResult, memberResult] = await Promise.all([
db
.select({ id: mothershipInboxAllowedSender.id })
Expand All @@ -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])
Expand Down
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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')}`

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -232,11 +233,6 @@ describe('inbox sender authentication', () => {
`${memberFrom}, Attacker <ceo@attacker.test>`,
{ spf: 'pass' },
],
[
'lists an allow-listed address beside a second mailbox',
`Ops <${allowlistedMemberEmail}>, Attacker <ceo@attacker.test>`,
undefined,
],
])('rejects a message naming a member that %s', async (_case, from, results) => {
const task = await deliver(from, results)

Expand Down Expand Up @@ -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)

Expand All @@ -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',
})
})
})
7 changes: 4 additions & 3 deletions apps/sim/lib/mothership/inbox/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading