Files
supabase/apps/studio/tests/routes/authorize.test.tsx
Danny WhiteandJoshen Lim 4dbb966b2e feat(studio): show Trusted Partner access on OAuth consent (#53583)
> [!WARNING]
> Live readiness checks require
[CTRL-2277](https://linear.app/supabase/issue/CTRL-2277) in the target
environment; production deployment is pending.

## Problem

Trusted Partner consent must explain direct database access and project
blockers before authorisation.
[DEPR-732](https://linear.app/supabase/issue/DEPR-732)

## Solution

- Show Direct database access alongside the requested permissions.
- Check selected projects, or every project page for organisation-wide
grants.
- Separate blocking issues from SSL notices; block authorisation during
loading or errors and offer retry.

| After |
| --- |
| <img width="1280" height="1323" alt="Authorize API Access Supabase"
src="https://github.com/user-attachments/assets/adb6367a-bace-4b62-81b5-68ba4c11396c"
/> |
| Consent screen with Direct database access (previously “Table data”)
and Database management |
| <img width="1280" height="1323" alt="Authorize API Access Supabase"
src="https://github.com/user-attachments/assets/0c35900c-1059-49cd-b1c5-4e0cf5441b9b"
/> |
| Selected-project blockers and the separate SSL notice |
| <img width="1280" height="1323" alt="95741"
src="https://github.com/user-attachments/assets/1fbef4f0-0433-4c93-b390-84d210dfb665"
/> |
| Organisation-wide blockers _without_ project-removal actions |

## Review instructions

1. Open the [staging consent
screen](https://studio-staging-git-dnywh-depr-732-trusted-partn-f24cfb-supabase.vercel.app/dashboard/authorize?auth_id=11666aa8-7f7e-4705-b33a-981903fd682e).
Enable `enableScopedOAuthConsent` in the dev toolbar’s **Flags** tab if
needed.
2. Open Chrome DevTools → **Network** and reload. Select the **GET**
request ending in `/platform/oauth/authorizations/{id}`.
3. Right-click that request → **Override content**. Choose a local
folder and click **Allow**. Add `database_token_access:read` and
`database_token_access:write` to `scopes`. Use only the read scope to
check read-only access. Keep every other field, save with
**Cmd/Ctrl+S**, then reload with DevTools open.
4. Select projects. Override each **GET** request ending in
`/platform/organizations/{slug}/oauth/authorizations/{id}/projects/{ref}/database-access`.
Use `{"issues":[],"enables_ssl":false}` for ready projects, then
`{"issues":[],"enables_ssl":true}` for an SSL notice. Save and reload
after each change. Check Direct database access and Database management
are separate, and SSL alone allows authorisation.
5. Change a readiness response to
`{"issues":["postgres_upgrade_required","platform_unsupported"],"enables_ssl":true}`.
Save and reload. Check blockers prevent authorisation, SSL stays
separate, and removing a blocked project clears its blockers.
6. Set `project_scoping_mode: false` in the authorisation override. Save
and reload. Check any blocked project prevents organisation-wide
authorisation, with no project-removal actions.
7. Block a database-access request in Network and reload. Check
authorisation stays disabled. Unblock it and choose **Retry checks**.
8. For a returning app, override `existing_grant.approved_scopes` in the
request ending in `/preflight`. Save and reload. Check added, removed
and unchanged permissions.
9. Disable **Sources → Overrides → Enable Local Overrides**. Repeat
ready and blocked project checks with a real staging authorisation
before approving live readiness behaviour.

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-12-02 16:19:30 +07:00

322 lines
9.7 KiB
TypeScript

import { screen, waitFor } from '@testing-library/react'
import { mockIntersectionObserver } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { createMockOrganization } from '../helpers'
import { addAPIMock } from '../lib/msw'
import { createMockProfileContext } from '../lib/profile-helpers'
import { OAuthAppsAuthorizeRequestData } from '@/data/oauth-apps/oauth-apps-authorize-request-query'
import { OAuthAppsPreflightValidationData } from '@/data/oauth-apps/oauth-apps-preflight-validation-query'
import { OrgProject, OrgProjectsResponse } from '@/data/projects/org-projects-infinite-query'
import { ProjectDetail } from '@/data/projects/project-detail-query'
import { Route } from '@/routes/authorize'
import { renderRoute } from '@/tests/lib/route-render'
import { Organization } from '@/types'
vi.mock('@/hooks/misc/withAuth', () => ({
withAuth: (Component: React.ComponentType) => Component,
}))
const flags = vi.hoisted(() => ({ consent: false }))
vi.mock('common', async (importOriginal) => {
const actual = await importOriginal<typeof import('common')>()
return {
...actual,
useFlag: (key: string) => key === 'enableScopedOAuthConsent' && flags.consent,
}
})
const mockScopes: OAuthAppsAuthorizeRequestData['scopes'] = [
'database:read',
'database:write',
'environment:read',
'environment:write',
'secrets:read',
'projects:read',
'edge_functions:read',
'storage:read',
'analytics:read',
'analytics:write',
]
const createMockRequest = (
request?: Partial<OAuthAppsAuthorizeRequestData>
): OAuthAppsAuthorizeRequestData => ({
allow_partial_grants: false,
app_id: 'vercel',
name: 'Vercel',
website: 'https://vercel.com',
domain: 'vercel.com',
redirect_uri: 'https://vercel.com/api/integrations/supabase/callback',
registration_type: 'manual',
expires_at: '',
grant_kind: 'member_bound',
project_scoping_mode: true,
scopes: mockScopes,
...request,
})
const createMockOrganizationProjects = (projects?: Array<OrgProject>) => ({
projects: projects ?? [
createMockOrganizationProject({
ref: 'northwindstorefront1',
name: 'northwind-storefront',
}),
createMockOrganizationProject({
ref: 'northwindcms1',
name: 'northwind-cms',
}),
],
pagination: {
count: projects?.length ?? 0,
limit: 100,
offset: 0,
},
})
const createMockOrganizationProject = (project?: Partial<OrgProject>): OrgProject => ({
cloud_provider: '',
databases: [],
inserted_at: '',
integration_source: null,
is_branch: false,
name: '',
ref: '',
region: '',
status: 'ACTIVE_HEALTHY',
...project,
})
const createMockProject = (project?: Partial<ProjectDetail>): ProjectDetail => ({
cloud_provider: '',
connectionString: '',
db_host: '',
high_availability: false,
id: 1,
inserted_at: '',
integration_source: '',
is_branch_enabled: false,
is_physical_backups_enabled: false,
ref: 'northwindstorefront1',
name: 'northwind-storefront',
organization_id: 1,
region: '',
restUrl: '',
status: 'ACTIVE_HEALTHY',
subscription_id: '',
updated_at: '',
dbVersion: '',
...project,
})
const createMockPreflight = (
response?: Partial<OAuthAppsPreflightValidationData>
): OAuthAppsPreflightValidationData => ({
existing_grant: response?.existing_grant ?? null,
validation_failure: response?.validation_failure ?? null,
})
const renderAuthorize = (url = '/authorize') =>
renderRoute(Route, {
routeId: '/authorize',
url,
profileContext: createMockProfileContext(),
})
describe('/authorize', () => {
mockIntersectionObserver()
afterEach(() => {
flags.consent = false
document.title = ''
})
test('renders loading interstitial while the authorization request loads', async () => {
flags.consent = true
addAPIMock({
path: '/platform/oauth/authorizations/:id',
method: 'get',
response: () => new Promise<Response>(() => {}),
})
addAPIMock({
path: '/platform/organizations',
method: 'get',
response: () => HttpResponse.json<Organization[]>([]),
})
await renderAuthorize('/authorize?auth_id=some_id')
expect(screen.getByText('Loading...')).toBeInTheDocument()
})
test('renders the legacy component when the enableScopedOAuthConsent flag is off', async () => {
await renderAuthorize()
expect(screen.getByText('Missing authorization link')).toBeInTheDocument()
expect(screen.queryByText(/is connected/)).not.toBeInTheDocument()
})
test('does not let a draft preview parameter bypass the consent feature flag', async () => {
await renderAuthorize('/authorize?mock_scenario=trusted_partner_read')
expect(screen.getByText('Missing authorization link')).toBeInTheDocument()
expect(screen.queryByText('Example Partner')).not.toBeInTheDocument()
})
test('updates the document title with the requester name in the legacy authorize screen', async () => {
addAPIMock({
path: '/platform/oauth/authorizations/:id',
method: 'get',
response: () => HttpResponse.json<OAuthAppsAuthorizeRequestData>(createMockRequest()),
})
addAPIMock({
path: '/platform/organizations',
method: 'get',
response: () =>
HttpResponse.json<Organization[]>([
createMockOrganization({
slug: 'northwind-traders',
name: 'Northwind Traders',
}),
]),
})
await renderAuthorize('/authorize?auth_id=some_id')
await waitFor(() => {
expect(document.title).toBe('Authorize Vercel | Supabase')
})
})
test('correctly select the organization from the organization_slug', async () => {
flags.consent = true
addAPIMock({
path: '/platform/oauth/authorizations/:id',
method: 'get',
response: () => HttpResponse.json<OAuthAppsAuthorizeRequestData>(createMockRequest()),
})
addAPIMock({
path: '/platform/organizations',
method: 'get',
response: () =>
HttpResponse.json<Organization[]>([
createMockOrganization({
slug: 'anotherorg',
name: 'Another org',
}),
createMockOrganization({
id: 2,
slug: 'northwind-traders',
name: 'Northwind Traders',
}),
]),
})
addAPIMock({
path: '/platform/organizations/:slug/projects',
method: 'get',
response: () => HttpResponse.json<OrgProjectsResponse>(createMockOrganizationProjects()),
})
addAPIMock({
path: '/platform/organizations/:slug/oauth/authorizations/:id/preflight',
method: 'get',
response: () => HttpResponse.json<OAuthAppsPreflightValidationData>(createMockPreflight()),
})
addAPIMock({
path: '/platform/projects/:ref',
method: 'get',
response: () => HttpResponse.json<ProjectDetail>(createMockProject()),
})
await renderAuthorize('/authorize?auth_id=some_id&organization_slug=northwind-traders')
await screen.findByText('Northwind Traders')
})
test('preselects projects from repeated project_ref params', async () => {
flags.consent = true
addAPIMock({
path: '/platform/oauth/authorizations/:id',
method: 'get',
response: () => HttpResponse.json<OAuthAppsAuthorizeRequestData>(createMockRequest()),
})
addAPIMock({
path: '/platform/organizations',
method: 'get',
response: () =>
HttpResponse.json<Organization[]>([
createMockOrganization({
slug: 'northwind-traders',
}),
]),
})
addAPIMock({
path: '/platform/organizations/:slug/projects',
method: 'get',
response: () => HttpResponse.json<OrgProjectsResponse>(createMockOrganizationProjects()),
})
addAPIMock({
path: '/platform/organizations/:slug/oauth/authorizations/:id/preflight',
method: 'get',
response: () => HttpResponse.json<OAuthAppsPreflightValidationData>(createMockPreflight()),
})
addAPIMock({
path: '/platform/projects/:ref',
method: 'get',
response: () => HttpResponse.json<ProjectDetail>(createMockProject()),
})
await renderAuthorize(
'/authorize?auth_id=some_id&organization_slug=northwind-traders&project_ref=northwindstorefront1&project_ref=northwindcms1'
)
expect(await screen.findByText('northwind-storefront')).toBeInTheDocument()
})
test('normalises a single project_ref param to a one-item preselection', async () => {
flags.consent = true
addAPIMock({
path: '/platform/oauth/authorizations/:id',
method: 'get',
response: () => HttpResponse.json<OAuthAppsAuthorizeRequestData>(createMockRequest()),
})
addAPIMock({
path: '/platform/organizations',
method: 'get',
response: () =>
HttpResponse.json<Organization[]>([
createMockOrganization({
slug: 'northwind-traders',
}),
]),
})
addAPIMock({
path: '/platform/organizations/:slug/projects',
method: 'get',
response: () => HttpResponse.json<OrgProjectsResponse>(createMockOrganizationProjects()),
})
addAPIMock({
path: '/platform/organizations/:slug/oauth/authorizations/:id/preflight',
method: 'get',
response: () => HttpResponse.json<OAuthAppsPreflightValidationData>(createMockPreflight()),
})
addAPIMock({
path: '/platform/projects/:ref',
method: 'get',
response: () =>
HttpResponse.json<ProjectDetail>(
createMockProject({
ref: 'northwindcms1',
})
),
})
await renderAuthorize(
'/authorize?auth_id=some_id&organization_slug=northwind-traders&project_ref=northwindcms1'
)
expect(await screen.findByText('northwind-cms')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
})
})