ApiAuthorization.test.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import { screen, waitFor } from '@testing-library/react'
  2. import userEvent from '@testing-library/user-event'
  3. import dayjs from 'dayjs'
  4. import { HttpResponse } from 'msw'
  5. import { describe, expect, test, vi } from 'vitest'
  6. import {
  7. ApiAuthorizationScreen,
  8. type ApiAuthorizationScreenProps,
  9. } from '@/components/interfaces/ApiAuthorization/ApiAuthorization'
  10. import type { ApiAuthorizationResponse } from '@/data/api-authorization/api-authorization-query'
  11. import type { ProfileContextType } from '@/lib/profile'
  12. import { createMockOrganization } from '@/tests/helpers'
  13. import { customRender } from '@/tests/lib/custom-render'
  14. import { addAPIMock } from '@/tests/lib/msw'
  15. import type { Organization } from '@/types'
  16. // --- Fixtures ---
  17. const DEFAULT_PROFILE_CONTEXT: ProfileContextType = {
  18. profile: {
  19. id: 1,
  20. auth0_id: 'auth0|test',
  21. gotrue_id: 'gotrue-test',
  22. username: 'testuser',
  23. primary_email: 'test@example.com',
  24. first_name: null,
  25. last_name: null,
  26. mobile: null,
  27. is_alpha_user: false,
  28. is_sso_user: false,
  29. disabled_features: [],
  30. free_project_limit: null,
  31. },
  32. error: null,
  33. isLoading: false,
  34. isError: false,
  35. isSuccess: true,
  36. }
  37. function createMockAuthResponse(
  38. overrides: Partial<ApiAuthorizationResponse> = {}
  39. ): ApiAuthorizationResponse {
  40. return {
  41. name: 'Test App',
  42. website: 'https://testapp.com',
  43. icon: null,
  44. domain: 'testapp.com',
  45. scopes: [],
  46. expires_at: dayjs().add(1, 'hour').toISOString(),
  47. approved_at: null,
  48. registration_type: 'static',
  49. ...overrides,
  50. }
  51. }
  52. const DEFAULT_ORG = createMockOrganization({ name: 'My Org', slug: 'my-org' })
  53. const SECOND_ORG = createMockOrganization({ id: 2, name: 'Second Org', slug: 'second-org' })
  54. // --- MSW helpers ---
  55. // Both the auth query and the organizations query fire for any valid auth_id render.
  56. // Since MSW is configured with onUnhandledRequest: 'error', both must always be mocked.
  57. function mockAuthEndpoint(authResponse: ApiAuthorizationResponse) {
  58. addAPIMock({
  59. method: 'get',
  60. path: '/platform/oauth/authorizations/:id',
  61. response: () => HttpResponse.json(authResponse),
  62. })
  63. }
  64. function mockOrgsEndpoint(orgs: Array<Organization> = [DEFAULT_ORG]) {
  65. addAPIMock({
  66. method: 'get',
  67. path: '/platform/organizations',
  68. response: () => HttpResponse.json(orgs),
  69. })
  70. }
  71. function mockBothEndpoints(
  72. authResponse: ApiAuthorizationResponse = createMockAuthResponse(),
  73. orgs: Array<Organization> = [DEFAULT_ORG]
  74. ) {
  75. mockAuthEndpoint(authResponse)
  76. mockOrgsEndpoint(orgs)
  77. }
  78. // --- Render helper ---
  79. function renderScreen(props: Partial<ApiAuthorizationScreenProps> = {}) {
  80. const navigate = vi.fn()
  81. const result = customRender(
  82. <ApiAuthorizationScreen
  83. auth_id="test-auth-id"
  84. organization_slug={undefined}
  85. navigate={navigate}
  86. {...props}
  87. />,
  88. { profileContext: DEFAULT_PROFILE_CONTEXT }
  89. )
  90. return { ...result, navigate }
  91. }
  92. // --- Tests ---
  93. describe('ApiAuthorizationScreen', () => {
  94. describe('when auth_id is missing', () => {
  95. test('renders invalid screen when auth_id is undefined', () => {
  96. renderScreen({ auth_id: undefined })
  97. expect(screen.getByText('Missing parameters')).toBeInTheDocument()
  98. expect(screen.getByText(/auth_id/)).toBeInTheDocument()
  99. })
  100. })
  101. describe('when auth_id is provided', () => {
  102. test('renders loading screen while authorization data is being fetched', () => {
  103. mockOrgsEndpoint()
  104. addAPIMock({
  105. method: 'get',
  106. path: '/platform/oauth/authorizations/:id',
  107. response: () => new Promise(() => {}),
  108. })
  109. const { container } = renderScreen()
  110. expect(screen.getByText('Loading...')).toBeInTheDocument()
  111. expect(container.querySelectorAll('.shimmering-loader').length).toBeGreaterThan(0)
  112. })
  113. test('renders error screen when authorization query fails', async () => {
  114. mockOrgsEndpoint()
  115. addAPIMock({
  116. method: 'get',
  117. path: '/platform/oauth/authorizations/:id',
  118. response: () => HttpResponse.json({ message: 'Not found' }, { status: 404 }),
  119. })
  120. renderScreen()
  121. await screen.findByText('Failed to fetch details for API authorization request')
  122. })
  123. describe('when already approved', () => {
  124. test('renders approved screen with matching organization name', async () => {
  125. mockBothEndpoints(
  126. createMockAuthResponse({
  127. approved_at: '2025-01-15T10:00:00Z',
  128. approved_organization_slug: 'my-org',
  129. })
  130. )
  131. renderScreen()
  132. await screen.findByText('This authorization request has been approved')
  133. expect(screen.getByText(/organization "My Org"/)).toBeInTheDocument()
  134. })
  135. test('shows Unknown when approved organization is not in the user organizations list', async () => {
  136. mockBothEndpoints(
  137. createMockAuthResponse({
  138. approved_at: '2025-01-15T10:00:00Z',
  139. approved_organization_slug: 'other-org',
  140. })
  141. )
  142. renderScreen()
  143. await screen.findByText('This authorization request has been approved')
  144. expect(screen.getByText(/organization "Unknown"/)).toBeInTheDocument()
  145. })
  146. })
  147. describe('main authorization form', () => {
  148. describe('organizations states', () => {
  149. test('disables action buttons while organizations are being fetched', async () => {
  150. mockAuthEndpoint(createMockAuthResponse())
  151. addAPIMock({
  152. method: 'get',
  153. path: '/platform/organizations',
  154. response: () => new Promise(() => {}),
  155. })
  156. renderScreen()
  157. await screen.findByText('Authorize API access for Test App')
  158. expect(screen.getByRole('button', { name: 'Decline' })).toBeDisabled()
  159. expect(screen.getByRole('button', { name: /Authorize Test App/ })).toBeDisabled()
  160. })
  161. test('shows error notice, disables decline button, and hides accept button when organizations query fails', async () => {
  162. mockAuthEndpoint(createMockAuthResponse())
  163. addAPIMock({
  164. method: 'get',
  165. path: '/platform/organizations',
  166. response: () => HttpResponse.json({ message: 'Server error' }, { status: 500 }),
  167. })
  168. renderScreen()
  169. await screen.findByText('There was an error loading your organizations')
  170. expect(screen.getByRole('button', { name: 'Decline' })).toBeDisabled()
  171. expect(
  172. screen.queryByRole('button', { name: /Authorize Test App/ })
  173. ).not.toBeInTheDocument()
  174. })
  175. test('shows empty state when user has no organizations', async () => {
  176. mockBothEndpoints(createMockAuthResponse(), [])
  177. renderScreen()
  178. await screen.findByText(/Your account isn't associated with any organizations/)
  179. expect(screen.getByRole('link', { name: 'Create an organization' })).toBeInTheDocument()
  180. expect(screen.getByRole('button', { name: 'Decline' })).toBeDisabled()
  181. expect(
  182. screen.queryByRole('button', { name: /Authorize Test App/ })
  183. ).not.toBeInTheDocument()
  184. })
  185. test('shows not_member notice when organization_slug does not match any user organization', async () => {
  186. mockBothEndpoints()
  187. renderScreen({ organization_slug: 'nonexistent-org' })
  188. await screen.findByText(/Your account is not a member of the pre-selected organization/)
  189. expect(screen.getByRole('button', { name: 'Decline' })).toBeDisabled()
  190. expect(screen.getByRole('button', { name: /Authorize Test App/ })).toBeDisabled()
  191. })
  192. })
  193. describe('success state with organization selector', () => {
  194. test('renders form with organization selector and action buttons', async () => {
  195. mockBothEndpoints(createMockAuthResponse({ name: 'My OAuth App' }))
  196. renderScreen()
  197. await screen.findByText('Authorize API access for My OAuth App')
  198. expect(screen.getByRole('combobox')).toBeInTheDocument()
  199. expect(screen.getByRole('button', { name: /Authorize My OAuth App/ })).toBeInTheDocument()
  200. expect(screen.getByRole('button', { name: 'Decline' })).toBeInTheDocument()
  201. })
  202. test('auto-selects the only organization when no organization_slug is provided', async () => {
  203. mockBothEndpoints()
  204. renderScreen()
  205. const combobox = await screen.findByRole('combobox')
  206. expect(combobox).toHaveTextContent('My Org')
  207. })
  208. test('pre-selects organization when organization_slug matches a user organization', async () => {
  209. mockBothEndpoints(createMockAuthResponse(), [DEFAULT_ORG, SECOND_ORG])
  210. renderScreen({ organization_slug: 'second-org' })
  211. const combobox = await screen.findByRole('combobox')
  212. expect(combobox).toHaveTextContent('Second Org')
  213. expect(combobox).not.toHaveTextContent('My Org')
  214. expect(
  215. screen.getByText('This organization has been pre-selected by Test App.')
  216. ).toBeInTheDocument()
  217. })
  218. })
  219. describe('MCP client warning', () => {
  220. test('shows MCP warning when registration_type is dynamic', async () => {
  221. mockBothEndpoints(createMockAuthResponse({ registration_type: 'dynamic' }))
  222. renderScreen()
  223. await screen.findByText('MCP Client Connection')
  224. })
  225. test('does not show MCP warning for non-dynamic registration type', async () => {
  226. mockBothEndpoints()
  227. renderScreen()
  228. await screen.findByText('Authorize API access for Test App')
  229. expect(screen.queryByText('MCP Client Connection')).not.toBeInTheDocument()
  230. })
  231. })
  232. describe('expiration', () => {
  233. test('shows expiration warning and disables buttons when request has expired', async () => {
  234. mockBothEndpoints(
  235. createMockAuthResponse({ expires_at: dayjs().subtract(1, 'hour').toISOString() })
  236. )
  237. renderScreen()
  238. await screen.findByText('This authorization request is expired')
  239. expect(screen.getByRole('button', { name: 'Decline' })).toBeDisabled()
  240. expect(screen.getByRole('button', { name: /Authorize Test App/ })).toBeDisabled()
  241. })
  242. test('does not show expiration warning when request has not expired', async () => {
  243. mockBothEndpoints()
  244. renderScreen()
  245. await screen.findByText('Authorize API access for Test App')
  246. expect(
  247. screen.queryByText('This authorization request is expired')
  248. ).not.toBeInTheDocument()
  249. })
  250. })
  251. describe('approve action', () => {
  252. test('calls approve endpoint when Authorize button is clicked', async () => {
  253. const user = userEvent.setup()
  254. const approveHandler = vi.fn(() =>
  255. HttpResponse.json({ url: 'https://redirect.example.com' })
  256. )
  257. mockBothEndpoints()
  258. addAPIMock({
  259. method: 'post',
  260. path: '/platform/organizations/:slug/oauth/authorizations/:id',
  261. response: approveHandler,
  262. })
  263. renderScreen()
  264. await screen.findByRole('button', { name: /Authorize Test App/ })
  265. await user.click(screen.getByRole('button', { name: /Authorize Test App/ }))
  266. await waitFor(() => expect(approveHandler).toHaveBeenCalled())
  267. })
  268. })
  269. describe('decline action', () => {
  270. test('navigates to /organizations after declining', async () => {
  271. const user = userEvent.setup()
  272. const declineHandler = vi.fn(() => HttpResponse.json({ id: 'test-auth-id' }))
  273. mockBothEndpoints()
  274. addAPIMock({
  275. method: 'delete',
  276. path: '/platform/organizations/:slug/oauth/authorizations/:id',
  277. response: declineHandler,
  278. })
  279. const { navigate } = renderScreen()
  280. await screen.findByRole('button', { name: 'Decline' })
  281. await user.click(screen.getByRole('button', { name: 'Decline' }))
  282. await waitFor(() => expect(declineHandler).toHaveBeenCalled())
  283. await waitFor(() => expect(navigate).toHaveBeenCalledWith('/organizations'))
  284. })
  285. })
  286. describe('form validation', () => {
  287. test('shows validation error when Authorize is clicked without selecting an organization', async () => {
  288. const user = userEvent.setup()
  289. // Two orgs → no auto-selection, user must pick one manually
  290. mockBothEndpoints(createMockAuthResponse(), [DEFAULT_ORG, SECOND_ORG])
  291. renderScreen()
  292. await screen.findByRole('button', { name: /Authorize Test App/ })
  293. await user.click(screen.getByRole('button', { name: /Authorize Test App/ }))
  294. expect(
  295. (await screen.findAllByText('Please select an organization')).length
  296. ).toBeGreaterThan(0)
  297. })
  298. })
  299. })
  300. })
  301. })