Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

2.5 KB
Raw Blame
import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import SSOAuth from '../sso-auth'

const navigationMocks = vi.hoisted(() => ({
  push: vi.fn(),
  replace: vi.fn(),
  searchParams: new URLSearchParams(),
}))

const serviceMocks = vi.hoisted(() => ({
  fetchMembersOAuth2SSOUrl: vi.fn(),
  fetchMembersOIDCSSOUrl: vi.fn(),
  fetchMembersSAMLSSOUrl: vi.fn(),
}))

vi.mock('@/next/navigation', () => ({
  useRouter: () => ({
    push: navigationMocks.push,
    replace: navigationMocks.replace,
  }),
  useSearchParams: () => navigationMocks.searchParams,
}))

vi.mock('@/service/share', () => serviceMocks)

describe('SSOAuth redirect security', () => {
  beforeEach(() => {
    Object.values(serviceMocks).forEach((mock) => mock.mockReset())
    navigationMocks.searchParams = new URLSearchParams({
      redirect_url: 'https://evil.example/chatbot/evil-app',
    })
  })

  it('should use the login fallback without calling SSO when the redirect target is external', async () => {
    const user = userEvent.setup()
    render(<SSOAuth protocol={zSsoProtocol.enum.saml} />)

    await user.click(screen.getByRole('button', { name: 'login.withSSO' }))

    await waitFor(() => {
      expect(navigationMocks.replace).toHaveBeenCalledWith('/')
    })
    expect(serviceMocks.fetchMembersSAMLSSOUrl).not.toHaveBeenCalled()
    expect(serviceMocks.fetchMembersOIDCSSOUrl).not.toHaveBeenCalled()
    expect(serviceMocks.fetchMembersOAuth2SSOUrl).not.toHaveBeenCalled()
  })

  it.each([
    [zSsoProtocol.enum.saml, serviceMocks.fetchMembersSAMLSSOUrl],
    [zSsoProtocol.enum.oidc, serviceMocks.fetchMembersOIDCSSOUrl],
    [zSsoProtocol.enum.oauth2, serviceMocks.fetchMembersOAuth2SSOUrl],
  ])('should send the sanitized redirect target to %s SSO', async (protocol, serviceMock) => {
    const user = userEvent.setup()
    navigationMocks.searchParams = new URLSearchParams({
      redirect_url: encodeURIComponent('/chatbot/share-app?foo=bar'),
    })
    serviceMock.mockResolvedValue({ url: 'https://idp.example/authorize' })
    render(<SSOAuth protocol={protocol} />)

    await user.click(screen.getByRole('button', { name: 'login.withSSO' }))

    await waitFor(() => {
      expect(serviceMock).toHaveBeenCalledWith('share-app', '/chatbot/share-app?foo=bar')
    })
    expect(navigationMocks.push).toHaveBeenCalledWith('https://idp.example/authorize')
  })
})