fix(security): SSRF, access control, and info disclosure (#3815)

* fix(security): scope copilot feedback GET endpoint to authenticated user

Add WHERE clause to filter feedback records by the authenticated user's
ID, preventing any authenticated user from reading all users' copilot
interactions, queries, and workflow YAML (IDOR / CWE-639).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(smtp): add SSRF validation and genericize network error messages

Prevent SSRF via user-controlled smtpHost by validating with
validateDatabaseHost before creating the nodemailer transporter.
Collapse distinct network error messages (ECONNREFUSED, ECONNRESET,
ETIMEDOUT) into a single generic message to prevent port-state leakage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(security): add SSRF validation to SFTP/SSH and access control to workspace invitations

Add `validateDatabaseHost` checks to SFTP and SSH connection utilities to
block connections to private/reserved IPs and localhost, matching the
existing pattern used by all database tools. Add authorization check to
the workspace invitation GET endpoint so only the invitee or a workspace
admin can view invitation details.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(smtp): restore SMTP response code handling for post-connection errors

SMTP 4xx/5xx response codes are application-level errors (invalid
recipient, mailbox full, server error) unrelated to the SSRF hardening
goal. Restore response code differentiation and logging to preserve
actionable user-facing error messages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(security): use session email directly instead of extra DB query

Addresses PR review feedback — align with the workspace invitation
route pattern by using session.user.email instead of re-fetching
from the database.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* lint

* fix(auth): revert lint autofix that broke hasExternalApiCredentials return type

Biome auto-fixed `return auth !== null && auth.startsWith(...)` to
`return auth?.startsWith(...)` which returns `boolean | undefined`,
not `boolean`, causing a TypeScript build failure.

* fix(smtp): pin resolved IP to prevent DNS rebinding (TOCTOU)

Use the pre-resolved IP from validateDatabaseHost instead of the
original hostname when creating the nodemailer transporter. Set
servername to the original hostname to preserve TLS SNI validation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(security): extract createPinnedLookup helper for DNS rebinding prevention

Extract reusable createPinnedLookup from secureFetchWithPinnedIP so
non-HTTP transports (SSH, SFTP, IMAP) can pin resolved IPs at the
socket level. SMTP route uses host+servername pinning instead since
nodemailer doesn't reliably pass lookup to both secure/plaintext paths.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(security): pin IMAP connections to validated resolved IP

Pass the resolved IP from validateDatabaseHost to ImapFlow as host,
with the original hostname as servername for TLS SNI verification.
Closes the DNS TOCTOU rebinding window.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* lint

* fix(auth): revert lint autofix on hasExternalApiCredentials return type

Also pin SFTP/SSH connections to validated resolved IP to prevent DNS rebinding.

* fix(security): short-circuit admin check when caller is invitee

Skip the hasWorkspaceAdminAccess DB query when the caller is already
the invitee, avoiding an unnecessary round-trip. Aligns with the org
invitation route pattern.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Waleed
2026-03-27 18:10:47 -07:00
committed by GitHub
parent a7c1e510e6
commit c05e2e0fc8
18 changed files with 229 additions and 105 deletions

View File

@@ -12,6 +12,7 @@ const {
mockReturning,
mockSelect,
mockFrom,
mockWhere,
mockAuthenticate,
mockCreateUnauthorizedResponse,
mockCreateBadRequestResponse,
@@ -23,6 +24,7 @@ const {
mockReturning: vi.fn(),
mockSelect: vi.fn(),
mockFrom: vi.fn(),
mockWhere: vi.fn(),
mockAuthenticate: vi.fn(),
mockCreateUnauthorizedResponse: vi.fn(),
mockCreateBadRequestResponse: vi.fn(),
@@ -81,7 +83,8 @@ describe('Copilot Feedback API Route', () => {
mockValues.mockReturnValue({ returning: mockReturning })
mockReturning.mockResolvedValue([])
mockSelect.mockReturnValue({ from: mockFrom })
mockFrom.mockResolvedValue([])
mockFrom.mockReturnValue({ where: mockWhere })
mockWhere.mockResolvedValue([])
mockCreateRequestTracker.mockReturnValue({
requestId: 'test-request-id',
@@ -386,7 +389,7 @@ edges:
isAuthenticated: true,
})
mockFrom.mockResolvedValueOnce([])
mockWhere.mockResolvedValueOnce([])
const request = new Request('http://localhost:3000/api/copilot/feedback')
const response = await GET(request as any)
@@ -397,7 +400,7 @@ edges:
expect(responseData.feedback).toEqual([])
})
it('should return all feedback records', async () => {
it('should only return feedback records for the authenticated user', async () => {
mockAuthenticate.mockResolvedValueOnce({
userId: 'user-123',
isAuthenticated: true,
@@ -415,19 +418,8 @@ edges:
workflowYaml: null,
createdAt: new Date('2024-01-01'),
},
{
feedbackId: 'feedback-2',
userId: 'user-456',
chatId: 'chat-2',
userQuery: 'Query 2',
agentResponse: 'Response 2',
isPositive: false,
feedback: 'Not helpful',
workflowYaml: 'yaml: content',
createdAt: new Date('2024-01-02'),
},
]
mockFrom.mockResolvedValueOnce(mockFeedback)
mockWhere.mockResolvedValueOnce(mockFeedback)
const request = new Request('http://localhost:3000/api/copilot/feedback')
const response = await GET(request as any)
@@ -435,9 +427,14 @@ edges:
expect(response.status).toBe(200)
const responseData = await response.json()
expect(responseData.success).toBe(true)
expect(responseData.feedback).toHaveLength(2)
expect(responseData.feedback).toHaveLength(1)
expect(responseData.feedback[0].feedbackId).toBe('feedback-1')
expect(responseData.feedback[1].feedbackId).toBe('feedback-2')
expect(responseData.feedback[0].userId).toBe('user-123')
// Verify the where clause was called with the authenticated user's ID
const { eq } = await import('drizzle-orm')
expect(mockWhere).toHaveBeenCalled()
expect(eq).toHaveBeenCalledWith('userId', 'user-123')
})
it('should handle database errors gracefully', async () => {
@@ -446,7 +443,7 @@ edges:
isAuthenticated: true,
})
mockFrom.mockRejectedValueOnce(new Error('Database connection failed'))
mockWhere.mockRejectedValueOnce(new Error('Database connection failed'))
const request = new Request('http://localhost:3000/api/copilot/feedback')
const response = await GET(request as any)
@@ -462,7 +459,7 @@ edges:
isAuthenticated: true,
})
mockFrom.mockResolvedValueOnce([])
mockWhere.mockResolvedValueOnce([])
const request = new Request('http://localhost:3000/api/copilot/feedback')
const response = await GET(request as any)

View File

@@ -1,6 +1,7 @@
import { db } from '@sim/db'
import { copilotFeedback } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import {
@@ -109,7 +110,7 @@ export async function POST(req: NextRequest) {
/**
* GET /api/copilot/feedback
* Get all feedback records (for analytics)
* Get feedback records for the authenticated user
*/
export async function GET(req: NextRequest) {
const tracker = createRequestTracker()
@@ -123,7 +124,7 @@ export async function GET(req: NextRequest) {
return createUnauthorizedResponse()
}
// Get all feedback records
// Get feedback records for the authenticated user only
const feedbackRecords = await db
.select({
feedbackId: copilotFeedback.feedbackId,
@@ -137,6 +138,7 @@ export async function GET(req: NextRequest) {
createdAt: copilotFeedback.createdAt,
})
.from(copilotFeedback)
.where(eq(copilotFeedback.userId, authenticatedUserId))
logger.info(`[${tracker.requestId}] Retrieved ${feedbackRecords.length} feedback records`)

View File

@@ -1,6 +1,10 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import {
authenticateCopilotRequestSessionOnly,
createUnauthorizedResponse,
} from '@/lib/copilot/request-helpers'
import { env } from '@/lib/core/config/env'
const logger = createLogger('CopilotTrainingExamplesAPI')
@@ -16,6 +20,11 @@ const TrainingExampleSchema = z.object({
})
export async function POST(request: NextRequest) {
const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly()
if (!isAuthenticated || !userId) {
return createUnauthorizedResponse()
}
const baseUrl = env.AGENT_INDEXER_URL
if (!baseUrl) {
logger.error('Missing AGENT_INDEXER_URL environment variable')

View File

@@ -1,6 +1,10 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import {
authenticateCopilotRequestSessionOnly,
createUnauthorizedResponse,
} from '@/lib/copilot/request-helpers'
import { env } from '@/lib/core/config/env'
const logger = createLogger('CopilotTrainingAPI')
@@ -22,6 +26,11 @@ const TrainingDataSchema = z.object({
})
export async function POST(request: NextRequest) {
const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly()
if (!isAuthenticated || !userId) {
return createUnauthorizedResponse()
}
try {
const baseUrl = env.AGENT_INDEXER_URL
if (!baseUrl) {

View File

@@ -61,6 +61,21 @@ export async function GET(
return NextResponse.json({ error: 'Invitation not found' }, { status: 404 })
}
// Verify caller is either an org member or the invitee
const isInvitee = session.user.email?.toLowerCase() === orgInvitation.email.toLowerCase()
if (!isInvitee) {
const memberEntry = await db
.select()
.from(member)
.where(and(eq(member.organizationId, organizationId), eq(member.userId, session.user.id)))
.limit(1)
if (memberEntry.length === 0) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
}
const org = await db
.select()
.from(organization)

View File

@@ -2,6 +2,7 @@ import { createLogger } from '@sim/logger'
import { ImapFlow } from 'imapflow'
import { type NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { validateDatabaseHost } from '@/lib/core/security/input-validation.server'
const logger = createLogger('ImapMailboxesAPI')
@@ -9,7 +10,6 @@ interface ImapMailboxRequest {
host: string
port: number
secure: boolean
rejectUnauthorized: boolean
username: string
password: string
}
@@ -22,7 +22,7 @@ export async function POST(request: NextRequest) {
try {
const body = (await request.json()) as ImapMailboxRequest
const { host, port, secure, rejectUnauthorized, username, password } = body
const { host, port, secure, username, password } = body
if (!host || !username || !password) {
return NextResponse.json(
@@ -31,8 +31,14 @@ export async function POST(request: NextRequest) {
)
}
const hostValidation = await validateDatabaseHost(host, 'host')
if (!hostValidation.isValid) {
return NextResponse.json({ success: false, message: hostValidation.error }, { status: 400 })
}
const client = new ImapFlow({
host,
host: hostValidation.resolvedIP!,
servername: host,
port: port || 993,
secure: secure ?? true,
auth: {
@@ -40,7 +46,7 @@ export async function POST(request: NextRequest) {
pass: password,
},
tls: {
rejectUnauthorized: rejectUnauthorized ?? true,
rejectUnauthorized: true,
},
logger: false,
})
@@ -79,21 +85,12 @@ export async function POST(request: NextRequest) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
logger.error('Error fetching IMAP mailboxes:', errorMessage)
let userMessage = 'Failed to connect to IMAP server'
let userMessage = 'Failed to connect to IMAP server. Please check your connection settings.'
if (
errorMessage.includes('AUTHENTICATIONFAILED') ||
errorMessage.includes('Invalid credentials')
) {
userMessage = 'Invalid username or password. For Gmail, use an App Password.'
} else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('getaddrinfo')) {
userMessage = 'Could not find IMAP server. Please check the hostname.'
} else if (errorMessage.includes('ECONNREFUSED')) {
userMessage = 'Connection refused. Please check the port and SSL settings.'
} else if (errorMessage.includes('certificate') || errorMessage.includes('SSL')) {
userMessage =
'TLS/SSL error. Try disabling "Verify TLS Certificate" for self-signed certificates.'
} else if (errorMessage.includes('timeout')) {
userMessage = 'Connection timed out. Please check your network and server settings.'
}
return NextResponse.json({ success: false, message: userMessage }, { status: 500 })

View File

@@ -1,4 +1,5 @@
import { type Attributes, Client, type ConnectConfig, type SFTPWrapper } from 'ssh2'
import { validateDatabaseHost } from '@/lib/core/security/input-validation.server'
const S_IFMT = 0o170000
const S_IFDIR = 0o040000
@@ -91,16 +92,23 @@ function formatSftpError(err: Error, config: { host: string; port: number }): Er
* Creates an SSH connection for SFTP using the provided configuration.
* Uses ssh2 library defaults which align with OpenSSH standards.
*/
export function createSftpConnection(config: SftpConnectionConfig): Promise<Client> {
export async function createSftpConnection(config: SftpConnectionConfig): Promise<Client> {
const host = config.host
if (!host || host.trim() === '') {
throw new Error('Host is required. Please provide a valid hostname or IP address.')
}
const hostValidation = await validateDatabaseHost(host, 'host')
if (!hostValidation.isValid) {
throw new Error(hostValidation.error)
}
const resolvedHost = hostValidation.resolvedIP ?? host.trim()
return new Promise((resolve, reject) => {
const client = new Client()
const port = config.port || 22
const host = config.host
if (!host || host.trim() === '') {
reject(new Error('Host is required. Please provide a valid hostname or IP address.'))
return
}
const hasPassword = config.password && config.password.trim() !== ''
const hasPrivateKey = config.privateKey && config.privateKey.trim() !== ''
@@ -111,7 +119,7 @@ export function createSftpConnection(config: SftpConnectionConfig): Promise<Clie
}
const connectConfig: ConnectConfig = {
host: host.trim(),
host: resolvedHost,
port,
username: config.username,
}

View File

@@ -3,6 +3,7 @@ import { type NextRequest, NextResponse } from 'next/server'
import nodemailer from 'nodemailer'
import { z } from 'zod'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { validateDatabaseHost } from '@/lib/core/security/input-validation.server'
import { generateRequestId } from '@/lib/core/utils/request'
import { RawFileInputArraySchema } from '@/lib/uploads/utils/file-schemas'
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
@@ -56,6 +57,15 @@ export async function POST(request: NextRequest) {
const body = await request.json()
const validatedData = SmtpSendSchema.parse(body)
const hostValidation = await validateDatabaseHost(validatedData.smtpHost, 'smtpHost')
if (!hostValidation.isValid) {
logger.warn(`[${requestId}] SMTP host validation failed`, {
host: validatedData.smtpHost,
error: hostValidation.error,
})
return NextResponse.json({ success: false, error: hostValidation.error }, { status: 400 })
}
logger.info(`[${requestId}] Sending email via SMTP`, {
host: validatedData.smtpHost,
port: validatedData.smtpPort,
@@ -64,8 +74,13 @@ export async function POST(request: NextRequest) {
secure: validatedData.smtpSecure,
})
// Pin the pre-resolved IP to prevent DNS rebinding (TOCTOU) attacks.
// Pass resolvedIP as the host so nodemailer connects to the validated address,
// and set servername for correct TLS SNI/certificate validation.
const pinnedHost = hostValidation.resolvedIP ?? validatedData.smtpHost
const transporter = nodemailer.createTransport({
host: validatedData.smtpHost,
host: pinnedHost,
port: validatedData.smtpPort,
secure: validatedData.smtpSecure === 'SSL',
auth: {
@@ -74,12 +89,8 @@ export async function POST(request: NextRequest) {
},
tls:
validatedData.smtpSecure === 'None'
? {
rejectUnauthorized: false,
}
: {
rejectUnauthorized: true,
},
? { rejectUnauthorized: false, servername: validatedData.smtpHost }
: { rejectUnauthorized: true, servername: validatedData.smtpHost },
})
const contentType = validatedData.contentType || 'text'
@@ -189,16 +200,16 @@ export async function POST(request: NextRequest) {
if (isNodeError(error)) {
if (error.code === 'EAUTH') {
errorMessage = 'SMTP authentication failed - check username and password'
} else if (error.code === 'ECONNECTION' || error.code === 'ECONNREFUSED') {
} else if (
error.code === 'ECONNECTION' ||
error.code === 'ECONNREFUSED' ||
error.code === 'ECONNRESET' ||
error.code === 'ETIMEDOUT'
) {
errorMessage = 'Could not connect to SMTP server - check host and port'
} else if (error.code === 'ECONNRESET') {
errorMessage = 'Connection was reset by SMTP server'
} else if (error.code === 'ETIMEDOUT') {
errorMessage = 'SMTP server connection timeout'
}
}
// Check for SMTP response codes
const hasResponseCode = (err: unknown): err is { responseCode: number } => {
return typeof err === 'object' && err !== null && 'responseCode' in err
}

View File

@@ -1,5 +1,6 @@
import { createLogger } from '@sim/logger'
import { type Attributes, Client, type ConnectConfig } from 'ssh2'
import { validateDatabaseHost } from '@/lib/core/security/input-validation.server'
const logger = createLogger('SSHUtils')
@@ -108,16 +109,23 @@ function formatSSHError(err: Error, config: { host: string; port: number }): Err
* - keepaliveInterval: 0 (disabled, same as OpenSSH ServerAliveInterval)
* - keepaliveCountMax: 3 (same as OpenSSH ServerAliveCountMax)
*/
export function createSSHConnection(config: SSHConnectionConfig): Promise<Client> {
export async function createSSHConnection(config: SSHConnectionConfig): Promise<Client> {
const host = config.host
if (!host || host.trim() === '') {
throw new Error('Host is required. Please provide a valid hostname or IP address.')
}
const hostValidation = await validateDatabaseHost(host, 'host')
if (!hostValidation.isValid) {
throw new Error(hostValidation.error)
}
const resolvedHost = hostValidation.resolvedIP ?? host.trim()
return new Promise((resolve, reject) => {
const client = new Client()
const port = config.port || 22
const host = config.host
if (!host || host.trim() === '') {
reject(new Error('Host is required. Please provide a valid hostname or IP address.'))
return
}
const hasPassword = config.password && config.password.trim() !== ''
const hasPrivateKey = config.privateKey && config.privateKey.trim() !== ''
@@ -128,7 +136,7 @@ export function createSSHConnection(config: SSHConnectionConfig): Promise<Client
}
const connectConfig: ConnectConfig = {
host: host.trim(),
host: resolvedHost,
port,
username: config.username,
}

View File

@@ -6,7 +6,6 @@ import {
updateApiKeyLastUsed,
} from '@/lib/api-key/service'
import { type AuthResult, checkHybridAuth } from '@/lib/auth/hybrid'
import { env } from '@/lib/core/config/env'
import { authorizeWorkflowByWorkspacePermission, getWorkflowById } from '@/lib/workflows/utils'
const logger = createLogger('WorkflowMiddleware')
@@ -81,11 +80,6 @@ export async function validateWorkflowAccess(
}
}
const internalSecret = request.headers.get('X-Internal-Secret')
if (env.INTERNAL_API_SECRET && internalSecret === env.INTERNAL_API_SECRET) {
return { workflow }
}
let apiKeyHeader = null
for (const [key, value] of request.headers.entries()) {
if (key.toLowerCase() === 'x-api-key' && value) {

View File

@@ -79,6 +79,22 @@ vi.mock('@/lib/core/utils/urls', () => ({
getBaseUrl: vi.fn().mockReturnValue('https://test.sim.ai'),
}))
vi.mock('@/components/emails', () => ({
WorkspaceInvitationEmail: vi.fn().mockReturnValue(null),
}))
vi.mock('@/lib/messaging/email/mailer', () => ({
sendEmail: vi.fn().mockResolvedValue({ success: true }),
}))
vi.mock('@/lib/messaging/email/utils', () => ({
getFromEmailAddress: vi.fn().mockReturnValue('noreply@test.com'),
}))
vi.mock('@react-email/render', () => ({
render: vi.fn().mockResolvedValue('<html></html>'),
}))
vi.mock('@sim/db', () => ({
db: {
select: () => mockDbSelect(),
@@ -171,9 +187,10 @@ describe('Workspace Invitation [invitationId] API Route', () => {
})
describe('GET /api/workspaces/invitations/[invitationId]', () => {
it('should return invitation details when called without token', async () => {
const session = createSession({ userId: mockUser.id, email: mockUser.email })
it('should return invitation details when caller is the invitee', async () => {
const session = createSession({ userId: mockUser.id, email: 'invited@example.com' })
mockGetSession.mockResolvedValue(session)
mockHasWorkspaceAdminAccess.mockResolvedValue(false)
dbSelectResults = [[mockInvitation], [mockWorkspace]]
const request = new NextRequest('http://localhost/api/workspaces/invitations/invitation-789')
@@ -191,6 +208,43 @@ describe('Workspace Invitation [invitationId] API Route', () => {
})
})
it('should return invitation details when caller is a workspace admin', async () => {
const session = createSession({ userId: mockUser.id, email: mockUser.email })
mockGetSession.mockResolvedValue(session)
mockHasWorkspaceAdminAccess.mockResolvedValue(true)
dbSelectResults = [[mockInvitation], [mockWorkspace]]
const request = new NextRequest('http://localhost/api/workspaces/invitations/invitation-789')
const params = Promise.resolve({ invitationId: 'invitation-789' })
const response = await GET(request, { params })
const data = await response.json()
expect(response.status).toBe(200)
expect(data).toMatchObject({
id: 'invitation-789',
email: 'invited@example.com',
status: 'pending',
workspaceName: 'Test Workspace',
})
})
it('should return 403 when caller is neither invitee nor workspace admin', async () => {
const session = createSession({ userId: mockUser.id, email: 'unrelated@example.com' })
mockGetSession.mockResolvedValue(session)
mockHasWorkspaceAdminAccess.mockResolvedValue(false)
dbSelectResults = [[mockInvitation], [mockWorkspace]]
const request = new NextRequest('http://localhost/api/workspaces/invitations/invitation-789')
const params = Promise.resolve({ invitationId: 'invitation-789' })
const response = await GET(request, { params })
const data = await response.json()
expect(response.status).toBe(403)
expect(data).toEqual({ error: 'Insufficient permissions' })
})
it('should redirect to login when unauthenticated with token', async () => {
mockGetSession.mockResolvedValue(null)

View File

@@ -198,6 +198,15 @@ export async function GET(
)
}
const isInvitee = session.user.email?.toLowerCase() === invitation.email.toLowerCase()
if (!isInvitee) {
const hasAdminAccess = await hasWorkspaceAdminAccess(session.user.id, invitation.workspaceId)
if (!hasAdminAccess) {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 })
}
}
return NextResponse.json({
...invitation,
workspaceName: workspaceDetails.name,

View File

@@ -28,7 +28,6 @@ export const ImapBlock: BlockConfig = {
host: { type: 'string', description: 'IMAP server hostname' },
port: { type: 'string', description: 'IMAP server port' },
secure: { type: 'boolean', description: 'Use SSL/TLS encryption' },
rejectUnauthorized: { type: 'boolean', description: 'Verify TLS certificate' },
username: { type: 'string', description: 'Email username' },
password: { type: 'string', description: 'Email password' },
mailbox: { type: 'string', description: 'Mailbox to monitor' },

View File

@@ -243,6 +243,24 @@ function resolveRedirectUrl(baseUrl: string, location: string): string {
}
}
/**
* Creates a DNS lookup function that always returns a pre-resolved IP address.
* Use this to prevent DNS rebinding (TOCTOU) attacks when connecting to
* user-controlled hostnames via non-HTTP protocols (SMTP, SSH, IMAP, etc.).
*/
export function createPinnedLookup(resolvedIP: string): LookupFunction {
const isIPv6 = resolvedIP.includes(':')
const family = isIPv6 ? 6 : 4
return (_hostname, options, callback) => {
if (options.all) {
callback(null, [{ address: resolvedIP, family }])
} else {
callback(null, resolvedIP, family)
}
}
}
/**
* Performs a fetch with IP pinning to prevent DNS rebinding attacks.
* Uses the pre-resolved IP address while preserving the original hostname for TLS SNI.
@@ -263,16 +281,7 @@ export async function secureFetchWithPinnedIP(
const defaultPort = isHttps ? 443 : 80
const port = parsed.port ? Number.parseInt(parsed.port, 10) : defaultPort
const isIPv6 = resolvedIP.includes(':')
const family = isIPv6 ? 6 : 4
const lookup: LookupFunction = (_hostname, options, callback) => {
if (options.all) {
callback(null, [{ address: resolvedIP, family }])
} else {
callback(null, resolvedIP, family)
}
}
const lookup = createPinnedLookup(resolvedIP)
const agentOptions: http.AgentOptions = { lookup }

View File

@@ -7,6 +7,7 @@ import type { FetchMessageObject, MailboxLockObject } from 'imapflow'
import { ImapFlow } from 'imapflow'
import { nanoid } from 'nanoid'
import { pollingIdempotency } from '@/lib/core/idempotency/service'
import { validateDatabaseHost } from '@/lib/core/security/input-validation.server'
import { getInternalApiBaseUrl } from '@/lib/core/utils/urls'
import { MAX_CONSECUTIVE_FAILURES } from '@/triggers/constants'
@@ -18,7 +19,6 @@ interface ImapWebhookConfig {
host: string
port: number
secure: boolean
rejectUnauthorized: boolean
username: string
password: string
mailbox: string | string[] // Can be single mailbox or array of mailboxes
@@ -172,7 +172,17 @@ export async function pollImapWebhooks() {
return
}
const fetchResult = await fetchNewEmails(config, requestId)
const hostValidation = await validateDatabaseHost(config.host, 'host')
if (!hostValidation.isValid) {
logger.error(
`[${requestId}] IMAP host validation failed for webhook ${webhookId}: ${hostValidation.error}`
)
await markWebhookFailed(webhookId)
failureCount++
return
}
const fetchResult = await fetchNewEmails(config, requestId, hostValidation.resolvedIP!)
const { emails, latestUidByMailbox } = fetchResult
const pollTimestamp = new Date().toISOString()
@@ -190,7 +200,8 @@ export async function pollImapWebhooks() {
emails,
webhookData,
config,
requestId
requestId,
hostValidation.resolvedIP!
)
await updateWebhookLastProcessedUids(webhookId, latestUidByMailbox, pollTimestamp)
@@ -257,9 +268,10 @@ export async function pollImapWebhooks() {
}
}
async function fetchNewEmails(config: ImapWebhookConfig, requestId: string) {
async function fetchNewEmails(config: ImapWebhookConfig, requestId: string, resolvedIP: string) {
const client = new ImapFlow({
host: config.host,
host: resolvedIP,
servername: config.host,
port: config.port || 993,
secure: config.secure ?? true,
auth: {
@@ -267,7 +279,7 @@ async function fetchNewEmails(config: ImapWebhookConfig, requestId: string) {
pass: config.password,
},
tls: {
rejectUnauthorized: config.rejectUnauthorized ?? true,
rejectUnauthorized: true,
},
logger: false,
})
@@ -553,13 +565,15 @@ async function processEmails(
}>,
webhookData: WebhookRecord,
config: ImapWebhookConfig,
requestId: string
requestId: string,
resolvedIP: string
) {
let processedCount = 0
let failedCount = 0
const client = new ImapFlow({
host: config.host,
host: resolvedIP,
servername: config.host,
port: config.port || 993,
secure: config.secure ?? true,
auth: {
@@ -567,7 +581,7 @@ async function processEmails(
pass: config.password,
},
tls: {
rejectUnauthorized: config.rejectUnauthorized ?? true,
rejectUnauthorized: true,
},
logger: false,
})

View File

@@ -2822,7 +2822,6 @@ export async function configureImapPolling(webhookData: any, requestId: string):
...providerConfig,
port: providerConfig.port || '993',
secure: providerConfig.secure !== false,
rejectUnauthorized: providerConfig.rejectUnauthorized !== false,
mailbox: providerConfig.mailbox || 'INBOX',
searchCriteria: providerConfig.searchCriteria || 'UNSEEN',
markAsRead: providerConfig.markAsRead || false,

View File

@@ -44,15 +44,6 @@ export const imapPollingTrigger: TriggerConfig = {
required: false,
mode: 'trigger',
},
{
id: 'rejectUnauthorized',
title: 'Verify TLS Certificate',
type: 'switch',
defaultValue: true,
description: 'Verify server TLS certificate. Disable for self-signed certificates.',
required: false,
mode: 'trigger',
},
// Authentication
{
id: 'username',
@@ -89,7 +80,6 @@ export const imapPollingTrigger: TriggerConfig = {
const host = store.getValue(blockId, 'host') as string | null
const port = store.getValue(blockId, 'port') as string | null
const secure = store.getValue(blockId, 'secure') as boolean | null
const rejectUnauthorized = store.getValue(blockId, 'rejectUnauthorized') as boolean | null
const username = store.getValue(blockId, 'username') as string | null
const password = store.getValue(blockId, 'password') as string | null
@@ -105,7 +95,6 @@ export const imapPollingTrigger: TriggerConfig = {
host,
port: port ? Number.parseInt(port, 10) : 993,
secure: secure ?? true,
rejectUnauthorized: rejectUnauthorized ?? true,
username,
password,
}),
@@ -129,7 +118,7 @@ export const imapPollingTrigger: TriggerConfig = {
throw error
}
},
dependsOn: ['host', 'port', 'secure', 'rejectUnauthorized', 'username', 'password'],
dependsOn: ['host', 'port', 'secure', 'username', 'password'],
mode: 'trigger',
},
// Email filtering

View File

@@ -1,5 +1,6 @@
{
"lockfileVersion": 1,
"configVersion": 0,
"workspaces": {
"": {
"name": "simstudio",