mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 07:59:03 +00:00
## Context Deploys the trusted partner changes from the following PRs: - https://github.com/supabase/supabase/pull/54006 - https://github.com/supabase/supabase/pull/53583 - https://github.com/supabase/supabase/pull/53705 - https://github.com/supabase/supabase/pull/53917 - https://github.com/supabase/supabase/pull/54507 - https://github.com/supabase/supabase/pull/54506 --------- Co-authored-by: Danny White <3104761+dnywh@users.noreply.github.com>
436 lines
17 KiB
TypeScript
436 lines
17 KiB
TypeScript
import { QueryClient } from '@tanstack/react-query'
|
||
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
|
||
import userEvent from '@testing-library/user-event'
|
||
import type { paths } from 'api-types'
|
||
import { FeatureFlagContext } from 'common'
|
||
import { mockAnimationsApi } from 'jsdom-testing-mocks'
|
||
import { http, HttpResponse } from 'msw'
|
||
import { beforeEach, describe, expect, test } from 'vitest'
|
||
|
||
import { JitDbAccessApps } from './JitDbAccessApps'
|
||
import { JitDbAccessConfiguration } from './JitDbAccessConfiguration'
|
||
import { mockAccess } from './JitDbAccessConfiguration.test-fixtures'
|
||
import { API_URL } from '@/lib/constants'
|
||
import { createMockAuthContext } from '@/tests/lib/auth-helpers'
|
||
import { customRender } from '@/tests/lib/custom-render'
|
||
import { addAPIMock, mswServer, type APIErrorBody } from '@/tests/lib/msw'
|
||
import { mockPermissions } from '@/tests/lib/msw-permissions'
|
||
import { allPermissionsFor } from '@/tests/lib/permissions-fixtures'
|
||
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
|
||
|
||
type Configuration =
|
||
paths['/v1/projects/{ref}/jit-access']['get']['responses'][200]['content']['application/json']
|
||
|
||
mockAnimationsApi()
|
||
|
||
beforeEach(() => {
|
||
mockPermissions(allPermissionsFor(['test-org']))
|
||
mswServer.use(
|
||
http.get(`${API_URL}/platform/profile/permissions`, () =>
|
||
HttpResponse.json([
|
||
{
|
||
organization_slug: 'test-org',
|
||
actions: ['%'],
|
||
resources: ['%'],
|
||
condition: null,
|
||
restrictive: false,
|
||
project_refs: [],
|
||
},
|
||
])
|
||
)
|
||
)
|
||
})
|
||
|
||
async function renderConfiguration() {
|
||
customRender(
|
||
<FeatureFlagContext.Provider
|
||
value={{ configcat: { enableScopedOAuthManage: true }, posthog: {} }}
|
||
>
|
||
<JitDbAccessConfiguration />
|
||
</FeatureFlagContext.Provider>,
|
||
{
|
||
profileContext: createMockProfileContext(),
|
||
authContext: createMockAuthContext(),
|
||
}
|
||
)
|
||
const toggle = await screen.findByRole('switch')
|
||
await waitFor(() => expect(toggle).toBeEnabled())
|
||
return toggle
|
||
}
|
||
|
||
describe('Temporary access confirmations', () => {
|
||
test('keeps the app list and general link available without unsupported access-sheet actions', () => {
|
||
customRender(
|
||
<FeatureFlagContext.Provider
|
||
value={{ configcat: { enableScopedOAuthManage: false }, posthog: {} }}
|
||
>
|
||
<JitDbAccessApps
|
||
apps={[{ id: 'partner', name: 'Test partner', icon: null, access: 'write' }]}
|
||
organizationSlug="test-org"
|
||
isPending={false}
|
||
error={null}
|
||
canRead
|
||
/>
|
||
</FeatureFlagContext.Provider>
|
||
)
|
||
expect(screen.getByText('Test partner')).toBeInTheDocument()
|
||
expect(screen.getByText('Read and write')).toBeInTheDocument()
|
||
expect(screen.getByRole('link', { name: 'OAuth Apps' })).toHaveAttribute(
|
||
'href',
|
||
'/org/test-org/apps'
|
||
)
|
||
expect(screen.queryByRole('button', { name: 'Manage Test partner' })).not.toBeInTheDocument()
|
||
})
|
||
|
||
test('loads every approval and grant page, showing only this project’s organization token grants', async () => {
|
||
mockAccess()
|
||
const approval = (id: string, access: string) => ({
|
||
id,
|
||
type: 'oauth_app',
|
||
attributes: {
|
||
app: { name: id, icon: null, created_by: null },
|
||
last_approved_at: '',
|
||
target: 'organization',
|
||
org_grant: {
|
||
grant_id: `${id}-org`,
|
||
approved_scopes: [`database_token_access:${access}`],
|
||
approved_at: '',
|
||
},
|
||
},
|
||
})
|
||
mswServer.use(
|
||
http.get(`${API_URL}/platform/organizations/:slug/oauth/approvals`, ({ request }) =>
|
||
HttpResponse.json({
|
||
data: new URL(request.url).searchParams.has('page[after]')
|
||
? [approval('All projects', 'write'), approval('Other project', 'read')]
|
||
: [approval('Scoped app', 'read')],
|
||
links: {
|
||
next: new URL(request.url).searchParams.has('page[after]') ? null : '?page[after]=more',
|
||
prev: null,
|
||
},
|
||
})
|
||
)
|
||
)
|
||
mswServer.use(
|
||
http.get(
|
||
`${API_URL}/platform/organizations/:slug/oauth/approvals/:app_id/grants`,
|
||
({ params, request }) => {
|
||
const id = String(params.app_id)
|
||
const isLast = new URL(request.url).searchParams.has('page[after]')
|
||
return HttpResponse.json({
|
||
data: [
|
||
{
|
||
id: isLast ? `${id}-org` : 'member-grant',
|
||
type: 'oauth_grant',
|
||
attributes: {
|
||
kind: isLast ? 'organization_bound' : 'member_bound',
|
||
user: null,
|
||
approved_at: '',
|
||
approved_scopes: [
|
||
`database_token_access:${id === 'All projects' ? 'write' : 'read'}`,
|
||
],
|
||
projects:
|
||
id === 'All projects'
|
||
? null
|
||
: [
|
||
{
|
||
ref: id === 'Other project' ? 'another' : 'default',
|
||
name: 'Test project',
|
||
},
|
||
],
|
||
},
|
||
},
|
||
],
|
||
links: { next: isLast ? null : '?page[after]=grant', prev: null },
|
||
})
|
||
}
|
||
)
|
||
)
|
||
await renderConfiguration()
|
||
const apps = screen.getByRole('table', { name: 'Apps' })
|
||
expect(within(apps).getByText('Scoped app')).toBeInTheDocument()
|
||
expect(within(apps).getByText('All projects')).toBeInTheDocument()
|
||
expect(within(apps).queryByText('Other project')).not.toBeInTheDocument()
|
||
expect(within(apps).getByText('Read and write')).toBeInTheDocument()
|
||
expect(screen.getByRole('link', { name: 'OAuth Apps' })).toHaveAttribute(
|
||
'href',
|
||
'/org/test-org/apps'
|
||
)
|
||
await userEvent.click(within(apps).getByRole('button', { name: 'Manage Scoped app' }))
|
||
expect(await screen.findByRole('menuitem', { name: 'View access' })).toHaveAttribute(
|
||
'href',
|
||
'/org/test-org/apps?access_app=Scoped+app'
|
||
)
|
||
})
|
||
|
||
test('hides Apps while permissions resolve and when no apps are authorized', async () => {
|
||
mockAccess()
|
||
let finish: (() => void) | undefined
|
||
const pending = new Promise<void>((resolve) => {
|
||
finish = resolve
|
||
})
|
||
mswServer.use(
|
||
http.get(`${API_URL}/platform/profile/permissions`, async () => {
|
||
await pending
|
||
return HttpResponse.json([
|
||
{
|
||
organization_slug: 'test-org',
|
||
actions: ['%'],
|
||
resources: ['%'],
|
||
condition: null,
|
||
restrictive: false,
|
||
project_refs: [],
|
||
},
|
||
])
|
||
})
|
||
)
|
||
customRender(<JitDbAccessConfiguration />, {
|
||
profileContext: createMockProfileContext(),
|
||
authContext: createMockAuthContext(),
|
||
})
|
||
await screen.findByText('member-0@example.com')
|
||
expect(screen.queryByRole('heading', { name: 'Apps' })).not.toBeInTheDocument()
|
||
expect(
|
||
screen.queryByText(/You need additional permissions to view authorized apps/)
|
||
).not.toBeInTheDocument()
|
||
await act(async () => finish?.())
|
||
await waitFor(() => expect(screen.getByRole('switch')).toBeEnabled())
|
||
expect(screen.queryByRole('heading', { name: 'Apps' })).not.toBeInTheDocument()
|
||
})
|
||
|
||
test('still lets token access change when app permissions are unavailable', async () => {
|
||
mockAccess({ state: 'disabled' })
|
||
mswServer.use(http.get(`${API_URL}/platform/profile/permissions`, () => HttpResponse.json([])))
|
||
customRender(<JitDbAccessConfiguration />, {
|
||
profileContext: createMockProfileContext(),
|
||
authContext: createMockAuthContext(),
|
||
})
|
||
await waitFor(() => expect(screen.getByRole('switch')).toBeEnabled())
|
||
expect(screen.queryByText('No apps authorized')).not.toBeInTheDocument()
|
||
fireEvent.click(screen.getByRole('switch'))
|
||
const dialog = await screen.findByRole('alertdialog')
|
||
expect(dialog).toHaveTextContent(/Authorized apps couldn’t be loaded/)
|
||
expect(within(dialog).getByRole('button', { name: 'Enable' })).toBeEnabled()
|
||
})
|
||
|
||
test.each(['request failure', 'mismatched scopes'])(
|
||
'does not block an enable after %s, and lists apps once they load',
|
||
async (failure) => {
|
||
mockAccess({ state: 'disabled', memberCount: 0 })
|
||
let finish: (() => void) | undefined
|
||
const pending = new Promise<void>((resolve) => {
|
||
finish = resolve
|
||
})
|
||
let failed = false
|
||
let grantScope =
|
||
failure === 'mismatched scopes'
|
||
? 'database_token_access:read'
|
||
: 'database_token_access:write'
|
||
mswServer.use(
|
||
http.get(`${API_URL}/platform/organizations/:slug/oauth/approvals`, async () => {
|
||
if (!failed) {
|
||
failed = true
|
||
await pending
|
||
if (failure === 'request failure') {
|
||
return HttpResponse.json<APIErrorBody>(
|
||
{ message: 'Apps unavailable' },
|
||
{ status: 500 }
|
||
)
|
||
}
|
||
}
|
||
return HttpResponse.json({
|
||
data: [
|
||
{
|
||
id: 'partner',
|
||
type: 'oauth_app',
|
||
attributes: {
|
||
app: { name: 'Example Partner', icon: null, created_by: null },
|
||
last_approved_at: '',
|
||
target: 'organization',
|
||
org_grant: {
|
||
grant_id: 'partner-org',
|
||
approved_scopes: ['database_token_access:write'],
|
||
approved_at: '',
|
||
},
|
||
},
|
||
},
|
||
],
|
||
links: { next: null, prev: null },
|
||
})
|
||
})
|
||
)
|
||
mswServer.use(
|
||
http.get(`${API_URL}/platform/organizations/:slug/oauth/approvals/:app_id/grants`, () =>
|
||
HttpResponse.json({
|
||
data: [
|
||
{
|
||
id: 'partner-org',
|
||
type: 'oauth_grant',
|
||
attributes: {
|
||
kind: 'organization_bound',
|
||
user: null,
|
||
approved_at: '',
|
||
approved_scopes: [grantScope],
|
||
projects: null,
|
||
},
|
||
},
|
||
],
|
||
links: { next: null, prev: null },
|
||
})
|
||
)
|
||
)
|
||
const queryClient = new QueryClient({
|
||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||
})
|
||
customRender(<JitDbAccessConfiguration />, {
|
||
queryClient,
|
||
profileContext: createMockProfileContext(),
|
||
authContext: createMockAuthContext(),
|
||
})
|
||
expect(await screen.findByRole('switch')).toBeDisabled()
|
||
expect(screen.queryByRole('heading', { name: 'Apps' })).not.toBeInTheDocument()
|
||
expect(screen.queryByText('No apps authorized')).not.toBeInTheDocument()
|
||
await act(async () => finish?.())
|
||
await waitFor(() => expect(screen.getByRole('switch')).toBeEnabled())
|
||
fireEvent.click(screen.getByRole('switch'))
|
||
const failedDialog = await screen.findByRole('alertdialog')
|
||
expect(failedDialog).toHaveTextContent(/Authorized apps couldn’t be loaded/)
|
||
fireEvent.click(within(failedDialog).getByRole('button', { name: 'Cancel' }))
|
||
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
|
||
|
||
grantScope = 'database_token_access:write'
|
||
await act(() => queryClient.refetchQueries({ queryKey: ['oauth-apps', 'approvals'] }))
|
||
await waitFor(() => expect(screen.getByRole('switch')).toBeEnabled())
|
||
fireEvent.click(screen.getByRole('switch'))
|
||
const dialog = await screen.findByRole('alertdialog')
|
||
expect(dialog).toHaveTextContent('1 authorized app')
|
||
fireEvent.click(within(dialog).getByRole('button', { name: 'Who will regain access?' }))
|
||
expect(within(dialog).getByText('Example Partner')).toBeInTheDocument()
|
||
}
|
||
)
|
||
|
||
test.each([
|
||
{
|
||
state: 'disabled',
|
||
description:
|
||
'Members with access rules and approved apps will be able to connect using access tokens.',
|
||
},
|
||
{
|
||
state: 'enabled',
|
||
description:
|
||
'Members and apps will no longer be able to connect using access tokens. Existing connections will stay open.',
|
||
},
|
||
] as const)(
|
||
'explains the change when token access is $state and all rules have expired',
|
||
async ({ state, description }) => {
|
||
mockAccess({ state, roleExpiresAt: 1 })
|
||
const toggle = await renderConfiguration()
|
||
if (state === 'enabled') await waitFor(() => expect(toggle).toBeChecked())
|
||
|
||
fireEvent.click(toggle)
|
||
|
||
const dialog = await screen.findByRole('alertdialog')
|
||
expect(within(dialog).getByText(description)).toBeInTheDocument()
|
||
expect(
|
||
within(dialog).queryByRole('button', { name: 'Who will regain access?' })
|
||
).not.toBeInTheDocument()
|
||
}
|
||
)
|
||
|
||
test('cancels disabling without changing access and confirms through the real mutation', async () => {
|
||
const update = mockAccess()
|
||
const toggle = await renderConfiguration()
|
||
await waitFor(() => expect(toggle).toBeChecked())
|
||
fireEvent.click(toggle)
|
||
const dialog = await screen.findByRole('alertdialog')
|
||
expect(dialog).toHaveTextContent('1 member')
|
||
expect(dialog).toHaveTextContent('Existing connections will stay open.')
|
||
expect(update).not.toHaveBeenCalled()
|
||
fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
|
||
expect(toggle).toBeChecked()
|
||
expect(update).not.toHaveBeenCalled()
|
||
fireEvent.click(toggle)
|
||
fireEvent.click(
|
||
within(await screen.findByRole('alertdialog')).getByRole('button', { name: 'Disable' })
|
||
)
|
||
await waitFor(() => expect(update).toHaveBeenCalledTimes(1))
|
||
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
|
||
expect(toggle).not.toBeChecked()
|
||
})
|
||
|
||
test('shows all 100 current members before enabling and confirms the update', async () => {
|
||
const update = mockAccess({ state: 'disabled', memberCount: 100 })
|
||
const toggle = await renderConfiguration()
|
||
fireEvent.click(toggle)
|
||
const dialog = await screen.findByRole('alertdialog')
|
||
expect(dialog).toHaveTextContent('100 members open new database connections')
|
||
fireEvent.click(within(dialog).getByRole('button', { name: 'Who will regain access?' }))
|
||
expect(within(dialog).getByText('member-99@example.com')).toBeInTheDocument()
|
||
expect(update).not.toHaveBeenCalled()
|
||
fireEvent.click(within(dialog).getByRole('button', { name: /^Enable$/ }))
|
||
await waitFor(() => expect(update).toHaveBeenCalledTimes(1))
|
||
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
|
||
expect(toggle).toBeChecked()
|
||
})
|
||
|
||
test('explains a failed member list before allowing disabled access to be enabled', async () => {
|
||
const update = mockAccess({ state: 'disabled' })
|
||
addAPIMock({
|
||
method: 'get',
|
||
path: '/v1/projects/:ref/database/jit/list',
|
||
response: () =>
|
||
HttpResponse.json<APIErrorBody>({ message: 'Member list unavailable' }, { status: 500 }),
|
||
})
|
||
customRender(<JitDbAccessConfiguration />, {
|
||
profileContext: createMockProfileContext(),
|
||
authContext: createMockAuthContext(),
|
||
})
|
||
const toggle = await screen.findByRole('switch', { name: 'Token access' })
|
||
await waitFor(() => expect(toggle).toHaveAttribute('aria-busy', 'false'))
|
||
expect(screen.getByText('Failed to load member access rules')).toBeInTheDocument()
|
||
expect(toggle).not.toBeChecked()
|
||
expect(toggle).toBeDisabled()
|
||
fireEvent.click(toggle)
|
||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
|
||
expect(update).not.toHaveBeenCalled()
|
||
})
|
||
|
||
test('keeps the dialog open while saving and after a failure so the user can retry', async () => {
|
||
mockAccess()
|
||
let failRequest: (() => void) | undefined
|
||
const pending = new Promise<void>((resolve) => {
|
||
failRequest = resolve
|
||
})
|
||
let hasFailed = false
|
||
addAPIMock({
|
||
method: 'put',
|
||
path: '/v1/projects/:ref/jit-access',
|
||
response: async () => {
|
||
if (!hasFailed) {
|
||
hasFailed = true
|
||
await pending
|
||
return HttpResponse.json<APIErrorBody>(
|
||
{ message: 'Access update failed' },
|
||
{ status: 500 }
|
||
)
|
||
}
|
||
return HttpResponse.json<Configuration>({ state: 'disabled', appliedSuccessfully: true })
|
||
},
|
||
})
|
||
const toggle = await renderConfiguration()
|
||
await waitFor(() => expect(toggle).toBeChecked())
|
||
fireEvent.click(toggle)
|
||
const dialog = await screen.findByRole('alertdialog')
|
||
fireEvent.click(within(dialog).getByRole('button', { name: 'Disable' }))
|
||
await waitFor(() =>
|
||
expect(within(dialog).getByRole('button', { name: 'Cancel' })).toBeDisabled()
|
||
)
|
||
expect(dialog).toHaveTextContent('Disable token access')
|
||
await act(async () => failRequest?.())
|
||
expect(await within(dialog).findByText('Access update failed')).toBeInTheDocument()
|
||
expect(toggle).toBeChecked()
|
||
fireEvent.click(within(dialog).getByRole('button', { name: 'Disable' }))
|
||
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
|
||
})
|
||
})
|