Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
2dd6d3d
fix(import): dedup workflow name (#3813)
icecrasher321 Mar 27, 2026
dda012e
feat(concurrency): bullmq based concurrency control system (#3605)
icecrasher321 Mar 27, 2026
271624a
fix(linear): add default null for after cursor (#3814)
icecrasher321 Mar 27, 2026
a7c1e51
fix(knowledge): reject non-alphanumeric file extensions from document…
waleedlatif1 Mar 27, 2026
c05e2e0
fix(security): SSRF, access control, and info disclosure (#3815)
waleedlatif1 Mar 28, 2026
21156dd
fix(worker): dockerfile + helm updates (#3818)
icecrasher321 Mar 28, 2026
33fdb11
update dockerfile (#3819)
icecrasher321 Mar 28, 2026
23c3072
fix dockerfile
icecrasher321 Mar 28, 2026
8f3e864
fix(security): pentest remediation — condition escaping, SSRF hardeni…
waleedlatif1 Mar 28, 2026
d2c3c1c
improvement(worker): configuration defaults (#3821)
icecrasher321 Mar 28, 2026
eac41ca
improvement(tour): remove auto-start, only trigger on explicit user a…
waleedlatif1 Mar 28, 2026
b4064c5
fix(mcp): use correct modal for creating workflow MCP servers in depl…
waleedlatif1 Mar 28, 2026
e4d3573
fix(knowledge): give users choice to keep or delete documents when re…
waleedlatif1 Mar 28, 2026
f6b461a
fix(readme): restore readme gifs (#3827)
waleedlatif1 Mar 28, 2026
e2be992
feat(academy): Sim Academy — interactive partner certification platfo…
waleedlatif1 Mar 28, 2026
edc5023
improvement(sidebar): expand sidebar by hovering and clicking the edg…
waleedlatif1 Mar 28, 2026
0ea7326
feat(ui): handle image paste (#3826)
TheodoreSpeaks Mar 28, 2026
7b0ce80
feat(files): interactive markdown checkbox toggling in preview (#3829)
waleedlatif1 Mar 28, 2026
d013132
improvement(home): position @ mention popup at caret and fix icon con…
waleedlatif1 Mar 28, 2026
30377d7
improvement(ui): sidebar (#3832)
waleedlatif1 Mar 28, 2026
f1ead2e
fix docker image build
icecrasher321 Mar 29, 2026
b9b930b
feat(analytics): add Profound web traffic tracking (#3835)
waleedlatif1 Mar 29, 2026
b371364
feat(resources): add sort and filter to all resource list pages (#3834)
waleedlatif1 Mar 29, 2026
336c065
fix(viewer): image pan/zoom, sort fixes, sidebar dot fixes (#3836)
waleedlatif1 Mar 29, 2026
82e58a5
fix(academy): hide academy pages until content is ready (#3839)
waleedlatif1 Mar 30, 2026
1728c37
improvement(landing): lighthouse performance and accessibility fixes …
waleedlatif1 Mar 30, 2026
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
Prev Previous commit
Next Next commit
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>
  • Loading branch information
waleedlatif1 and claude authored Mar 28, 2026
commit c05e2e0fc8d7e79cc02d61300675c4b2791ba38b
35 changes: 16 additions & 19 deletions apps/sim/app/api/copilot/feedback/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const {
mockReturning,
mockSelect,
mockFrom,
mockWhere,
mockAuthenticate,
mockCreateUnauthorizedResponse,
mockCreateBadRequestResponse,
Expand All @@ -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(),
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand All @@ -415,29 +418,23 @@ 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)

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 () => {
Expand All @@ -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)
Expand All @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions apps/sim/app/api/copilot/feedback/route.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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()
Expand All @@ -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,
Expand All @@ -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`)

Expand Down
9 changes: 9 additions & 0 deletions apps/sim/app/api/copilot/training/examples/route.ts
Original file line number Diff line number Diff line change
@@ -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')
Expand All @@ -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')
Expand Down
9 changes: 9 additions & 0 deletions apps/sim/app/api/copilot/training/route.ts
Original file line number Diff line number Diff line change
@@ -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')
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
25 changes: 11 additions & 14 deletions apps/sim/app/api/tools/imap/mailboxes/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ 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')

interface ImapMailboxRequest {
host: string
port: number
secure: boolean
rejectUnauthorized: boolean
username: string
password: string
}
Expand All @@ -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(
Expand All @@ -31,16 +31,22 @@ 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: {
user: username,
pass: password,
},
tls: {
rejectUnauthorized: rejectUnauthorized ?? true,
rejectUnauthorized: true,
},
logger: false,
})
Expand Down Expand Up @@ -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 })
Expand Down
24 changes: 16 additions & 8 deletions apps/sim/app/api/tools/sftp/utils.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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() !== ''
Expand All @@ -111,7 +119,7 @@ export function createSftpConnection(config: SftpConnectionConfig): Promise<Clie
}

const connectConfig: ConnectConfig = {
host: host.trim(),
host: resolvedHost,
port,
username: config.username,
}
Expand Down
37 changes: 24 additions & 13 deletions apps/sim/app/api/tools/smtp/send/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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,
Expand All @@ -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: {
Expand All @@ -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'
Expand Down Expand Up @@ -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
}
Expand Down
Loading
Loading